#!/usr/bin/env python3
# summary: List restore points and read recovery status.
"""starchaser recovery: what Settings > Recovery shows, read without root.

    starchaser recovery last     JSON: the last recovery result, kept across restarts
    starchaser recovery last-dismiss <time>    dismiss that result
                                 Use now to dismiss the current result: starchaser recovery last-dismiss now
                                 Scripts can use the exact time value from last, including any decimal places.
    starchaser recovery list     JSON: the snapshots, newest first, in plain words ("Before installing
                                 VLC and 3 system parts"), each with what changed then and what going back to
                                 it would undo, plus whether snapshots are set up, whether the boot menu can
                                 start one, and the free disk space
    starchaser recovery run KIND TIME ARGS...   start that go-back or snapshot (it asks for your password),
                                 in its own session so it keeps running even when Settings closes this command; the
                                 answer is printed and kept for job, and this ends as the go-back itself did
                                 This is what Settings > Recovery runs; use that page for everyday recovery.
                                 KIND is a short label for the job: undo, create, delete, boot or unlock.
                                 TIME is the snapshot's time from list for an undo; use 0 for the others.
                                 ARGS is the action and what it needs:
                                   recovery-undo NUMBER      go back to snapshot NUMBER (from list)
                                   recovery-create [NAME]    take a snapshot now
                                   recovery-delete NUMBER    delete a snapshot you took by hand
                                   recovery-boot             rebuild the startup files
                                   recovery-update-undo NUMBER   undo that update (use KIND restore)
                                   pacman-unlock             clear a leftover software-install lock
                                 Example: starchaser recovery run create 0 recovery-create "Before my change"
    starchaser recovery job      JSON: that record ({} when there is none); a "running" job whose runner is gone
                                 reads as done, with no answer
    starchaser recovery job-seen [ID]   marks that answer (or, with no ID, the finished one) as shown
    starchaser recovery booted   JSON: the snapshot this computer started from in the boot menu ("booted", or null)
                                 and the snapshots the boot menu lists
    starchaser recovery snapshot-go-back   started from a snapshot: go back to it (asks for your password), then
                                 switch the system from this session, then restart once
    starchaser recovery restart-normally   started from a snapshot: restart into the normal system
    starchaser recovery notice   at sign-in: after starting from a snapshot, a notice offering those two; after a
                                 go-back chosen that way, its result
Going back and taking a snapshot ask for your password.
"""
# Restore points are snapper snapshots; what changed comes from pacman.log. Going back and taking one go through
# `pkexec /usr/local/lib/starchaser/starchaser-admin recovery-...`. Reading needs snapper's ALLOW_GROUPS to
# include wheel (the desktop setup sets it). `run` passes its words to that helper, records the answer in
# $XDG_RUNTIME_DIR/starchaser-recovery-job.json, and exits with the helper's code.
import ast
import fcntl
import functools
import json
import os
import re
import shutil
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams
safe_streams()

# pacman's lock left by a crash or power cut: going back refuses while it's there, so the page says so up front and
# offers to clear it. The rule lives in updater.py (the root helper's copy); without it, never "stale".
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "updater.py").is_file():
        sys.path.insert(0, str(_lib))
        break
try:
    from updater import pacman_lock_state
except ImportError:
    def pacman_lock_state() -> str:
        return "busy" if Path("/var/lib/pacman/db.lck").exists() else ""
try:
    import bootsnap
except ImportError:
    bootsnap = None

PACLOG = Path("/var/log/pacman.log")
CONFIG = Path("/etc/snapper/configs/root")
INSTALL_LOG = Path("/var/log/starchaser-install.log")
# app names seen on earlier runs, so an app that has since been removed is still named ("Before removing VLC")
NAME_CACHE = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "starchaser" / "app-names.json"
# package names that would put another project's name on screen: those stay "a system part"
# packages that AUR builds needed and Settings removed again afterward (updater.py writes it): going back to a
# snapshot from mid-build puts them back, and the page says "build tools" for those instead of "system parts"
BUILD_TOOLS = Path("/var/lib/starchaser/build-tools.json")
# (cockpit: Mission Control's web server, a name that also clashes with the taskbar's; its add-ons stay system parts)
FOREIGN = re.compile(r"gnome|kde|plasma|^kf\d|xfce|cachyos|manjaro|endeavour|garuda|^arch|cockpit", re.I)
# Helpers Starchaser installs for one of its features. They have no menu entry, so without this a snapshot taken when
# one was installed alone said "Before installing hyprsunset". Named for the feature they serve, and treated like
# apps everywhere (titles, what going back removes). A menu entry's own name wins unless TITLE_ALIASES names it.
FEATURES = {"hyprland": "the desktop", "hyprsunset": "the night light helper", "sunshine": "remote desktop sharing",
            "tailscale": "the away-from-home connection", "archlinux-appstream-data": "the app search listings",
            "snap-pac": "automatic snapshots", "opensnitch": "the outgoing connection guard",
            "flatpak": "Flathub app support", "cups": "printing support", "bluez": "Bluetooth support",
            # setup's own helpers with no menu entry (a computer that gets them later, from an update of Starchaser)
            "wtype": "the emoji typing helper", "unicode-emoji": "the emoji list",
            "unicode-character-database": "the character list", "usbutils": "the USB device list tool",
            "pciutils": "the hardware list tool", "cliphist": "the clipboard history", "wl-clipboard": "copy and paste support",
            "grim": "the screenshot tool", "slurp": "the screen area picker", "gpu-screen-recorder": "the screen recorder",
            "brightnessctl": "the brightness control", "playerctl": "the media key helper", "ethtool": "Wake on LAN support",
            "usbguard": "the USB device guard", "gamemode": "Game mode", "lib32-gamemode": "Game mode (for 32-bit games)",
            "scx-scheds": "Game mode's speed settings", "scx-tools": "Game mode's speed settings switcher",
            "steam-devices": "game controller support", "sound-theme-freedesktop": "the system sounds",
            "power-profiles-daemon": "power modes", "avahi": "finding devices on your network",
            # Mission Control's web server and the two helpers setup installs with it
            "cockpit": "Mission Control support", "udisks2": "the disk details service", "bubblewrap": "the app sandbox tool",
            "mpv-mpris": "the video player's media controls",
            # the names Updates and Software use for these too (bin/starchaser-updates LABELS), so one package reads
            # the same on all three pages
            "amd-ucode": "the processor fixes (AMD)", "intel-ucode": "the processor fixes (Intel)",
            # the component's own name meant nothing to a first-time user ("Returns Quickshell and 2 system parts");
            # Updates calls it "Desktop shell" too
            "quickshell": "the desktop shell (taskbar and menus)"}
TITLE_ALIASES = {"hyprland": "the desktop", "mousepad": "Text editor", "gspell": "Spelling support", "hyprsunset": "Night light",
                 "xterm": "XTerm",  # the package also owns UXTerm's launcher, which sorts before XTerm's
                 # the Terminal while the screen reader runs, which setup installs everywhere: its menu entry's own
                 # name ("Xfce Terminal") titled every new install's first snapshot (decided 2026-11-07 #33: "Terminal")
                 "xfce4-terminal": "Terminal",
                 # the projects' own spellings: the plain fallback would write "Espeak ng" and "Speech dispatcher"
                 "espeak-ng": "eSpeak NG", "speech-dispatcher": "Speech Dispatcher",
                 # Updates calls it this too; "Starchaser Starfield" is the component's own name
                 "starchaser-starfield": "Starfield screensaver",
                 # one of the menu entries it owns (Mission Control) isn't what a desktop update changed (QA 20261106-2244 008)
                 "starchaser-desktop": "Starchaser Linux (desktop, Settings and tools)",
                 # Updates' and the boot menu's words: two kernels from Update now read "2 software items"
                 "linux-starchaser": "Starchaser kernel", "linux-starchaser-v3": "Starchaser kernel",
                 "linux-starchaser-lts": "Starchaser LTS kernel"}
