PaganOS Luna 0.6.0
PL EN DE
🔒 Repository is read-only – file editing is disabled.

PaganLinux/tools/fix-kernel-depmod.py main

186 lines Raw ← Back
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
#!/usr/bin/env python3
"""Naprawia recepturę kernel: depmod z podwójnym /usr + brak /dev/null.

Problem (build 7.2.11):
    depmod -b ${PKGDIR}/usr -a $KERNELRELEASE
    -> depmod: ERROR: could not open directory .../usr/usr/lib/modules/7.2.11-pagan

kmod na Pagan/Arch ma wkompilowane /usr/lib/modules, więc `-b BASE` dokłada
BASE przed CAŁĄ ścieżką. `-b ${PKGDIR}/usr` daje ${PKGDIR}/usr/usr/lib/modules.
Ten sam błąd popełnia `make modules_install` (scripts/depmod.sh robi
`depmod -b $INSTALL_MOD_PATH`), dlatego wyłączamy jego depmod przez
DEPMOD=/bin/true i wołamy depmod raz, poprawnie.

Użycie (na VPS):
    python3 fix-kernel-depmod.py                 # tylko pokaż diff
    python3 fix-kernel-depmod.py --apply         # zapisz zmiany
    python3 fix-kernel-depmod.py --recipe /ścieżka/PAGBUILD.yaml [--apply]
"""

import argparse
import difflib
import glob
import re
import sys

DEFAULT_GLOBS = [
    "/var/lib/pagan-sync/recipes/utils/kernel/PAGBUILD.yaml",
    "/var/lib/pagan-sync/recipes/*/kernel/PAGBUILD.yaml",
    "/var/lib/pagan-sync/recipes/*/kernel-lts/PAGBUILD.yaml",
]

DEPMOD_BLOCK = r'''# ── depmod: NIE `-b ${PKGDIR}/usr` ─────────────────────────────────────
# kmod na Pagan/Arch ma wkompilowane /usr/lib/modules – `-b BASE` dokłada
# BASE przed CAŁĄ ścieżką, więc `-b ${PKGDIR}/usr` szuka
# ${PKGDIR}/usr/usr/lib/modules/<ver> i kończy się FATAL.
# `make modules_install` robi to samo (scripts/depmod.sh), dlatego w tej
# recepturze jest DEPMOD=/bin/true, a depmod wołamy raz, poprawnie.
# Dla hostów z kmod na /lib/modules tworzymy na czas depmod dowiązanie.
_lnk=""
if [ ! -e "${PKGDIR}/lib" ] && [ ! -L "${PKGDIR}/lib" ]; then
    ln -s usr/lib "${PKGDIR}/lib"
    _lnk="${PKGDIR}/lib"
elif [ -d "${PKGDIR}/lib" ] && [ ! -e "${PKGDIR}/lib/modules" ]; then
    ln -s ../usr/lib/modules "${PKGDIR}/lib/modules"
    _lnk="${PKGDIR}/lib/modules"
fi
depmod -b "${PKGDIR}" -a "${KERNELRELEASE}"
_rc=$?
if [ -n "$_lnk" ]; then rm -f "$_lnk"; fi
[ "$_rc" -eq 0 ] || { echo "BŁĄD: depmod nie powiódł się (${PKGDIR}/usr/lib/modules/${KERNELRELEASE})" >&2; exit 1; }'''

PREFLIGHT = ('[ -c /dev/null ] || { echo "BŁĄD: brak /dev/null – wykonaj: '
             'sudo mknod -m 666 /dev/null c 1 3 (albo zrestartuj system)" >&2; exit 1; }')


def find_recipe(explicit: str) -> str:
    if explicit:
        return explicit
    for pat in DEFAULT_GLOBS:
        hits = sorted(glob.glob(pat))
        if hits:
            return hits[0]
    sys.exit("Nie znaleziono receptury kernel. Podaj --recipe ŚCIEŻKA.")


