#!/usr/bin/python3
"""linuxdoors-update-grub -- boot the newest LinuxDoors kernel, keep the last working one.

Rewrites /boot/grub/grub.cfg on an installed LinuxDoors system so that it has:
  * entry 0 "LinuxDoors": the newest stock kernel (/boot/vmlinuz-<release>-linuxdoors
    whose /lib/modules/<release> is present) -- the default;
  * entry 1 "LinuxDoors (kernel X -- previous)": the PREVIOUS WORKING kernel, i.e.
    the kernel the machine was running when the new one arrived. `set fallback=1`
    makes GRUB start it by itself if the new kernel fails to load. Once the machine
    has booted the new kernel, the previous entry is kept as it is, so it always
    names a kernel this machine has really run;
  * kernels built with LinuxDoors Kernel Config (release ending -customN) as their
    own "Custom Kernel" entries, never made the default;
  * menu entries that don't boot a LinuxDoors kernel (another OS, etc.) unchanged.
Older stock kernels stay on disk but get no menu entry.

The kernel command line (root=, rw, console, init, ...) is taken from the current
default entry, or from --cmdline when there is no grub.cfg yet.

It will NOT move the default away from the running kernel when that kernel has
out-of-tree modules (e.g. the NVIDIA proprietary driver) that the newer kernel
lacks. It does nothing at all when /etc/linuxdoors/no-auto-kernel exists, or on
the live ISO. The old grub.cfg is saved as grub.cfg.ldbak before every change.

Run by: the LinuxDoors installer, the package manager after a kernel install,
and linuxdoors-update-grub.service at boot and again at shutdown (so the restart
after `pkg upgrade` already starts the new kernel, even with an older package
manager that has no after-install hook).

  linuxdoors-update-grub [--root DIR] [--cmdline "root=... rw ..."] [--dry-run]
"""
import argparse
import os
import re
import shutil
import subprocess
import sys

STOCK_RE = re.compile(r"^vmlinuz-(\d+(?:\.\d+)*)-linuxdoors$")
ANY_RE = re.compile(r"^vmlinuz-(.+)-linuxdoors$")
OOT_DIRS = ("extra", "updates", "video")
HEADER = ("insmod part_gpt\n"
          "insmod part_msdos\n"
          "insmod ext2\n"
          "insmod normal\n\n"
          "set timeout=5\n"
          "set default=0\n")


def vkey(release):
    return tuple(int(x) for x in re.findall(r"\d+", release))


def out_of_tree_modules(root, release):
    """Module file names under extra/, updates/ or kernel/drivers/video/nvidia*."""
    names = set()
    base = os.path.join(root, "lib/modules", release)
    for d in OOT_DIRS:
        for top in (os.path.join(base, d), os.path.join(base, "kernel/drivers", d)):
            if not os.path.isdir(top):
                continue
            for dirpath, _, files in os.walk(top):
                for f in files:
                    if ".ko" in f and (d != "video" or f.startswith("nvidia")):
                        names.add(f)
    return names


def split_entries(text):
    """Return (header_text, [entry_text, ...]) for top-level menuentry blocks."""
    entries, i, header_end = [], 0, None
    for m in re.finditer(r"^menuentry\b", text, re.M):
        if m.start() < i:
            continue
        if header_end is None:
            header_end = m.start()
        depth, j = 0, text.index("{", m.start())
        while j < len(text):
            if text[j] == "{":
                depth += 1
            elif text[j] == "}":
                depth -= 1
                if depth == 0:
                    break
            j += 1
        entries.append(text[m.start():j + 1])
        i = j + 1
    return (text if header_end is None else text[:header_end]), entries


def entry_kernel(entry):
    """The /boot/vmlinuz-*-linuxdoors file an entry boots, or None."""
    m = re.search(r"^\s*linux\s+/boot/(vmlinuz-\S+-linuxdoors)\b", entry, re.M)
    return m.group(1) if m else None


def kernel_args(entry):
    m = re.search(r"^\s*linux\s+/boot/\S+\s+(.*)$", entry, re.M)
    return m.group(1).strip() if m else None


def entry(title, kernel, args):
    return f'menuentry "{title}" {{\n    linux /boot/{kernel} {args}\n}}'