# Bundled terminal helpers: explain snapshot titles without changing explicit-package confirmation names.
TITLE_ONLY_ALIASES = {"gptfdisk": "Disk partition tools", "exfatprogs": "exFAT drive tools",
                      "fzf": "Terminal search helper", "bash-completion": "Terminal command completion"}


def sh(*cmd) -> subprocess.CompletedProcess:
    return subprocess.run(cmd, capture_output=True, text=True, env={"LANG": "C.UTF-8", "PATH": "/usr/bin:/bin"})


def when(s: str) -> float:
    try:
        return datetime.strptime(s, "%Y-%m-%d %H:%M:%S").timestamp()
    except ValueError:
        return 0


def paclog() -> list:
    """The package changes, one list per pacman transaction ("transaction started" to the next one):
    [{"start": time, "pre": snapshot number or None, "changes": [(time, action, package, detail)]}]. Grouping by
    transaction (rather than by a time window around the snapshot) keeps an earlier install from the same second out
    of the next snapshot's list. snap-pac's pre hook prints the number it took ("==> root: 93") just before the
    transaction starts, so where that line is there, the transaction is tied to its snapshot exactly."""
    out = []
    try:
        lines = PACLOG.read_text(errors="replace").splitlines()[-60000:]
    except OSError:
        return out
    hook, pre, command = "", None, ""
    for l in lines:
        run = re.match(r"\[[^\]]+\] \[PACMAN\] Running '(.*)'$", l)
        if run:
            command = run[1]
            continue
        m = re.match(r"\[(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)[^\]]*\] \[ALPM(-SCRIPTLET)?\] (.*)", l)
        if not m:
            continue
        msg = m.group(3)
        if m.group(2):
            n = re.match(r"==> root: (\d+)$", msg.strip())
            if n and "snap-pac-pre" in hook:
                pre = int(n.group(1))
            continue
        h = re.match(r"running '(.*)'\.\.\.$", msg)
        if h:
            hook = h.group(1)
            continue
        t = datetime.strptime(m.group(1), "%Y-%m-%dT%H:%M:%S").timestamp()
        if msg == "transaction started" or not out:
            out.append({"start": t, "pre": pre if msg == "transaction started" else None, "command": command, "changes": []})
            pre = None
            if msg == "transaction started":
                continue
        c = re.match(r"(upgraded|installed|removed|downgraded|reinstalled) (\S+) \((.*)\)", msg)
        if c:
            out[-1]["changes"].append((t, c.group(1), c.group(2), c.group(3)))
    return out


def app_names() -> dict:
    """package -> the app name people see (Name= of a desktop file it owns), for the packages that have one."""
    files = [f for d in ("/usr/share/applications",) for f in sorted(Path(d).glob("*.desktop"))]
    names = {}
    for f in files:
        try:
            txt = f.read_text(errors="replace")
        except OSError:
            continue
        entry = txt.split("[Desktop Entry]", 1)[-1].split("\n[", 1)[0]
        if re.search(r"(?m)^NoDisplay\s*=\s*true", entry):
            continue
        m = re.search(r"(?m)^Name\s*=\s*(.+)$", entry)
        if m:
            names[str(f)] = m.group(1).strip()
    out = {}
    if names:
        r = sh("pacman", "-Qo", *names)
        for l in r.stdout.splitlines():
            m = re.match(r"(.*) is owned by (\S+) \S+$", l)
            if m and m.group(1) in names:
                out.setdefault(m.group(2), names[m.group(1)])
    # merge with the names remembered from earlier runs (installed apps win), and remember the result
    try:
        cached = json.loads(NAME_CACHE.read_text())
        cached = {k: v for k, v in cached.items() if isinstance(k, str) and isinstance(v, str)} if isinstance(cached, dict) else {}
    except (OSError, ValueError):
        cached = {}
    merged = {**cached, **out}
    if merged != cached:
        try:
            NAME_CACHE.parent.mkdir(parents=True, exist_ok=True)
            tmp = NAME_CACHE.with_suffix(".tmp")
            tmp.write_text(json.dumps(merged, sort_keys=True))
            tmp.replace(NAME_CACHE)
        except OSError:
            pass
    return merged


# Software's app catalog, in the order Software reads it (bin/starchaser-software CATALOG)
CATALOG = [Path.home() / ".config/starchaser/software/catalog.json",
           Path(__file__).resolve().parent.parent / "config/software/catalog.json",
           Path("/usr/share/starchaser/software/catalog.json")]


def catalog_names() -> dict:
    """package -> the name Software's card gave it ("aisleriot" -> "Solitaire"), so a snapshot names an app the way
    the person picked it, not by its menu entry ("Before installing AisleRiot Solitaire": QA 20261104-1847 004)."""
    for p in CATALOG:
        try:
            apps = json.loads(p.read_text()).get("apps")
        except (OSError, ValueError, AttributeError):
            continue
        if not isinstance(apps, list):
            continue
        out = {}
        for a in apps:
            if not isinstance(a, dict) or not isinstance(a.get("name"), str) or not isinstance(a.get("sources"), list):
                continue
            for src in a["sources"]:
                if isinstance(src, list) and len(src) == 2 and src[0] == "repo" and isinstance(src[1], str):
                    out.setdefault(src[1], a["name"])
        return out
    return {}


# Software itself, beside this tool: its Installed list names some apps outside the catalog (INSTALLED_TITLES)
SOFTWARE = Path(__file__).resolve().parent / "starchaser-software"


def software_titles() -> dict:
    """package -> the name Software's Installed list shows when it isn't the catalog's or the menu entry's
    ("kshisen" -> "KShisen", never "Shisen-Sho": QA 20261105-0841 001). Read from Software's own table, not run."""
    try:
        tree = ast.parse(SOFTWARE.read_text())
    except (OSError, SyntaxError, ValueError):
        return {}
    for node in tree.body:
        if isinstance(node, ast.Assign) and any(getattr(t, "id", "") == "INSTALLED_TITLES" for t in node.targets):
            try:
                titles = ast.literal_eval(node.value)
            except ValueError:
                return {}
            if isinstance(titles, dict):
                return {k: v for k, v in titles.items() if isinstance(k, str) and isinstance(v, str)}
    return {}


def pkgdb(root: str) -> dict | None:
    """package -> version, from the package database under root ("/" for now, a snapshot's own copy for then).
    None when it can't be read. Going back restores this database (it's part of the system), but not pacman.log
    (a separate subvolume), so after a go-back only the database says what is really installed."""
    out = {}
    try:
        with os.scandir(Path(root) / "var/lib/pacman/local") as it:
            for e in it:
                parts = e.name.rsplit("-", 2)     # name-version-release: version and release never hold a "-"
                if len(parts) == 3 and e.is_dir():
                    out[parts[0]] = parts[1] + "-" + parts[2]
    except OSError:
        return None
    return out or None