def add_preflight(text: str) -> tuple[str, bool]:
    """Wstawia kontrolę /dev/null na początek bloku `build: |`."""
    if "brak /dev/null" in text:
        return text, False

    lines = text.splitlines(keepends=True)
    out, done = [], False
    for i, line in enumerate(lines):
        out.append(line)
        if done:
            continue
        m = re.match(r'^(\s*)build:\s*\|\s*$', line.rstrip("\n"))
        if not m:
            continue
        key_indent = m.group(1)
        # Wcięcie treści: pierwsza niepusta linia po `build: |`.
        body_indent = key_indent + "  "
        for nxt in lines[i + 1:]:
            if nxt.strip():
                lead = nxt[:len(nxt) - len(nxt.lstrip())]
                if len(lead) > len(key_indent):
                    body_indent = lead
                break
        out.append(f"{body_indent}{PREFLIGHT}\n")
        done = True
    return "".join(out), done


def disable_make_depmod(text: str) -> tuple[str, int]:
    """Ustawia DEPMOD=/bin/true dla modules_install.

    `DEPMOD=/dev/null` (taka wartość była w recepturze kernel 7.2.11) jest
    błędne: make próbuje wykonać /dev/null jako program. Poprawna wartość
    to /bin/true.
    """
    lines = text.splitlines(keepends=True)
    out, n = [], 0
    for line in lines:
        if line.lstrip().startswith("#"):
            out.append(line)
            continue
        if "DEPMOD=/dev/null" in line:
            line = line.replace("DEPMOD=/dev/null", "DEPMOD=/bin/true")
            n += 1
        if "modules_install" in line and "DEPMOD=" not in line:
            line = line.replace("modules_install", "modules_install DEPMOD=/bin/true", 1)
            n += 1
        out.append(line)
    return "".join(out), n


def fix_depmod(text: str) -> tuple[str, bool]:
    """Zamienia `depmod -b ${PKGDIR}/usr ...` na poprawny blok (z zachowaniem wcięcia)."""
    if '_lnk="${PKGDIR}/lib"' in text:
        return text, False

    pat = re.compile(
        r'(?m)^([ \t]*)depmod\s+-b\s+["\']?\$\{PKGDIR\}/usr/?["\']?\s+'
        r'-a\s+["\']?\$KERNELRELEASE["\']?[ \t]*\n'
    )
    m = pat.search(text)
    if not m:
        return text, False

    indent = m.group(1)
    block = "".join(f"{indent}{ln}\n" for ln in DEPMOD_BLOCK.splitlines())
    return text[:m.start()] + block + text[m.end():], True


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--recipe", default="")
    ap.add_argument("--apply", action="store_true")
    args = ap.parse_args()

    path = find_recipe(args.recipe)
    src = open(path, encoding="utf-8").read()
    out = src

    out, pf = add_preflight(out)
    out, mi = disable_make_depmod(out)
    out, dd = fix_depmod(out)

    print(f"receptura: {path}")
    print(f"  preflight /dev/null : {'DODANY' if pf else 'już jest / nie znaleziono build: |'}")
    print(f"  modules_install     : {mi} linii z DEPMOD=/bin/true")
    print(f"  depmod -b           : {'POPRAWIONY' if dd else 'już poprawny / nie znaleziono'}")
    print()

    if out == src:
        print("Bez zmian.")
        return 0

    if "depmod -b" in out and '_lnk="${PKGDIR}/lib"' not in out:
        print("UWAGA: w recepturze nadal jest depmod -b bez poprawki – sprawdź ręcznie.",
              file=sys.stderr)

    try:
        import yaml
        yaml.safe_load(out)
        print("YAML: OK")
    except ImportError:
        print("YAML: pominięta walidacja (brak modułu yaml)")
    except Exception as e:
        print(f"YAML: BŁĄD – {e}", file=sys.stderr)
        return 1

    print("\n".join(difflib.unified_diff(
        src.splitlines(), out.splitlines(),
        fromfile=path, tofile=path + " (po poprawce)", lineterm="")))

    if args.apply:
        open(path, "w", encoding="utf-8").write(out)
        print(f"\nZapisano: {path}")
    else:
        print("\n(dry-run – dodaj --apply, aby zapisać)")
    return 0


if __name__ == "__main__":
    sys.exit(main())