def with_fallback(header, fallback):
    """Header with exactly one `set fallback=` line (or none)."""
    lines = [l for l in header.rstrip("\n").split("\n") if not re.match(r"^\s*set\s+fallback=", l)]
    if fallback is not None:
        at = next((i + 1 for i, l in enumerate(lines) if re.match(r"^\s*set\s+default=", l)), len(lines))
        lines.insert(at, f"set fallback={fallback}")
    return "\n".join(lines) + "\n"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default="/")
    ap.add_argument("--cmdline", default=None)
    ap.add_argument("--dry-run", action="store_true")
    a = ap.parse_args()
    root = a.root
    cfg_path = os.path.join(root, "boot/grub/grub.cfg")

    if os.path.exists(os.path.join(root, "etc/linuxdoors/no-auto-kernel")):
        print("linuxdoors-update-grub: /etc/linuxdoors/no-auto-kernel present, leaving GRUB alone")
        return 0
    if root == "/":
        fs = subprocess.run(["findmnt", "-n", "-o", "FSTYPE", "/"],
                            capture_output=True, text=True).stdout.strip()
        if fs in ("overlay", "squashfs", "tmpfs"):
            print("linuxdoors-update-grub: live session, nothing to do")
            return 0

    stock, custom = [], []
    for f in os.listdir(os.path.join(root, "boot")):
        m = ANY_RE.match(f)
        if not m or not os.path.isdir(os.path.join(root, "lib/modules", m.group(1))):
            continue
        (stock if STOCK_RE.match(f) else custom).append((m.group(1), f))
    if not stock and not custom:
        print("linuxdoors-update-grub: no kernel with modules found in /boot, not touching GRUB", file=sys.stderr)
        return 1
    stock.sort(key=lambda r: vkey(r[0]), reverse=True)
    custom.sort(key=lambda r: vkey(r[0]), reverse=True)
    by_file = {k: (rel, k) for rel, k in stock + custom}

    old_text = open(cfg_path, encoding="utf-8").read() if os.path.isfile(cfg_path) else ""
    header, old_entries = split_entries(old_text)
    keep = [e for e in old_entries if not entry_kernel(e)]
    old_ld = [entry_kernel(e) for e in old_entries if entry_kernel(e)]   # kernels in menu order
    args = a.cmdline
    if not args:
        for e in old_entries:
            if entry_kernel(e) and kernel_args(e):
                args = kernel_args(e)
                break
    if not args:
        print("linuxdoors-update-grub: no kernel command line (root=...) known; pass --cmdline", file=sys.stderr)
        return 1

    ordered = stock or custom
    newest = ordered[0]
    default = newest
    # LDUG_RUNNING lets tests stand in for the running kernel on a --root tree.
    running_rel = os.environ.get("LDUG_RUNNING") or (os.uname().release if root == "/" else None)
    running = next((r for r in stock + custom if r[0] == running_rel), None)
    # Keep the running kernel as default if it carries out-of-tree drivers the
    # newer one lacks (e.g. NVIDIA proprietary on a machine running CUDA).
    if running and running != newest and running in ordered:
        missing = out_of_tree_modules(root, running[0]) - out_of_tree_modules(root, newest[0])
        if missing:
            print(f"linuxdoors-update-grub: keeping {running[0]} as default -- it has "
                  f"out-of-tree modules {sorted(missing)} that {newest[0]} lacks")
            default = running

    # The previous working kernel: the one running now, if it isn't the default
    # (a new kernel has just arrived, or the default was held back). Otherwise --
    # we are already running the default -- keep the previous kernel this menu
    # already names, or, on a first run, the next-newest stock kernel.
    previous = None
    if running and running != default:
        previous = running
    else:
        for k in old_ld[1:] + old_ld[:1]:
            if k in by_file and by_file[k] != default and by_file[k] in stock:
                previous = by_file[k]
                break
        if previous is None:
            previous = next((r for r in stock if r != default), None)

    blocks = [entry("LinuxDoors", default[1], args)]
    if previous:
        blocks.append(entry(f"LinuxDoors (kernel {previous[0]} -- previous)", previous[1], args))
    for rel, k in custom:
        if (rel, k) not in (default, previous):
            blocks.append(entry(f"LinuxDoors (Custom Kernel {rel})", k, args))
    blocks += keep

    hdr = HEADER if not header.strip() else header
    new_text = with_fallback(hdr, 1 if previous else None) + "\n" + "\n\n".join(blocks) + "\n"
    print(f"linuxdoors-update-grub: default kernel {default[0]}"
          + (f", previous {previous[0]}" if previous else "")
          + f" ({len(blocks)} menu entr{'y' if len(blocks) == 1 else 'ies'})")
    if new_text == old_text:
        print("linuxdoors-update-grub: grub.cfg already up to date")
        return 0
    if a.dry_run:
        print(new_text)
        return 0
    if root == "/" and shutil.which("grub-script-check"):
        chk = subprocess.run(["grub-script-check"], input=new_text, text=True, capture_output=True)
        if chk.returncode != 0:
            print("linuxdoors-update-grub: new grub.cfg failed grub-script-check, not changing it:\n"
                  + chk.stdout + chk.stderr, file=sys.stderr)
            return 1
    os.makedirs(os.path.dirname(cfg_path), exist_ok=True)
    if old_text:
        shutil.copy2(cfg_path, cfg_path + ".ldbak")
    tmp = cfg_path + ".ldnew"
    with open(tmp, "w", encoding="utf-8") as f:
        f.write(new_text)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, cfg_path)
    return 0


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