def few(names: list, parts: int, others: int = 0, unnamed: int = 0) -> str:
    """"VLC, Steam and 3 system parts": apps by name, everything else counted, never raw library names. Past three
    names, the rest of the names are counted apart from the system parts ("VLC, Steam, Thunar, 2 other programs
    and a system part"), so the count always says what it counts. others: programs that came along unnamed (counted
    with the names past three)."""
    remainder = max(0, len(names) - 3) + others + unnamed + parts
    if len(names) >= 3 and remainder >= 10:
        return ', '.join(names[:3]) + f' and {remainder} more'
    extra = max(0, len(names) - 3) + others
    items = names[:3] + (["1 software item" if unnamed == 1 else f"{unnamed} software items"] if unnamed else []) + \
        (["1 other program" if extra == 1 else f"{extra} other programs"] if extra > 0 else []) + \
        (["a system part" if parts == 1 else f"{parts} system parts"] if parts else [])
    return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]


def display(p: str, apps: dict) -> str:
    """The name a package is shown by: its app or feature name, else the package name the way Software writes a repo
    package ("ed" -> "Ed", "fortune-mod" -> "Fortune mod"). Plain aliases come first, in titles and changes alike. No AUR
    suffix stripping (Software's -bin/-git): Recovery doesn't know where a package came from, and a repo package
    could lose part of its real name."""
    if p in TITLE_ALIASES:
        return TITLE_ALIASES[p]
    if apps.get(p):
        return apps[p]
    n = p.replace("-", " ")
    return n[:1].upper() + n[1:]


def recovery_destination(snapshot: dict) -> str:
    try:
        return bytes.fromhex((snapshot.get("userdata") or {}).get("recovery_name", "")).decode("utf-8")
    except (ValueError, UnicodeDecodeError):
        return ""


def title(pre: dict, changes: list, apps: dict) -> str:
    """Plain words from what actually changed; never snapper's own description (the pacman command line)."""
    d = pre.get("description") or ""
    if tag(pre) == "full-update":
        return "Before the full system update"
    if pre.get("type") == "single":
        # one taken with Take a snapshot now: its description was "Made by you" (older ones, and the subtitle says
        # who made it), so the title says what it is instead of repeating that
        if tag(pre) == "hand" and d in ("", "Made by you", "Snapshot you took"):
            return "Snapshot you took"
        if tag(pre) == "hand":          # a name typed in Settings > Recovery: shown as typed, whatever words it uses
            return d
        # a safety snapshot's name is always Starchaser's own words, but it can carry a name you typed ("Before going
        # back to “QA snapshot” (Oct 9, 8:05 PM)"). Keep the typed name, with consistent outer quotes for older copies.
        if tag(pre) == "safety" and d.startswith("Before going back"):
            old = re.fullmatch(r"Before going back to ‘(.*)’( \(.*\))?", d)
            if old:
                return f"Before going back to “{old[1]}”{old[2] or ''}"
            return d
        return "An earlier snapshot" if not d or FOREIGN.search(d) else d
    n = len(changes)
    if not n:
        return "Before an update" if re.search(r"\s-S[a-z]*u", d) else "Before a software change"
    acts = {c["action"] for c in changes}
    # the tools an AUR build needed, installed just for the build (and removed again after it)
    if acts <= {"installed"} and {c["package"] for c in changes} <= build_tools():
        return "Before installing helpers for setting up an app"
    # apps by name; without one, the package the person asked for by name (it's on the command line), or the only one
    asked = set(d.split())
    shown = [c["package"] for c in changes if c["package"] in apps or
             ((c["package"] in asked or n == 1) and not FOREIGN.search(c["package"]))]
    # what the person chose comes first, and alone by name: an app that only came along with it (SpeedCrunch brings
    # qt6-tools, whose menu entry is "Qt Assistant") is counted as another program, not named ahead of the one picked
    # ("Before installing Qt Assistant, SpeedCrunch and 2 system parts"). Only when the command line
    # still names a package installed or removed here (snap-pac can cut it short): otherwise every app is named.
    chosen = [p for p in shown if p in asked and any(c["package"] == p and c["action"] in ("installed", "removed")
                                                     for c in changes)]
    others = 0
    if chosen:
        others = sum(1 for p in shown if p not in chosen)
        shown = chosen
    # A batch of requested packages may have no app names. Count those items instead of turning their identifiers
    # into names. Single requested programs keep their familiar name, and exact packages remain in Show changes.
    unnamed = [p for p in shown if len(shown) > 1 and p not in apps and p not in TITLE_ALIASES and p not in TITLE_ONLY_ALIASES]
    named = list(dict.fromkeys(TITLE_ONLY_ALIASES.get(p, display(p, apps)) for p in shown if p not in unnamed))
    what = few(named, n - len(shown) - others, others, len(unnamed))
    # built here = Settings' own AUR install (its pacman command, or the build folder in the path); a downloaded
    # prebuilt package installed with -U (setup's Sunshine) wasn't built here. snap-pac cuts the description short,
    # so the path may be missing: Settings' pacman options are the other sign.
    built = " (built on this computer)" if " -U " in d and (
        "/.cache/starchaser/aur/" in d or ("--noprogressbar" in d and "/var/cache/" not in d)) else ""
    if re.search(r"\s-S[a-z]*u", d) or (acts & {"upgraded", "downgraded"} and n > 3):
        return f"Before updating {n} parts of the system" if n > 1 else f"Before updating {what}"
    if acts <= {"removed"}:
        return f"Before removing {what}"
    if acts <= {"installed"}:
        return f"Before installing {what}{built}"
    if acts <= {"downgraded"}:          # an older version put back: the changes list says so (style guide: never "roll back")
        return f"Before putting back an older {what}{built}"
    if acts <= {"upgraded", "downgraded", "reinstalled"}:
        return f"Before updating {what}{built}"
    return f"Before changing {what}{built}"


def asked_for(root: str | None, p: str, version: str) -> bool:
    """Was package p installed because someone asked for it by name (pacman's "explicitly installed"), rather than
    pulled in by another package? Read from its own entry in the package database under root (the live one for a
    package there now, the snapshot's for one going back). A package with no %REASON% line was asked for; reason 1
    means it came along as a dependency. Unreadable (or no database to read): not asked for, so it stays counted."""
    if root is None:
        return False
    try:
        desc = (Path(root) / "var/lib/pacman/local" / f"{p}-{version}" / "desc").read_text(errors="replace")
    except OSError:
        return False
    m = re.search(r"(?m)^%REASON%\n(\d+)", desc)
    return not m or m.group(1) == "0"


