import os
import re
import shutil

recipe_dir = "recipes"
backup_dir = "recipes_backup"

# make backup folder if not exists
os.makedirs(backup_dir, exist_ok=True)

# backup all recipes first
for file in os.listdir(recipe_dir):
    if file.endswith(".recipe.py"):
        shutil.copy(os.path.join(recipe_dir, file), os.path.join(backup_dir, file))

# now patch recipes
for file in os.listdir(recipe_dir):
    if not file.endswith(".recipe.py"):
        continue

    path = os.path.join(recipe_dir, file)
    text = open(path).read()

    # skip if already uses DESTDIR
    if "DESTDIR" in text:
        continue

    # only patch recipes that use "make install"
    if "make install" not in text:
        continue

    # safely replace "make install" with "make DESTDIR=... install"
    text = re.sub(r"make install", "make DESTDIR={destdir} install", text)

    # insert the three vars after fembuilddir definition
    if "fembuilddir" in text and "outputdir" not in text:
        lines = text.splitlines()
        for i, line in enumerate(lines):
            if "fembuilddir" in line:
                lines.insert(i + 1, 'outputdir = "/home/gabry/lfs-repo/binpkg"')
                lines.insert(i + 2, 'manifestdir = "/home/gabry/lfs-repo/manifests"')
                lines.insert(i + 3, 'destdir = f"{fembuilddir}/DESTDIR"')
                break
        text = "\n".join(lines)

    # correctly inject tarball + manifest lines before "# Cleanup"
    text = re.sub(
        r"# Cleanup",
        (
            "# Make tarball + manifests\n"
            "    f\"mkdir -p {outputdir} && cd {destdir} && "
            "tar --transform 's|^\\\\\\\\.||' -I zstd -cf {outputdir}/{pkgname}-{pkgver}.tar.zst .\",\n"
            "    f\"mkdir -p {manifestdir} && tar -tf {outputdir}/{pkgname}-{pkgver}.tar.zst "
            "| grep -v '/$' > {manifestdir}/{pkgname}.txt\",\n\n"
            "# Cleanup"
        ),
        text
    )

    with open(path, "w") as f:
        f.write(text)

    print(f"patched: {file}")