def undoes(then: dict, now: dict, apps: dict, then_root: str | None = None, now_root: str | None = None) -> dict:
    """What going back to a snapshot does to the packages: then (package -> version in the snapshot) against now
    (installed now = removed, gone now = put back, another version now = that version back). Package versions don't
    see settings files, so the page adds snapper's own file count when it asks to confirm. "app" means the page may
    name it: an app (it has a menu entry), or a package someone installed by name (cowsay: no menu entry, but the
    snapshot's title already names it, so the confirm should too). Dependencies stay counted as "system parts", and
    names that would put another project's name on screen are never shown."""
    def named(p: str, root: str | None, version: str) -> bool:
        return p in apps or (not FOREIGN.search(p) and asked_for(root, p, version))
    removes, puts_back, rolls_back, tools = [], [], [], build_tools()
    for p in sorted(set(then) | set(now)):
        # an app or a package asked for by name reads the way Software and the title write it ("Ed"); a dependency keeps its
        # exact package name (it's only ever counted, or listed as itself when the snapshot's database is gone)
        label = lambda app: display(p, apps) if app else apps.get(p, p)
        if p not in then:
            app = named(p, now_root, now[p])
            # going back removes build tools again too (a snapshot from before an earlier go-back put them back):
            # said as build tools there as well, never as mystery "system parts"
            removes.append({"package": p, "name": label(app), "app": app, "buildTool": not app and p in tools,
                            "foreign": bool(FOREIGN.search(p))})
        elif p not in now:
            app = named(p, then_root, then[p])
            puts_back.append({"package": p, "name": label(app), "app": app, "detail": then[p],
                              "buildTool": not app and p in tools, "foreign": bool(FOREIGN.search(p))})
        elif then[p] != now[p]:
            app = named(p, now_root, now[p])
            rolls_back.append({"package": p, "name": label(app), "app": app, "foreign": bool(FOREIGN.search(p))})
    key = lambda x: (not x["app"], x["name"].lower())
    return {"removes": sorted(removes, key=key), "putsBack": sorted(puts_back, key=key),
            "rollsBack": sorted(rolls_back, key=key)}


@functools.lru_cache(maxsize=1)
def build_tools() -> frozenset:
    try:
        names = json.loads(BUILD_TOOLS.read_text())
    except (OSError, ValueError):
        return frozenset()
    return frozenset(n for n in names if isinstance(n, str)) if isinstance(names, list) else frozenset()


def from_log(txs: list) -> tuple:
    """(then, now) for undoes() when the snapshot's package database can't be read: each package's version before
    the first and after the last of these transactions in pacman.log (None = not installed)."""
    then, now = {}, {}
    for tx in txs:
        for (_t, a, p, d) in tx["changes"]:
            vs = d.split(" -> ")
            if p not in then:
                then[p] = None if a == "installed" else vs[0]
            now[p] = None if a == "removed" else vs[-1]
    return ({p: v for p, v in then.items() if v}, {p: v for p, v in now.items() if v})


def tag(s: dict) -> str:
    """Same rule as starchaser-admin's: setup (the installer's baseline), safety, hand, or "" (automatic)."""
    t = (s.get("userdata") or {}).get("starchaser", "")
    if not t and s.get("type") == "single" and (s.get("description") or "").startswith("Before going back"):
        t = "safety"
    if not t and s.get("type") == "single" and (s.get("description") or "") in ("Made by you", "Snapshot you took"):
        t = "hand"
    return t


PACKAGE_SETUP = "/usr/share/starchaser/installer/starchaser-desktop-setup.sh"   # in starchaser-desktop
SNAPSHOTS = Path("/.snapshots")
PREDATES_PACKAGE = ("This snapshot is from before this computer got Starchaser's packages. Going back to it would "
                    "take away the desktop's own files, so it isn't offered.")


def predates_package(n: int) -> bool:
    """Snapshot n has no starchaser-desktop although this computer has it now: starchaser-admin refuses going back
    to it (undo_checked), so the row says so instead of asking for a password first. Same no-root check as the
    helper's own predates_package; unreadable = not known, and the helper still refuses under its locks."""
    snap = SNAPSHOTS / str(n) / "snapshot"
    try:
        return Path(PACKAGE_SETUP).exists() and (snap / "usr").is_dir() and not (snap / PACKAGE_SETUP.lstrip("/")).exists()
    except OSError:
        return False


def number_limit(value) -> int:
    """snapper's NUMBER_LIMIT is a number ("10") or a range ("10-20": keep up to 20 while there's room, and at least
    10). The page says "the newest N are kept", so a range reports its upper end; anything unreadable is 0 (not
    shown) instead of stopping the whole list."""
    m = re.fullmatch(r"\s*(\d+)\s*(?:-\s*(\d+)\s*)?", str(value or ""))
    return int(m.group(2) or m.group(1)) if m else 0


def last_change(snaps: list) -> dict | None:
    """Settings > Recovery's big button: the snapshot from just before the newest change, and that change in
    plain words ({number, time, what}), or None. The newest software change has its "Before …" snapshot; when
    the newest thing done was going back (or undoing it), its own safety snapshot undoes that. Snapshots taken
    by hand, the starting point and older safety points are never "the last change". snaps: newest first."""
    by_number = {str(s["number"]): s for s in snaps}
    for s in snaps:
        if s["notOffered"]:
            continue
        if s["kind"] == "safety" and s["newestSafety"]:
            # made by the newest go-back: its row says "Undo going back" ("Go back again" after an undo), and the big
            # button does the same
            what = "undoing going back" if s["redo"] else "going back to an earlier snapshot"
            return {"number": s["number"], "time": s["time"], "what": what}
        if s["kind"] == "auto" and (s["type"] == "pre" or s.get("fullUpdate")):
            # A full update can have several transactions. Its dedicated start undoes all of them; if that copy
            # is gone or unavailable, the newest offered transaction still provides a way back.
            parent = by_number.get(str(s.get("updateStart", "")))
            if parent and parent.get("fullUpdate") and not parent["notOffered"]:
                s = parent
            t = s["title"]
            what = t[7].lower() + t[8:] if t.startswith("Before ") and len(t) > 8 else "a software change"
            return {"number": s["number"], "time": s["time"], "what": what}
    return None


def main() -> None:
    if not CONFIG.exists() or not shutil.which("snapper"):
        print(json.dumps({"configured": False, "snapshots": []}))
        return
    r = sh("snapper", "--jsonout", "-c", "root", "list")
    menu = boot_menu()
    started = {"booted": menu["booted"], "bootedTitle": menu.get("bootedTitle", "")}
    if r.returncode != 0:
        # started from a snapshot, snapper may not read the list at all (the system there is a copy in memory): that
        # isn't the account's rights
        print(json.dumps({"configured": True, "allowed": None if menu["booted"] is not None else False,
                          "error": (r.stdout + r.stderr).strip(), "snapshots": [], **started}))
        return
    snaps = [s for s in json.loads(r.stdout).get("root", []) if s.get("number")]
    # Snapshots from before Starchaser finished installing hold a half-built system (no login screen, the installer's
    # no-password sudo rule): not shown, and starchaser-admin refuses them. Older than the installer's baseline, or
    # on computers installed before there was one, older than the install log the installer writes last.
    base = [s["number"] for s in snaps if tag(s) == "setup"]
    try:
        installed = INSTALL_LOG.stat().st_mtime
    except OSError:
        installed = 0
    snaps = [s for s in snaps if (s["number"] >= min(base) if base else when(s.get("date", "")) > installed)]
    txs = paclog()
    # Software's own name for an app it offers wins over the menu entry's; Starchaser's feature helpers keep theirs
    apps = {**FEATURES, **app_names()}
    apps.update({k: v for k, v in {**catalog_names(), **software_titles()}.items() if k not in FEATURES})
    live = pkgdb("/")
    posts = {s["pre-number"]: s for s in snaps if s.get("type") == "post" and s.get("pre-number")}
    safeties = [s["number"] for s in snaps if tag(s) == "safety"]
    out = []
    tied = {x["pre"]: i for i, x in enumerate(txs) if x["pre"] is not None}
    floor = 0                                       # transactions before this one belong to earlier snapshots
    for s in sorted(snaps, key=lambda x: x["number"]):
        if s.get("type") == "post":
            continue
        t0 = when(s.get("date", ""))
        post = posts.get(s["number"])
        # A pre snapshot's own transaction (going back to it undoes that one too): the one snap-pac's log line ties to
        # it, else the first one starting at or after it (snap-pac runs before pacman logs "transaction started",
        # often a second earlier), not claimed by an earlier snapshot, and no later than its post snapshot.
        # A snapshot by hand: the transactions from then on.
        changes = []
        since = next((i for i in range(floor, len(txs)) if txs[i]["start"] >= t0 and txs[i]["pre"] in (None, s["number"])), len(txs))
        if s.get("type") == "pre":
            # no post snapshot (the transaction never finished): only one starting right after it (snap-pac logs about
            # a second before "transaction started"), so the next, unrelated install isn't listed under this one
            t1 = when(post["date"]) + 1 if post else t0 + 5
            since = tied.get(s["number"], since)
            if since < len(txs) and (s["number"] in tied or txs[since]["start"] <= t1):
                floor = since + 1
                own = [c for c in txs[since]["changes"] if s["number"] in tied or not post or c[0] <= t1]
                # snap-pac truncates the command description, often before the chosen package's name ends.
                # The matched transaction's log keeps the whole command, including apps without a menu entry.
                if txs[since].get("command"):
                    s = {**s, "description": txs[since]["command"]}
                # named the way the title names it: an app or feature, or a package asked for by name ("Ed (ed)"),
                # never one that would put another project's name on screen; "foreign" tells the page to leave the
                # package id out of the brackets there too ("Mission Control support", not "(cockpit)")
                asked = set((s.get("description") or "").split())
                changes = [{"action": a, "package": p, "detail": d.replace(" -> ", " → "), "foreign": bool(FOREIGN.search(p)),
                            "name": display(p, apps) if p in apps or ((p in asked or len(own) == 1) and not FOREIGN.search(p)) else ""}
                           for (t, a, p, d) in own]
                # (with no post snapshot, the short window only picks the transaction: all of its changes are its
                # own, even the ones logged well after it started)
        # what going back undoes: the snapshot's own package database against the live one. pacman.log only as a
        # fallback, and not once a later go-back has happened (it rolled the packages back without logging it).
        then = pkgdb(f"/.snapshots/{s['number']}/snapshot")
        if then is not None and live is not None:
            und = undoes(then, live, apps, f"/.snapshots/{s['number']}/snapshot", "/")
        elif any(m > s["number"] for m in safeties):
            und = None
        else:
            und = undoes(*from_log(txs[since:]), apps, None, "/" if live is not None else None)
        tg = tag(s)
        full_update = tg == "full-update"
        keep = s.get("type") == "single" and not s.get("cleanup") and not full_update
        newest_safety = tg == "safety" and s["number"] == max(safeties)
        out.append({"number": s["number"], "post": post["number"] if post else None, "time": int(t0),
                    "type": s.get("type"), "title": title(s, changes, apps), "changes": changes[:400],
                    "count": len(changes), "undoes": und, "kind": "auto" if tg in ("full-update", "full-member") else tg or "auto",
                    "fullUpdate": full_update,
                    "updateStart": (s.get("userdata") or {}).get("full-update", "") if tg == "full-member" else "",
                    "kept": keep, "newestSafety": newest_safety,
                    "redoTarget": recovery_destination(s) if tg == "safety" else "",
                    "redo": tg == "safety" and (s.get("userdata") or {}).get("recovery") == "redo",
                    "deletable": keep and tg in ("hand", "safety") and not newest_safety,
                    "important": (s.get("userdata") or {}).get("important") == "yes",
                    "notOffered": PREDATES_PACKAGE if predates_package(s["number"]) else "",
                    "cleanup": s.get("cleanup") or "", "user": s.get("user")})
    out.sort(key=lambda x: -x["number"])
    last = last_change(out)
    cfg = {}                                        # the config file is root-only; snapper itself will tell us
    try:
        cfg = json.loads(sh("snapper", "--jsonout", "-c", "root", "get-config").stdout or "{}")
    except ValueError:
        pass
    bootable = bool(menu["entries"]) or sh("pacman", "-Q", "limine-snapper-sync").returncode == 0 or \
        sh("pacman", "-Q", "grub-btrfs").returncode == 0
    du = shutil.disk_usage("/")
    print(json.dumps({"configured": True, "allowed": True, "snapshots": out, "bootable": bootable,
                      "bootMenu": [e["number"] for e in menu["entries"]], "bootMenuWhy": menu.get("why", ""),
                      "bootMenuAddNow": bool(menu.get("addNow")), **started,
                      "autoBeforeChanges": sh("pacman", "-Q", "snap-pac").returncode == 0,
                      "limit": number_limit(cfg.get("NUMBER_LIMIT")),
                      "kept": sum(1 for x in out if x["kept"] and x["kind"] in ("hand", "safety")),
                      "diskFree": du.free, "diskSize": du.total,
                      "lockStale": pacman_lock_state() == "stale", "lastChange": last,
                      "helperReady": Path("/usr/local/lib/starchaser/starchaser-admin").exists()}))


ADMIN = "/usr/local/lib/starchaser/starchaser-admin"
# the door that makes the password box name the change ("go back to the snapshot you picked"); older system tools
# don't have it, and then starchaser-admin asks with its general words
ADMIN_AREA = "/usr/local/lib/starchaser/starchaser-admin-area"
AREA_CMDS = ("recovery-undo", "recovery-go-back-undo", "recovery-create", "recovery-delete", "recovery-keep", "recovery-boot", "pacman-unlock")
LAST = Path.home() / ".local/state/starchaser/recovery-last.json"
JOB = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-recovery-job.json"


def job_read() -> dict:
    try:
        d = json.loads(JOB.read_text())
        return d if isinstance(d, dict) else {}
    except (OSError, ValueError):
        return {}


def job_write(d: dict) -> bool:
    try:
        tmp = JOB.with_name(JOB.name + f".{os.getpid()}.tmp")
        with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
            json.dump(d, f)
            f.flush()
            os.fsync(f.fileno())
        tmp.replace(JOB)
        return True
    except OSError:
        return False


def boot_id() -> str:
    try:
        return Path("/proc/sys/kernel/random/boot_id").read_text().strip()
    except OSError:
        return ""


def last_read() -> dict:
    try:
        d = json.loads(LAST.read_text())
        if (not isinstance(d, dict) or d.get("outcome") not in ("ok", "partial", "failed")
                or d.get("kind") not in ("restore", "undo") or not isinstance(d.get("boot_id"), str)
                or not d["boot_id"] or not isinstance(d.get("time"), (int, float))
                or not isinstance(d.get("targetDate"), str) or not isinstance(d.get("targetName"), str)
                or not isinstance(d.get("target"), int) or not isinstance(d.get("safety"), int)
                or not isinstance(d.get("targetTime"), (int, float)) or not isinstance(d.get("dismissed"), bool)
                or not isinstance(d.get("result"), dict)):
            return {}
        r = d["result"]
        if d["outcome"] == "ok" and (r.get("ok") is not True or r.get("undo") != "done" or r.get("boot")):
            return {}
        return d
    except (OSError, ValueError):
        return {}


def last_write(d: dict) -> bool:
    tmp = LAST.with_name(LAST.name + f".{os.getpid()}.tmp")
    try:
        LAST.parent.mkdir(parents=True, exist_ok=True)
        # Private from its first byte, and replace only after the whole record has been written.
        with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
            json.dump(d, f)
            f.flush()
            os.fsync(f.fileno())
        tmp.replace(LAST)
        return True
    except (OSError, ValueError, TypeError):
        return False
    finally:
        try:
            tmp.unlink(missing_ok=True)
        except OSError:
            pass


def remember_result(rec: dict, code: int, out: str, boot: str = "") -> None:
    args = rec.get("args") or []
    if not args or args[0] not in ("recovery-undo", "recovery-go-back-undo", "recovery-update-undo", "recovery-update-undo-at", "recovery-boot"):
        return
    if code in (126, 127) and not out.strip():
        return      # pkexec: the password box was closed or no one could ask (126/127): nothing ran, keep the last result
    try:
        r = json.loads(out)
        if not isinstance(r, dict):
            r = {}
    except ValueError:
        r = {}
    if args[0] == "recovery-boot":
        # Only a go-back whose startup files still need rebuilding is this rebuild's news (its banner's Rebuild
        # button, also after a restart). Add them now runs the same rebuild: a finished go-back from last week, or
        # one dismissed, must not come back as if it had just happened.
        d = last_read()
        if not d or not d["result"].get("boot"):
            return
        result = {**d["result"], "boot": "" if code == 0 and r.get("ok") else r.get("boot") or r.get("errors") or "Startup files couldn't be rebuilt."}
        result["ok"] = result.get("undo") == "done" and not result["boot"]
        d.update(result=result, boot_id=boot_id(), time=time.time(), outcome="ok" if result["ok"] else "partial" if result.get("undo") in ("done", "partial") else "failed")
        last_write(d)
        return
    if code == 0 and r.get("ok") is True and r.get("undo") == "unchanged":
        return                                    # no restore happened; keep the previous result and safety snapshot
    if r.get("undo") == "refused" or (code == 2 and r.get("ok") is False and "undo" not in r):
        return                                    # refused before anything changed ("…isn't offered. Nothing was changed.");
                                                  # exit 2 without "undo": a command or its words the helper doesn't take
    outcome = "ok" if code == 0 and r.get("ok") is True and r.get("undo") == "done" and not r.get("boot") else "partial" if r.get("undo") in ("done", "partial") else "failed"
    last_write({"target": int(args[1]) if len(args) > 1 and str(args[1]).isdigit() else 0,
                "targetName": r.get("targetName", ""), "targetDate": r.get("targetDate", ""),
                "targetTime": r.get("targetTime") or rec.get("time", 0),
                "safety": int(r["safety"]) if str(r.get("safety", "")).isdigit() else 0,
                "time": time.time(), "boot_id": boot or boot_id(), "outcome": outcome,
                "kind": r.get("kind", "restore"), "dismissed": False, "result": r})


def boot_menu() -> dict:
    """The snapshots the boot menu lists, and the one this computer started from (bootsnap.py, root-written)."""
    if bootsnap is None:
        return {"entries": [], "loaders": [], "booted": None}
    try:
        return bootsnap.status()
    except (OSError, ValueError):
        return {"entries": [], "loaders": [], "booted": None}


GO_BACK_RESULT = Path("/var/lib/starchaser/snapshot-go-back-result.json")
GO_BACK_SEEN = Path.home() / ".local/state/starchaser/snapshot-go-back-seen"


def cmd_snapshot_go_back() -> int:
    """Switch the system from this working snapshot session, then restart. Prints one JSON answer."""
    menu = boot_menu()
    if menu["booted"] is None:
        print(json.dumps({"ok": False, "errors": "This computer didn't start from a snapshot, so there's nothing to go back to here. Use Settings > Recovery."}))
        return 1
    door = ADMIN_AREA if os.access(ADMIN_AREA, os.X_OK) else ADMIN
    try:
        r = subprocess.run(["pkexec", door, "recovery-snapshot-go-back", str(menu["booted"])], capture_output=True, text=True,
                           stdin=subprocess.DEVNULL)
    except OSError as e:
        print(json.dumps({"ok": False, "errors": f"The password box couldn't open: {e}"}))
        return 1
    if r.returncode in (126, 127) and not r.stdout.strip():
        print(json.dumps({"ok": False, "canceled": True, "errors": ""}))   # the password box was closed: nothing ran
        return 1
    try:
        answer = json.loads(r.stdout)
    except ValueError:
        answer = {}
    if r.returncode != 0 or not isinstance(answer, dict) or answer.get("ok") is not True:
        why = answer.get("errors") if isinstance(answer, dict) else ""
        print(json.dumps({"ok": False, "errors": why or "Going back couldn't be set up. Nothing was changed."}))
        return 1
    restart = subprocess.run(["systemctl", "reboot"], capture_output=True, text=True)
    print(json.dumps({"ok": restart.returncode == 0, "errors": "" if restart.returncode == 0 else
                      "The system was restored, but the computer didn't restart. Restart to finish going back."}))
    return 0 if restart.returncode == 0 else 1


def cmd_restart_normally() -> int:
    r = subprocess.run(["systemctl", "reboot"], capture_output=True, text=True)
    print(json.dumps({"ok": r.returncode == 0, "errors": "" if r.returncode == 0 else (r.stderr.strip() or "The computer didn't restart.")}))
    return 0 if r.returncode == 0 else 1


def import_go_back_result() -> dict:
    """The go-back that ran at startup (as root, before sign-in) becomes this account's last recovery result once, so
    Settings > Recovery shows it like any other go-back, with its Undo. {} when there is none new."""
    try:
        d = json.loads(GO_BACK_RESULT.read_text())
        seen = GO_BACK_SEEN.read_text().strip() if GO_BACK_SEEN.exists() else ""
    except (OSError, ValueError):
        return {}
    if not isinstance(d, dict) or not isinstance(d.get("number"), int) or not d.get("id") or d["id"] == seen:
        return {}
    remember_result({"args": ["recovery-undo", str(d["number"])], "time": 0}, int(d.get("code", 1)), str(d.get("out", "")),
                    boot=str(d.get("boot_id") or ""))
    try:
        GO_BACK_SEEN.parent.mkdir(parents=True, exist_ok=True)
        GO_BACK_SEEN.write_text(str(d["id"]) + "\n")
    except OSError:
        pass
    try:
        r = json.loads(d.get("out") or "{}")
    except ValueError:
        r = {}
    return r if isinstance(r, dict) else {"ok": False}


def notify(*args) -> str:
    """notify-send, waiting for the answer when the card has buttons; "" when it couldn't show or was closed."""
    try:
        r = subprocess.run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", *args], capture_output=True, text=True)
    except OSError:
        return ""
    return r.stdout.strip()


def cmd_notice() -> None:
    menu = boot_menu()
    if menu["booted"] is not None:
        # critical: stays on screen until answered (the normal system is one restart away, and nothing done here is kept)
        while True:
            answer = notify("-u", "critical", "-i", "dialog-warning", "-w", "-A", "back=Go back to this snapshot",
                            "-A", "restart=Restart normally", f"You started from a snapshot: {menu['bootedTitle']}",
                            "Changes you make to the system now are lost when you restart. Your files in your home folder are kept. "
                            "Go back to this snapshot to keep the system as it is here, or restart normally.")
            if answer not in ("restart", "back"):
                return
            with open(os.devnull, "w") as quiet:                # the JSON answers are for Settings, not this notice
                saved, sys.stdout = sys.stdout, quiet
                try:
                    code = cmd_restart_normally() if answer == "restart" else cmd_snapshot_go_back()
                finally:
                    sys.stdout = saved
            if code == 0:
                return
            # the password box was closed or going back couldn't be set up: offer the choice again
    r = import_go_back_result()
    d = last_read()
    if d and d.get('outcome') == 'ok' and d.get('boot_id') != boot_id():
        # A later software change makes an old completion misleading, just as it supersedes the Settings banner.
        if not any(change[0] > d['time'] for tx in paclog() for change in tx['changes']):
            completion_notice(d)
    elif r and r.get('undo') != 'unchanged':
        notify('-u', 'critical', '-i', 'dialog-error', "Going back to the snapshot didn't finish",
               (r.get('errors') or 'Nothing was changed.') + ' Open Settings > Recovery for details.')


def completion_notice(result):
    """Deduplicate accepted delivery per person/result, independently of Settings dismissal."""
    marker = LAST.with_name('recovery-notice.json')
    marker.parent.mkdir(parents=True, exist_ok=True)
    key = [result['time'], result['boot_id'], result['target'], result['kind']]
    process = None
    with marker.with_suffix('.lock').open('a') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        try:
            if json.loads(marker.read_text()) == key:
                return
        except (OSError, ValueError):
            pass
        name = ' '.join((result.get('targetName') or result.get('targetDate') or 'the earlier snapshot').split())[:160]
        title = ('Undid going back to ' if result['kind'] == 'undo' else 'Went back to ') + '“' + name + '”.'
        body = 'Your system is ready. Undo is in Settings > Recovery.'
        token = Path(os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}') / 'starchaser-notifications' / 'token'
        args = ['starchaser', 'notify', '-a', 'Starchaser', '-i', 'edit-undo', '-p', '-w',
                '-A', 'open=Open Recovery', title, body]
        # notify-send prints its accepted ID before waiting for an action. A failed send leaves delivery retryable.
        try:
            with token.open() as credential:
                args.insert(2, f'--credential-fd={credential.fileno()}')
                process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
                                           pass_fds=(credential.fileno(),))
            accepted = process.stdout.readline().strip()
            if not accepted.isdigit() or int(accepted) == 0:
                process.wait()
                return
            tmp = marker.with_name(f'.{marker.name}.{os.getpid()}.tmp')
            try:
                with open(tmp, 'w') as out:
                    json.dump(key, out); out.flush(); os.fsync(out.fileno())
                os.replace(tmp, marker)
            finally:
                tmp.unlink(missing_ok=True)
        except OSError:
            if process is not None:
                process.terminate()
                process.wait()
            return
    answer = process.stdout.read().strip()
    process.wait()
    if answer == 'open':
        subprocess.Popen(['starchaser', 'settings', 'recovery'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)


def cmd_last(dismiss_time: str = "") -> None:
    d = last_read()
    if dismiss_time and d and (dismiss_time == "now" or str(d["time"]) == dismiss_time):
        if last_write({**d, "dismissed": True}):
            d["dismissed"] = True
    current = boot_id()
    # Once restarted, a later package change makes the old success banner misleading: the system is no longer
    # at that snapshot. Keep the history/target, failed restores, and reminders that still need a restart.
    superseded = bool(current and d and d["outcome"] == "ok" and d["boot_id"] != current
                      and any(change[0] > d["time"] for tx in paclog() for change in tx["changes"]))
    print(json.dumps({"last": d if current and d and not d.get("dismissed") and not superseded else None,
                      "restoredTarget": d["target"] if current and d and d["outcome"] == "ok" else 0,
                      "rebooted": bool(current and d and d["boot_id"] != current)}))


def proc_start(pid: int) -> str:
    """When process pid started (field 22 of /proc/<pid>/stat, in clock ticks since boot), "" when it's gone or a
    zombie. With the pid it names one process: a pid the system handed to a new process after the runner died has
    another start time, so a killed runner isn't taken for alive."""
    try:
        st = Path(f"/proc/{pid}/stat").read_text()
    except (OSError, ValueError):
        return ""
    rest = st[st.rfind(")") + 2:].split()             # the name in (...) may hold spaces
    if len(rest) < 20 or rest[0] in ("Z", "X"):
        return ""
    return rest[19]


AUTHORIZED = b"@@authorized\n"


def door_args(door: str, args: list) -> list:
    """recovery-go-back-undo is only "recovery-undo" under its own name (for the password box's words). The system
    tools go back with the system, and ones from before Oct 30 refuse that name ("doesn't do that"), so "Undo going
    back" never ran after going back that far (QA 20261107-0828): ask the helper what it knows (no root needed) and
    use the plain name when it doesn't list the new one."""
    if not args or args[0] != "recovery-go-back-undo":
        return args
    try:
        known = json.loads(subprocess.run([door, "commands"], capture_output=True, text=True, timeout=10,
                                          stdin=subprocess.DEVNULL).stdout).get("commands")
    except (OSError, ValueError, AttributeError, subprocess.SubprocessError):
        return args
    return ["recovery-undo", *args[1:]] if isinstance(known, list) and args[0] not in known else args


def cmd_run(kind: str, when: str, args: list) -> None:
    """The runner stays pkexec's parent (pkexec refuses an orphaned caller) in a session of its own, so stopping this
    command, or its whole process group, leaves the go-back running to the end. The answer comes back to this command
    through a pipe, and is also kept in the job file for a page that was gone by then. Marking it shown is the page's
    job (job-seen), once it has the answer: a Settings closed in between finds it again on the next visit.
    The password box: pkexec runs the helper in its own place once the password is accepted, so its name changes
    then. The record gets "authorized" (its time), and with STARCHASER_RUN_EVENTS=1 an "@@authorized" line comes
    out first, so a page can say "Waiting for your password" until then instead of counting the time as work."""
    import signal
    import threading
    import time
    jid = f"{int(time.time() * 1000)}-{os.getpid()}"
    rec = {"id": jid, "kind": kind, "args": args, "time": int(when) if when.isdigit() else 0, "seen": False}
    # nothing runs unless its answer can be kept: a go-back whose result is lost can't be shown when the page returns
    if not job_write({**rec, "state": "starting", "pid": os.getpid(), "pidStart": proc_start(os.getpid())}):
        print(json.dumps({"ok": False, "errors": "Nothing changed: Settings couldn't save a note it needs in your "
                          "session folder (is the disk full?). Free up some space, then try again."}))
        sys.exit(1)
    rfd, wfd = os.pipe()
    pid = os.fork()
    if pid == 0:
        try:
            os.close(rfd)
            os.setsid()
            signal.signal(signal.SIGHUP, signal.SIG_IGN)
            signal.signal(signal.SIGPIPE, signal.SIG_IGN)    # a write to a closed pipe fails instead of killing this
            fd = os.open(os.devnull, os.O_RDWR)        # never write into Settings' pipe: it may be gone
            for n in (0, 1, 2):
                os.dup2(fd, n)
            running = {**rec, "state": "running", "pid": os.getpid(), "pidStart": proc_start(os.getpid()),
                       "started": time.time()}
            job_write(running)

            def authorized(p):
                while p.poll() is None:
                    try:
                        name = Path(f"/proc/{p.pid}/comm").read_text().strip()
                    except OSError:
                        name = ""                      # can't be read: the page counts the time as work, as before
                    if name != "pkexec":
                        if p.poll() is None:
                            running["authorized"] = time.time()
                            job_write(running)
                            try:
                                os.write(wfd, AUTHORIZED)
                            except OSError:
                                pass
                        return
                    time.sleep(0.25)
            try:
                door = ADMIN_AREA if args and args[0] in AREA_CMDS and os.access(ADMIN_AREA, os.X_OK) else ADMIN
                p = subprocess.Popen(["pkexec", door, *door_args(door, args)], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                     stdin=subprocess.DEVNULL, text=True, errors="replace")
                watch = threading.Thread(target=authorized, args=(p,), daemon=True)
                watch.start()
                out, err = p.communicate()
                watch.join()
                code = p.returncode
            except OSError as e:
                code, out, err = 127, "", f"Cannot run program pkexec: {e}"
            done = {**rec, "state": "done", "code": code, "out": out, "err": err[-4000:], "finished": time.time()}
            if "authorized" in running:
                done["authorized"] = running["authorized"]
            remember_result(rec, code, out)
            job_write(done)
            try:
                data = json.dumps(done).encode()
                while data:
                    data = data[os.write(wfd, data):]
            except OSError:
                pass
        finally:
            os._exit(0)
    os.close(wfd)
    chunks = []
    events = os.environ.get("STARCHASER_RUN_EVENTS") == "1"
    try:
        while True:
            b = os.read(rfd, 65536)
            if not b:
                break
            if not chunks and b.startswith(AUTHORIZED):  # the first thing the runner sends, if at all (one write)
                b = b[len(AUTHORIZED):]
                if events:
                    print("@@authorized", flush=True)
            chunks.append(b)
    except OSError:
        pass
    os.waitpid(pid, 0)
    try:
        d = json.loads(b"".join(chunks).decode(errors="replace"))
    except ValueError:
        d = job_read()                                   # the pipe broke: the job file still has it
    if not isinstance(d, dict) or d.get("id") != jid or d.get("state") != "done":
        print("the go-back's answer went missing", file=sys.stderr)
        sys.exit(1)
    out = d.get("out", "")
    sys.stdout.write(out + ("\n" if events and out and not out.endswith("\n") else ""))   # a page reading lines gets the last
    sys.stderr.write(d.get("err", ""))
    sys.stdout.flush()
    sys.stderr.flush()
    sys.exit(d.get("code", 1))


def cmd_job() -> None:
    d = job_read()
    if d.get("state") in ("starting", "running"):          # "starting": the instant before its runner is made
        d = {**d, "state": "running"}
        alive = False
        try:
            pid = int(d.get("pid", 0))
            os.kill(pid, 0)
            started = proc_start(pid)
            # the same process only if it started when the record says (a reused pid, or a zombie, is not)
            alive = pid > 0 and started != "" and started == str(d.get("pidStart", started))
        except (OSError, ValueError, TypeError):
            pass
        if not alive:                                     # the runner itself died: done, without an answer
            d = {**d, "state": "done", "code": 1, "out": "", "err": d.get("err", "")}
    print(json.dumps(d))


if __name__ == "__main__":
    if len(sys.argv) == 1:
        print("starchaser recovery: no command given. Run 'starchaser recovery --help' for more help.", file=sys.stderr)
        sys.exit(2)
    arg = sys.argv[1]
    # help after a command word is help (r172), except in last-dismiss's time place: there a help flag is a word
    # that can't be a time, and is refused as one so a script never believes a dismissal happened
    if arg in ("-h", "--help", "help") or (arg != "last-dismiss"
                                           and any(a in ("-h", "--help") for a in sys.argv[2:])):
        print(__doc__.strip())
        sys.exit(0)
    if arg in ("last", "list", "job", "booted", "snapshot-go-back", "restart-normally", "notice") and len(sys.argv) > 2:
        print(f"starchaser recovery: {arg} takes nothing after it (got {sys.argv[2]!r})\n"
              f"Usage: starchaser recovery {arg}\nRun 'starchaser recovery --help' for more help.", file=sys.stderr)
        sys.exit(2)
    if arg == "run" and len(sys.argv) >= 5 and (sys.argv[4].startswith("recovery-") or sys.argv[4] == "pacman-unlock"):
        cmd_run(sys.argv[2], sys.argv[3], sys.argv[4:])
    if arg == "last" and len(sys.argv) == 2:
        cmd_last()
        sys.exit(0)
    if arg == "booted":
        print(json.dumps(boot_menu()))
        sys.exit(0)
    if arg == "snapshot-go-back":
        sys.exit(cmd_snapshot_go_back())
    if arg == "restart-normally":
        sys.exit(cmd_restart_normally())
    if arg == "notice":
        cmd_notice()
        sys.exit(0)
    if arg == "last-dismiss":
        if len(sys.argv) != 3:
            print("last-dismiss needs a time: starchaser recovery last-dismiss <time>\n"
                  "Use now to dismiss the current result: starchaser recovery last-dismiss now\n"
                  "Scripts can use the exact time value from last, including any decimal places.", file=sys.stderr)
            sys.exit(2)
        if sys.argv[2] != "now" and not re.fullmatch(r"\d+(\.\d+)?", sys.argv[2]):
            # a word that can't be a time is wrong input, not a result that went away on its own
            print(f"starchaser recovery: last-dismiss needs 'now' or the exact time value from "
                  f"'starchaser recovery last' (got {sys.argv[2]!r}).\n"
                  "Run 'starchaser recovery --help' for more help.", file=sys.stderr)
            sys.exit(2)
        cmd_last(sys.argv[2])
        sys.exit(0)
    if arg == "job":
        if len(sys.argv) == 2:
            cmd_job()
            sys.exit(0)
        print(f"starchaser recovery: wrong arguments for 'job'\n\n{__doc__.strip()}", file=sys.stderr)
        sys.exit(2)
    if arg == "job-seen" and len(sys.argv) in (2, 3):
        d = job_read()
        if d.get("state") == "done" and (len(sys.argv) == 2 or d.get("id") == sys.argv[2]):
            job_write({**d, "seen": True})
        sys.exit(0)
    if arg in ("run", "job-seen"):
        usage = "run KIND TIME ARGS..." if arg == "run" else "job-seen [ID]"
        print(f"starchaser recovery: wrong arguments for '{arg}'\nUsage: starchaser recovery {usage}\n"
              "Run 'starchaser recovery --help' for more help.", file=sys.stderr)
        sys.exit(2)
    if arg == "list":
        if len(sys.argv) != 2:
            print(f"starchaser recovery: wrong arguments for 'list'\n\n{__doc__.strip()}", file=sys.stderr)
            sys.exit(2)
        main()
    if arg not in ("list", "job"):
        print(f"starchaser recovery: unknown command {arg!r}. Run 'starchaser recovery --help' for more help.", file=sys.stderr)
        sys.exit(2)
