#!/usr/bin/env python3
"""starchaser-admin: the few things Starchaser Settings does as root. Run through pkexec: polkit asks for the
password every time (org.starchaser.admin.<command>, one polkit action per command so the password box names the change; all
auth_admin: nothing is remembered between changes). The one exception
is answering the firewall's Keep countdown: Keep and Go back for a change you just made go through
starchaser-firewall-keep (org.starchaser.firewall-keep), which the person at the computer may run without a
password, and which can only confirm or undo the change waiting for Keep. The other exception is software:
Settings > Updates and > Software reach update-run, software-run and pacman-unlock through starchaser-admin-software
(org.starchaser.software + 50-starchaser-software.rules: the password once, then 15 minutes after the last such run
in that login session), which can run nothing else; the same 15 minutes cover update-channel-set and autoupdate-set
(the rest of Settings > Updates), and a password either of them asked for opens them. Installed root-owned at
/usr/local/lib/starchaser/ so code the user can edit never runs as root. Every input is validated here; nothing is
passed to a shell.

    starchaser-admin thunderbolt-device allow|remember|forget UUID CONNECTION
                                         change only that Thunderbolt connection after an administrator password
    starchaser-admin hardware-fix <item>    install missing support for one detected hardware item
    starchaser-admin firmware refresh|<device>  refresh or install device firmware (Settings > Updates)
    starchaser-admin drive-unlock <action>     repair drive unlock or renew an emergency sheet; private JSON on stdin
    starchaser-admin language <locale>     prepare and select a supported language for the next sign-in
    starchaser-admin printing-on            turn on printing: CUPS's socket, so it starts when something prints
    starchaser-admin backup-folder <mount point>
                                         Settings > Backups on a drive whose top folder belongs to the computer (one
                                         formatted for Linux): make "Starchaser Backups/<your account>" there, yours
    starchaser-admin firewall-commit <policy.json> [--timeout N] [--summary TEXT]
                                         make a firewall policy live (firewall.py); with --timeout, the previous
                                         policy comes back by itself unless confirmed
                                         (without --timeout while a change waits for Keep: refused)
                                         --end-once addr/proto/port[/adapter],...: also end these temporary
                                         permissions once it is live (a permission it turns off)
    starchaser-admin firewall-confirm    keep it
    starchaser-admin firewall-extend <id> add 60 seconds to a change waiting for Keep
    starchaser-admin firewall-revert     back to the previous policy now
    starchaser-admin firewall-rollback <history id> [--timeout N] [--summary TEXT]   an earlier commit
    starchaser-admin firewall-restart-outgoing      restart outgoing checks using the saved policy; keep incoming rules
    starchaser-admin firewall-reload [--reconnect]   load the saved policy again (the firewall is on but isn't
                                         running); --reconnect also restarts OpenSnitch so it connects to the
                                         question window again (Ask is on, but OpenSnitch stopped talking to it)
                                         --repair puts back the saved rules exactly as they last ran (after an
                                         outside change), without reading unapplied hand-written edits
    starchaser-admin firewall-boot-check the computer restarted while a change waited for Keep: put the previous
                                         policy back before the network starts (starchaser-firewall.service)
    starchaser-admin firewall-boot-load  the unit's start: load the saved rules; if they won't load, compile them
                                         again from policy.json; if that fails too, load a strict backup table
                                         (the network keeps working, nothing gets in) and say so in Settings
    starchaser-admin firewall-default-on setup: turn the firewall on with the first policy when there is no policy
                                         yet (no network counts as a network you trust until you say so); never changes one
    starchaser-admin firewall-upgrade    after an update: if the saved rules were compiled by an older version
                                         of the engine, compile them again from the unchanged policy and load them
                                         (the package's install hook; does nothing while a change waits for Keep)
    starchaser-admin firewall-zones-refresh [--boot]   networks changed (NetworkManager dispatcher; --boot: the
                                         firewall unit at startup, which only queues OpenSnitch's restart)
    starchaser-admin route-guard-refresh       traffic to a network this computer is on goes out that cable or Wi-Fi,
                                         even when a VPN routes the same network (route_guard.py: one "to
                                         <network> lookup main suppress_prefixlength 0" rule at priority 5200 each,
                                         added and removed to match; none while a VPN carries all traffic;
                                         NetworkManager dispatcher). JSON result
    starchaser-admin route-guard-watch         the same at start-up, then again whenever routes or addresses change
                                         (starchaser-route-guard.service; never returns)
    starchaser-admin firewall-outgoing-hold started|stopping|stopped   OpenSnitch's unit started, about to stop, or stopped:
                                         with an app Block or outgoing default Block, hold new outgoing connections while it is not checking them
                                         (a run that failed is counted; when it cannot start, the app firewall is
                                         paused and new connections are let out instead of held: firewall.py CHECKER_PAUSED)
    starchaser-admin firewall-stats            per-rule counters, and whether the rules are running ->
                                         /run/starchaser/firewall-stats.json (timer)
    starchaser-admin firewall-allow-once <address> tcp|udp <port> [minutes] [--iface NAME]
                                         the blocked-connection question's "Allow once": that device may reach that
                                         port for a while (default 15 minutes; what it opens stays up); --iface limits it to that adapter, omitted means every network;
                                         address "any" (with --iface): every device on that adapter's network (Simple's For 15 minutes)
    starchaser-admin firewall-public-pause-on    mark connected networks Public and pause new connections
    starchaser-admin firewall-public-pause-off   undo Public pause and restore earlier network settings
    starchaser-admin firewall-revoke-once <address> tcp|udp <port> [--iface NAME]
                                         end an "Allow once" before its time (Settings > Firewall > Log)
    starchaser-admin firewall-allow-always <address> tcp|udp <port> [device name] [service name] [--zone Z] [--network UUID]
                                         "Allow always": a rule for that device on that port, added to the policy
                                         (the device and the service get named entries you can see in Rules), on the
                                         kind of network it came in on (--zone; Trusted when that isn't known),
                                         or only one remembered network (--network)
    starchaser-admin firewall-mark-network <network uuid> trusted|public [--only-unmarked]
                                         the one-time "Is this a network you trust?" answer (public only marks a
                                         network nobody has marked yet; --only-unmarked: trusted too, so a late Yes
                                         never overrides a choice made in Settings after the question came up)
    starchaser-admin firewall-forget-asked <sc-asked-….json>   forget an outgoing answer (the app is asked again)
    starchaser-admin sharing-status            JSON, no root needed: the shared folder and network availability
    starchaser-admin sharing-start <folder> read|write   share one folder (sharing password on stdin)
    starchaser-admin sharing-stop              stop sharing and remove its firewall permission
    starchaser-admin ssh on|off                the SSH server (remote login); off also signs out the computers
                                         connected now ("ended": how many)
    starchaser-admin autoupdate                JSON, no root needed: level and last automatic run
    starchaser-admin autoupdate-set <level>    change automatic updates (off/security/starchaser/everything/aur)
    starchaser-admin autoupdate-default        setup: security patches and Starchaser when nothing is saved yet
                                         (the welcome's choice never made); never changes a saved choice
    starchaser-admin update-channel            JSON, no root needed: release or testing
    starchaser-admin update-channel-check      JSON, no root needed: can testing updates be reached?
    starchaser-admin update-channel-set release|testing   change this computer's update channel
    starchaser-admin update-rollback           JSON, no root needed: the snapshot before the last system update
    starchaser-admin recovery-update-undo <number>   undo that update, refusing if a newer update has run
    starchaser-admin home-versions             JSON, no root needed: whether hourly versions of Home are kept
    starchaser-admin home-versions on|off      keep or stop keeping them (off also removes the copies already made)
    starchaser-admin autologin                 JSON, no root needed: whether the login screen signs someone in at boot
    starchaser-admin users                     JSON, no root needed: regular computer accounts
    starchaser-admin user-password <name>      reset another account's password (one line on stdin)
    starchaser-admin own-password              JSON, no root needed: change your own password with passwd, which checks
                                         the current one (current password, then new password, one line each on stdin)
    starchaser-admin user-administrator <name> make another regular account an administrator
    starchaser-admin user-add <name> <full name...> add a standard account (password on stdin)
    starchaser-admin user-remove <name>        remove another standard account, keeping its home folder
    starchaser-admin user-reset-keyring <name> keep its saved passwords aside so they start fresh
    starchaser-admin recovery-code-status [name]   JSON, no root needed: whether an account (default: yours) has a
                                         password recovery code, and when its last one was used
    starchaser-admin recovery-code-new         make a new recovery code for your own account (asks your password);
                                         JSON with the code, shown once: only its hash is kept (recovery_code.py)
    starchaser-admin recovery-code-use <name>  the lock and login screens' "Use my recovery code" (code, then the new
                                         password, one line each on stdin): no password asked, for the person at
                                         the computer, for their own account (the login screen: any account);
                                         5 wrong codes pause tries for 10 minutes; the right one is used up
    starchaser-admin autologin on|off          sign the account that asked in automatically after a restart, or stop
                                         (greetd's initial_session; saved, so running the setup again keeps it)
    starchaser-admin password-next-start on|off   the next start shows the login screen once instead of signing in
                                         automatically (a restart from the lock screen); off: the restart didn't happen
    starchaser-admin password-next-start check    (greetd.service, as root, before greetd starts) use that mark up
    starchaser-admin hostname <name>           rename this computer (and announce the new name to your fleet at once)
    starchaser-admin fleet-networks            JSON, no root needed: where your fleet may reach this computer from
                                         (tailscale, vpn: the two switches; zones; this computer's networks,
                                         their kinds and whether someone chose them (marked); remoteLogin; ready: the fleet can reach it from a network it
                                         is on now)
    starchaser-admin fleet-networks tailscale|vpn on|off
                                         the fleet's Tailscale switch (on unless turned off) and VPN switch (off
                                         unless turned on): Starchaser's own fleet switches in the firewall (remote
                                         login, pairing, finding devices, remote desktop, Mission Control) follow
    starchaser-admin fleet-ready [<network uuid>...]
                                         get this computer ready to join a fleet: remote login on, and the
                                         networks named (default: the ones it is on now that aren't VPNs or
                                         Tailscale) counted as a network you trust; the welcome's "Join your fleet" asks first
    starchaser-admin fleet-switches-on         fleet v2 (rule 35.6): the fleet's two firewall switches, Remote login and
                                         Fleet (joining), on if they are off: remote login started, and Starchaser's
                                         own Allow for each switched on again; never a new port or a new rule
    starchaser-admin tailscale-on              install Tailscale (official repo), start it, let you run it without sudo
    starchaser-admin tailscale-off             stop Tailscale (stays installed and signed in for next time)
    starchaser-admin recovery-start          restart into independent Recovery
    starchaser-admin recovery-sizes          measure snapshot sharing without quotas
    starchaser-admin recovery-create [label]   take a system snapshot now (kept until you delete it)
    starchaser-admin recovery-undo <number>    put the system files back as they were at snapshot <number>
                                         (snapper undochange <number>..0), after a safety snapshot of now;
                                         rebuilds the boot files if the kernel changed in between; refuses snapshots from before
                                         setup finished; with --clear-stale-lock, first clears a package-manager lock
                                         an unfinished install left behind (nothing running holds it)
    starchaser-admin recovery-go-back-undo <number>  the same go-back under its own name, so the password box says
                                         "undo the last go-back" when that is what Settings asked for
    starchaser-admin recovery-boot             rebuild the startup files (kernels, initramfs) from the system files as they are now
    starchaser-admin recovery-snapshot-go-back <number>   started from snapshot <number> in the boot menu: go back
                                         to it here by swapping the system, then restart
    starchaser-admin recovery-delete <number>  delete a snapshot taken by hand (or an older "before going back" one)
    starchaser-admin recovery-keep             take hand-made and "before going back" snapshots out of the automatic cleanup
    starchaser-admin update-run <request.json> update everything (updater.py): repos, AUR (built as the
                                         user), Flatpak; streams progress as "@@{json}" lines
    starchaser-admin software-run <request.json>  install or remove an app (software.py): official repos, or AUR
                                         built as the user; same "@@{json}" progress
    starchaser-admin pacman-unlock             delete pacman's lock file when nothing that uses the package database
                                         is running (left by a crash or power cut); refused while anything is
    starchaser-admin usb-setup                 Set up USB device protection at its default level:
                                         every device plugged in now is remembered, keyboards/mice/hubs always
                                         work, anything new waits for you (idempotent; never forgets a device)
    starchaser-admin switch-to-package [--dry-run] [--channel release|testing] [--repo-url URL]
                                         [--package-dir DIR] [--keyring FILE] --user NAME
                                         snapshot, keyring, full update and package takeover, then setup as that user
                                         (passwordless sudo only during setup; removed afterward)
    starchaser-admin commands                 JSON list of the commands this copy knows (read-only, no root needed)
    starchaser-admin usb-level relaxed|strict|off   relaxed: as above; strict: new keyboards/mice wait too; off: no
                                         checks (the service stops and every device is let in)
"""
import contextlib
import fcntl
import grp
import importlib.machinery
import importlib.util
import ipaddress
import json
import os
import pwd
import re
import shutil
import subprocess
import sys
import time
import uuid
from pathlib import Path

sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import account_tools as account
import firewall as fw  # the engine, root-owned beside this file
import recovery_code

# What this copy of the helper can do. Settings reads it WITHOUT a password (`starchaser-admin commands`, the one
# command that needs no root, or this line in the world-readable file), so a page can say "this needs a newer
# Starchaser" before asking for a password, instead of getting an error from an older helper. Add new commands here
# too: command names are checked before requesting administrator permission.
COMMANDS = ("firmware", "recovery-start", "recovery-sizes", "drive-unlock", "sharing-status", "sharing-start", "sharing-stop", "firewall-commit", "firewall-commit-quick", "firewall-rollback-quick", "firewall-password-mode", "firewall-opens", "firewall-confirm", "firewall-extend", "firewall-revert", "firewall-rollback", "firewall-zones-refresh",
            "firewall-stats", "firewall-allow-app-temporary", "firewall-child-requests", "firewall-child-allow", "firewall-public-pause-on", "firewall-public-pause-off", "firewall-allow-once", "firewall-revoke-once", "firewall-allow-always", "firewall-mark-network", "firewall-forget-asked", "firewall-boot-check", "firewall-boot-load",
            "firewall-default-on", "firewall-upgrade", "route-guard-refresh", "route-guard-watch", "firewall-reload", "firewall-restart-outgoing", "firewall-outgoing-hold", "ssh", "hostname", "fleet-networks", "fleet-ready", "fleet-switches-on",
            "autologin", "home-versions", "password-next-start", "autoupdate", "autoupdate-set", "autoupdate-default", "update-channel", "update-channel-check", "update-channel-set", "switch-to-package",
            "users", "own-password", "user-password", "user-add", "user-remove", "user-reset-keyring", "user-administrator",
            "recovery-code-status", "recovery-code-new", "recovery-code-use",
            "tailscale-on", "tailscale-off", "recovery-create", "recovery-undo", "recovery-go-back-undo", "recovery-delete", "recovery-keep",
            "recovery-boot", "update-rollback", "recovery-update-undo", "recovery-update-undo-at", "recovery-snapshot-go-back",
            "update-run", "software-run", "pacman-unlock", "usb-setup", "usb-level", "usb-device", "thunderbolt-device", "welcome-session", "welcome-apply",
            "power-owner", "battery-limit", "hardware-fix", "hardware-restart", "printing-on", "language", "backup-folder", "watchdog")                                  # (watchdog: the firewall's own countdown, started by commit)
OLDER_PACKAGE = ("Nothing was changed: this part of Settings needs a newer version of Starchaser's system tools. "
                 "Open Settings > Updates and install the available updates to bring them up to date.")
OLDER_DEVELOPER = ("Nothing was changed: this part of Settings needs a newer version of Starchaser's system tools. "
                   "This copy was installed from a developer checkout, so run the checkout's setup again to bring it up to date.")


def older_message() -> str:
    """The refusal for a command this copy doesn't know. A package install is refreshed by Updates; only a developer
    checkout (no package setup file) is told to run its setup again. Settings runs the helper through the password box, so
    this is said after the password (the first refusal a person sees); a terminal gets the usage hint instead."""
    return OLDER_PACKAGE if os.path.exists(PACKAGE_SETUP) else OLDER_DEVELOPER

# A change waiting for Keep: what to go back to, kept on disk so a restart in the middle goes back too
# ({"id", "deadline", "history", "prev": policy, "prevNft": its compiled rules or null}). PENDING is the
# public part ({"id", "deadline", "history"}) that Settings reads without root.
WAITING = Path("/var/lib/starchaser/firewall-pending.json")
PENDING = Path("/run/starchaser-firewall.pending")
LOCK = Path("/var/lib/starchaser/firewall-pending.lock")
BUSY = "A firewall change is waiting for you to click Keep in Settings > Firewall. Click Keep or Go back now there first, then try again."
# Keep / Go back now name the change they were pressed for (its id); a newer change that took its place isn't kept
# or undone by a button that was showing the older one
REPLACED = ("Nothing was changed: a newer firewall change took the place of the one you were looking at. Look at "
            "Settings > Firewall again, then press Keep or Go back now.")
# Apply names the firewall its edits were made on (--base); one changed since (a notification's Allow always, the
# Keep countdown, another window) isn't silently overwritten by edits that never saw that change
# Keep / Go back now with nothing waiting any more: the countdown or another window already settled it, so neither
# "Kept your change" nor "went back" would be true from here
SETTLED = ("Nothing was changed: that change was already dealt with (the countdown ran out, or Keep or Go back now "
           "was pressed somewhere else). Look at Settings > Firewall again to see what's running.")
STALE = ("Nothing was changed: the firewall was changed somewhere else while you were deciding (a notification, "
         "the countdown, or another window). Your edits are still in Settings on top of that change; look them over "
         "and press Apply again.")


LOCK_FAILED = "Starchaser could not take its update lock, so nothing was changed. Try again, or restart the computer."


def die(msg: str) -> None:
    print(json.dumps({"ok": False, "errors": msg}))
    sys.exit(1)


def refuse(msg: str) -> None:
    """A go-back refused before anything changed: Recovery keeps its last result instead of saying it failed."""
    print(json.dumps({"ok": False, "undo": "refused", "errors": msg}))
    sys.exit(1)


def run(*cmd) -> subprocess.CompletedProcess:
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=30)
    except FileNotFoundError:
        # a helper program that isn't installed: no answer here (the callers report what failed), never a traceback
        return subprocess.CompletedProcess(cmd, 127, stdout="", stderr="")


def current_policy() -> dict:
    try:
        return json.loads(fw.POLICY.read_text())
    except (OSError, ValueError):
        return fw.validate({"enabled": False})


_held, _lock_fd = 0, -1


@contextlib.contextmanager
def locked():
    """One firewall change at a time: commit, Keep, Undo, the countdown, the restart check and the asker's
    "Allow always" each read the waiting record, change things and write it back, so they hold this while they do
    (otherwise the countdown could undo a change while "Allow always" re-applies it on top). Re-entrant within one
    process; released when the process ends, even by die()."""
    global _held, _lock_fd
    if _held == 0:
        LOCK.parent.mkdir(parents=True, exist_ok=True)
        _lock_fd = os.open(LOCK, os.O_RDWR | os.O_CREAT, 0o600)
        fcntl.flock(_lock_fd, fcntl.LOCK_EX)
    _held += 1
    try:
        yield
    finally:
        _held -= 1
        if _held == 0:
            os.close(_lock_fd)                         # closing the file releases the lock


@contextlib.contextmanager
def try_locked():
    """locked(), without waiting: yields False (and holds nothing) when another firewall change has the lock."""
    global _held, _lock_fd
    if _held:
        with locked():
            yield True
        return
    LOCK.parent.mkdir(parents=True, exist_ok=True)
    fd = os.open(LOCK, os.O_RDWR | os.O_CREAT, 0o600)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        os.close(fd)
        yield False
        return
    _held, _lock_fd = 1, fd
    try:
        yield True
    finally:
        _held = 0
        os.close(fd)


def waiting():
    try:
        w = json.loads(WAITING.read_text())
        return w if isinstance(w.get("prev"), dict) else None
    except (OSError, ValueError):
        return None


def save_waiting(w: dict) -> None:
    WAITING.parent.mkdir(parents=True, exist_ok=True)
    tmp = WAITING.with_suffix(".tmp")
    with open(tmp, "w") as f:
        f.write(json.dumps(w))
        f.flush()
        os.fsync(f.fileno())
    tmp.replace(WAITING)
    # Settings reuses the before/after permissions review during Keep, even after reopening.
    visible = {k: w.get(k) for k in ("id", "deadline", "history")}
    visible["beforePolicy"] = w.get("prev")
    fw.write_atomic(PENDING, json.dumps(visible), 0o644)


def clear_waiting() -> None:
    WAITING.unlink(missing_ok=True)
    PENDING.unlink(missing_ok=True)


def keep_unit_for_boot(policy: dict) -> str:
    """While a change waits for Keep, the firewall unit stays enabled even for an Off change: at the next start it
    is what puts the previous policy back (firewall-boot-check). Keep / the countdown set it right again.
    Returns an error string when the enable step fails, empty on success."""
    if not policy.get("enabled"):
        r = run("systemctl", "enable", "starchaser-firewall.service")
        if r.returncode:
            return "the rollback unit could not be enabled: " + (r.stderr.strip() or f"systemctl exit {r.returncode}")
    return ""


def boot_id() -> str:
    """This start of the computer (the kernel's boot id): a waiting record from an earlier start was never kept."""
    try:
        return Path("/proc/sys/kernel/random/boot_id").read_text().strip()
    except OSError:
        return ""


RESTARTED = "Not kept: the computer restarted before you clicked Keep"


def settle_restarted() -> bool:
    """A change still waiting for Keep from before the last restart (firewall-boot-check didn't get to it, say the
    unit was disabled by an older helper while it turned the firewall off): nobody can press Keep for it any more,
    and every change would be refused as BUSY with no Keep or Go back now button showing. It goes back, as a
    restart before Keep always does. Only a record that names its start (boot) is judged; call with the lock held.
    True when something was put back."""
    w = waiting()
    if not w or not w.get("boot") or not boot_id() or w["boot"] == boot_id():
        return False
    err = go_back(w, RESTARTED)
    if err:
        print(f"starchaser-admin: a change from before the restart couldn't be put back: {err}", file=sys.stderr, flush=True)
    return not waiting()


def no_policy_yet() -> bool:
    return not (fw.POLICY.exists() or fw.NFT.exists() or fw.NFT_OFF.exists())


def forget_policy() -> None:
    """Back to "no policy yet" (the firewall is already off): the files an Off policy leaves are removed."""
    for f in (fw.POLICY, fw.NFT, fw.NFT_OFF, fw.NFT_SUM):
        f.unlink(missing_ok=True)


def newest_history_key() -> list:
    """Where History ends right now (the newest entry's order key): a waiting record keeps it, so the change's own
    entry can still be found if the computer stops before its id is saved in the record."""
    keys = [list(fw.history_order(f)) for f in fw.HISTORY.glob("*.json")]
    return max(keys, default=[0, "", 0])


def trial_history_id(w: dict) -> str:
    """The History entry of the change waiting for Keep, which going back marks "tried, not kept". Its id is saved
    in the record right after the entry is written; a restart between those two steps leaves it empty, so the
    first real entry written after the record was armed is that change's (the lock keeps other commits out).
    "" only when no entry was written (a restart while it was applying) or an older record can't tell."""
    if w.get("history"):
        return w["history"]
    after = w.get("historyAfter")
    if not isinstance(after, list) or len(after) != 3:
        return ""
    after = tuple(after)
    newer = []
    for f in fw.HISTORY.glob("*.json"):
        key = fw.history_order(f)
        if key <= after:
            continue
        try:
            if json.loads(f.read_text()).get("runtimeOnly") is True:
                continue
        except (OSError, ValueError):
            continue
        newer.append((key, f.stem))
    return min(newer)[1] if newer else ""


def go_back(w: dict, summary: str) -> str:
    """Put the policy from before the waiting change back, now: the very rules that ran before it (prevNft) when
    they were kept, else compiled again. When nothing could be put back, the waiting record stays, so the countdown
    can try again and a restart still goes back (firewall-boot-check); it is cleared only once the previous policy
    is the saved one again."""
    try:
        prev = fw.validate(w["prev"])
    except fw.PolicyError as e:
        return str(e)
    saved = w.get("prevNft") if prev["enabled"] else None
    err, _ = fw.apply(prev, nft_text=saved)
    if err and saved:
        err, _ = fw.apply(prev)                        # the saved rules wouldn't load: compile them again
    if current_policy() != json.loads(json.dumps(prev)):
        return err or "the previous firewall couldn't be put back"
    if w.get("reload") and saved and err:
        # a reload trial keeps the same policy, so the policy check above proves nothing: the rules file must be
        # the previous one again, else the unkept rules are still what runs
        try:
            if zoneless(fw.strip_unused_sets(fw.NFT.read_text(), prev)) != zoneless(fw.strip_unused_sets(saved, prev)):
                return err
        except OSError:
            return err
    # (put back; an error now is about outgoing rules only, which the page reports)
    fw.snapshot(prev, summary, undid=trial_history_id(w))
    if w.get("prevMissing") and not prev["enabled"] and not err:
        forget_policy()
    clear_waiting()
    return err


def same_policy(a: dict, b: dict) -> bool:
    """Two policies say the same once validated (key order, defaults and empty fields aside); None when either
    can't be validated (then nothing is concluded)."""
    try:
        return json.dumps(fw.validate(a), sort_keys=True) == json.dumps(fw.validate(b), sort_keys=True)
    except (fw.PolicyError, AttributeError, TypeError):
        return None


def zoneless(text: str) -> str:
    """A compiled ruleset without its zone sets' interface lists (refresh_zones changes those in the running table,
    not in the file), for comparing a fresh compile with the saved rules."""
    out, prev = [], ""
    for line in text.splitlines():
        if not (prev.strip() == "type ifname" and line.strip().startswith("elements = ")):
            out.append(line)
        prev = line
    return "\n".join(out)


def same_rules_running(before: dict, policy: dict) -> bool:
    """Whether loading policy now would load the rules already running: a rename recompiles too. Compiled as apply()
    compiles it: a rule already loaded gains no port its program started listening on since (an SSH server started
    on 2222 since the last Apply); only Reload saved firewall lets those in, after its review."""
    if not policy.get("enabled"):
        return not before.get("enabled")
    try:
        saved = fw.NFT.read_text()
    except OSError:
        return False
    try:
        text, _ = fw.compile_nft(policy, fw.zone_map(policy), fw.listening(), hold=fw.loaded_report())   # as apply() would
    except fw.PolicyError:                             # the hand-written file can't be used: not the same rules
        return False
    # (address groups no rule uses are left out of both: compile_nft writes a set for each, so adding one would
    # otherwise always read as different rules, the very change the no-countdown path is for)
    return zoneless(fw.strip_unused_sets(text, policy)) == zoneless(fw.strip_unused_sets(saved, policy))


def only_enables_basic_allows(before: dict, policy: dict) -> bool:
    """Whether policy differs from before only by switching on Simple's own incoming Allow rules (managed "basic",
    allow, incoming) that were switched off: that can let more in and never takes anything away, so a countdown
    would test nothing (it can't be tried from a network the new Allow doesn't cover). Everything else must be the
    same: the other rules (in order), defaults, networks, groups and the hand-written file, and the rules running
    must be the ones the saved policy compiles to. Anything unsure is False: those changes keep the countdown."""
    try:
        before = fw.validate(before)
        if not (before.get("enabled") and policy.get("enabled")):
            return False
        b, a = before.get("rules") or [], policy.get("rules") or []
        if len(a) != len(b) or [r["id"] for r in a] != [r["id"] for r in b]:
            return False
        turned_on = 0
        for old, new in zip(b, a):
            if old == new:
                continue
            if (old.get("enabled") is not False or new.get("enabled") is not True or old.get("managed") != "basic"
                    or new.get("managed") != "basic" or new.get("dir") != "in" or new.get("action") != "allow"
                    or old.get("action") != "allow" or old.get("dir") != "in"
                    or any(k in new for k in ("icmp", "iface", "network", "rate", "sport", "state"))
                    or {k: v for k, v in old.items() if k not in ("enabled", "zones", "name")}
                    != {k: v for k, v in new.items() if k not in ("enabled", "zones", "name")}):
                return False
            turned_on += 1
        if not turned_on:
            return False
        rest = lambda p: {k: v for k, v in p.items() if k != "rules"}
        if rest(before) != rest(policy):
            return False
        lines, err = fw.extra_lines()
        if err or fw.compiled_extra_lines(fw.NFT.read_text()) != lines:
            return False
        if fw.live_managed_snapshot() is None:             # nothing running now: loading restores rules, so keep the trial
            return False
        return same_rules_running(before, before)
    except (fw.PolicyError, OSError, ValueError, KeyError):
        return False


# ---- who must type a password (decided 2026-10-14): one per sitting for changes that only tighten, a fresh one for
# anything that opens; a Settings option makes one per sitting cover every firewall change. Root decides here, not
# Settings: the quick commands (firewall-commit-quick, firewall-rollback-quick) re-check at the moment they run, and
# polkit delegates to the root verifier, which narrows a caller-bound sitting to one exact request.
class _AdminServices:
    def __getattr__(self, name):
        return globals()[name]


_admin_services = _AdminServices()

import firewall_transactions
class _AdminServices:
    def __getattr__(self, name):
        return globals()[name]


_admin_services = _AdminServices()

import firewall_policy
import firewall_grants

_firewall_authorization = None
GRANT_MINUTES = 15
MODE_FILE = Path("/var/lib/starchaser/firewall-password-mode")      # "sitting" = one password covers all changes
RANK = {"public": 0, "vpn": 1, "tailscale": 1, "trusted": 2}      # how much a zone lets in, by default
OUT_RANK = {"allow": 0, "ask": 1, "block": 2}
PING_RANK = {"any": 0, "own": 1, "never": 2}
PROTECTED_APPS = ("ssh", "tsshd", "sunshine", "starchaser-devices", "mission-control")
QUICK = ("firewall-commit-quick", "firewall-rollback-quick", "firewall-revoke-once", "firewall-forget-asked")


def _zones(rule: dict) -> set:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy._zones(_admin_services, rule)


def _rule_core(r: dict) -> dict:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy._rule_core(_admin_services, r)


def _without(r: dict, *keys) -> dict:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy._without(_admin_services, r, *keys)


def _rules_reordered(before: dict, after: dict, direction: str) -> bool:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy._rules_reordered(_admin_services, before, after, direction)


def opens_anything(before: dict, after: dict, extra_changed: bool = False) -> bool:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy.opens_anything(_admin_services, before, after, extra_changed)


RUN_USER = Path("/run/user")
HOME_ROOT = Path("/home")
PROC = Path("/proc")
CLIENT_LINE = re.compile(r"CLIENT (CONNECTED|DISCONNECTED)")


def sunshine_running() -> bool:
    try:
        return any((p / "comm").read_text().strip() == "sunshine" for p in PROC.iterdir() if p.name.isdigit())
    except OSError:
        return False


def sunshine_streaming() -> bool:
    """Whether a Moonlight client is streaming from this computer now (Derek streams to his machines): a Moonlight
    resolution profile's mark (sun-vd), or Sunshine's last client line, from its journal or its own log file, says
    CONNECTED while Sunshine runs. Can't tell: not streaming (logind's answer still counts)."""
    try:
        if any(RUN_USER.glob("*/sun-vd.active")):
            return True
    except OSError:
        pass
    if not sunshine_running():
        return False
    last = ""
    try:
        out = run("journalctl", "-q", "-o", "cat", "--no-pager", "-n", "4000", "--since", "-2d", "_COMM=sunshine").stdout
        last = ([m.group(1) for m in CLIENT_LINE.finditer(out)] or [""])[-1]
    except (OSError, subprocess.SubprocessError):
        pass
    if not last:
        try:
            logs = sorted(HOME_ROOT.glob("*/.config/sunshine/sunshine.log"), key=lambda p: p.stat().st_mtime)
        except OSError:
            logs = []
        for log in logs[-1:]:
            try:
                with open(log, "rb") as fh:
                    fh.seek(max(0, log.stat().st_size - 262144))
                    text = fh.read().decode(errors="replace")
            except OSError:
                continue
            last = ([m.group(1) for m in CLIENT_LINE.finditer(text)] or [""])[-1]
    return last == "CONNECTED"


def local_console_change() -> bool:
    """Positive logind evidence that this request came from the person at the computer; uncertainty keeps Keep."""
    uid = sitting_user()
    if uid < 1000: return False
    try:
        result = run("loginctl", "show-user", str(uid), "-p", "Display", "--value")
        if result.returncode or not result.stdout.strip(): return False
        session = run("loginctl", "show-session", result.stdout.strip(), "-p", "Active", "-p", "Remote", "-p", "Type")
        values = dict(line.split("=", 1) for line in session.stdout.splitlines() if "=" in line)
        return session.returncode == 0 and values.get("Active") == "yes" and values.get("Remote") == "no" and values.get("Type") in ("wayland", "x11")
    except (OSError, ValueError, subprocess.SubprocessError): return False


def remote_session() -> bool:
    """Whether someone is signed in from another computer now (logind's Remote flag) or streams this computer's
    screen with Moonlight: a change that cuts off remote login or the stream would end that session, so it gets
    the Keep countdown."""
    try:
        sessions = run("loginctl", "list-sessions", "--no-legend")
        if sessions.returncode: return True
        for line in sessions.stdout.splitlines():
            sid = line.split()[0] if line.split() else ""
            if not sid: continue
            answer = run("loginctl", "show-session", sid, "-p", "Remote", "--value")
            if answer.returncode or answer.stdout.strip() != "no": return True
    except (OSError, subprocess.SubprocessError):
        return True                                         # can't tell: assume someone is
    return sunshine_streaming()


def _block_may_hit_protected(block: dict, before: dict, after: dict) -> bool:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy._block_may_hit_protected(_admin_services, block, before, after)


PROGRAM_PATH = "/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/sbin:/bin:/sbin:/usr/lib/ssh:/opt/bin"


def _app_absent(rule: dict) -> bool:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy._app_absent(_admin_services, rule)


def _inactive_allow(rule: dict) -> bool:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy._inactive_allow(_admin_services, rule)


def lockout_risk(before: dict, after: dict) -> bool:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy.lockout_risk(_admin_services, before, after)


def away_only_now(before: dict, after: dict) -> bool:
    """Compatibility entry point; firewall_policy owns this operation."""
    return firewall_policy.away_only_now(_admin_services, before, after)


def sitting_user() -> int:
    try:
        return int(os.environ.get("PKEXEC_UID", "-1"))
    except ValueError:
        return -1


def grant_remaining(kind: str, uid: int) -> float:
    try:
        who = firewall_grants.principal(os.getpid(), uid)
        command = "firewall-commit" if kind == "all" else "firewall-commit-quick"
        return firewall_grants.remaining(who, command)
    except (OSError, ValueError, KeyError, StopIteration):
        return 0


def grant_fresh(kind: str, uid: int) -> bool:
    return grant_remaining(kind, uid) > 0


def sitting_mode_all() -> bool:
    try:
        return MODE_FILE.read_text().strip() == "sitting"
    except OSError:
        return False


class Sitting:
    """A consumed exact-request token never starts or extends the authenticated sitting."""
    def __init__(self, cmd: str):
        self.uid = sitting_user()
        self.cmd = cmd
        self.free = bool(_firewall_authorization)

    def done(self) -> None:
        if os.geteuid() != 0 or self.uid < 0 or self.free or self.cmd not in firewall_grants.QUICK + firewall_grants.OTHER:
            return
        try:
            who = firewall_grants.principal(os.getpid(), self.uid)
            firewall_grants.start(who, sitting_mode_all())
        except (OSError, ValueError, KeyError, StopIteration):
            pass  # identity unavailable: the next change asks again


def password_mode(argv: list) -> dict:
    """firewall-password-mode [sitting|each]: read (no root) or set (asks for the password) whether one password per
    sitting covers every firewall change. Changing it ends any such grant."""
    if len(argv) == 1:
        return {"ok": True, "errors": "", "mode": "sitting" if sitting_mode_all() else "each"}
    if argv[1] not in ("sitting", "each"):
        die("bad choice")
    MODE_FILE.parent.mkdir(parents=True, exist_ok=True)
    if argv[1] == "sitting":
        MODE_FILE.write_text("sitting\n")
        os.chmod(MODE_FILE, 0o644)
    else:
        MODE_FILE.unlink(missing_ok=True)
    firewall_grants.clear_all()
    return {"ok": True, "errors": "", "mode": argv[1]}


def extras_changed() -> bool:
    """The hand-written rules file differs from what is running: loading would add them."""
    try:
        lines, err = fw.extra_lines()
        return bool(err) or fw.compiled_extra_lines(fw.NFT.read_text()) != lines
    except (OSError, ValueError, AttributeError):
        return True


def quick_check(cmd: str, new_policy: dict) -> bool:
    """Whether a commit or rollback only tightens. The quick commands (polkit may let them through without the
    password during a sitting) refuse here, before anything changes, when it doesn't: Settings then asks the
    ordinary way. The ordinary commands only get the answer: their password starts a sitting either way (Sitting)."""
    before = current_policy()
    tight = not opens_anything(before, new_policy, extras_changed() if before.get("enabled") else False)
    if cmd.endswith("-quick") and not tight:
        print(json.dumps({"ok": False, "needsPassword": True,
                          "errors": "This change opens something, so it needs your password. Nothing was changed."}))
        sys.exit(1)
    return tight


def firewall_opens(argv: list) -> dict:
    """firewall-opens <policy.json> | firewall-opens --history <id>: read-only (no root), so Settings can pick the
    quick command when a change only tightens. Root checks again when the quick command runs; this answer is only
    a guess about which command to try. Unreadable means opens. "password": whether Apply would ask for the
    password now, for the person asking (the grants polkit reads, as Sitting does), so Settings words its bar.
    "lockoutRisk" previews the same assessment as Apply; unreadable is unknown (null). "freeFor": how many seconds
    that no-password answer still holds (polkit's grant runs out 15 minutes after the password was typed)."""
    uid = os.getuid() if os.getuid() != 0 else sitting_user()

    def answer(opens: bool, lockout=None) -> dict:
        free = uid >= 0 and (grant_fresh("all", uid) or (not opens and grant_fresh("tighten", uid)))
        left = max((grant_remaining(kind, uid) for kind in (("all", "tighten") if not opens else ("all",))), default=0) if free else 0
        return {"ok": True, "errors": "", "opens": opens, "password": not free,
                "freeFor": round(max(left, 0.0), 1), "lockoutRisk": lockout}
    try:
        before = json.loads(fw.POLICY.read_text())
        if argv[1] == "--history" and len(argv) == 3 and fw.HISTORY_ID.fullmatch(argv[2]):
            after = json.loads((fw.HISTORY / f"{argv[2]}.json").read_text())["policy"]
        else:
            after = json.loads(Path(argv[1]).read_text())
        before, after = fw.validate(before), fw.validate(after)
        risk = (lockout_risk(before, after) and not away_only_now(before, after)) or (after["enabled"] and extras_changed())
        # the same question root asks in quick_check: unloaded hand-written rules make any change an opening one
        return answer(opens_anything(before, after, extras_changed() if before.get("enabled") else False), risk)
    except (OSError, ValueError, KeyError):
        return answer(True)


def capture_apply_state():
    """Compatibility entry point; firewall_transactions owns this operation."""
    return firewall_transactions.capture_apply_state(_admin_services)


def restore_apply_state(state, before, before_nft, keep_unit=False) -> str:
    """Compatibility entry point; firewall_transactions owns this operation."""
    return firewall_transactions.restore_apply_state(_admin_services, state, before, before_nft, keep_unit)


def failed_apply_message(err: str, back_err: str) -> str:
    """Compatibility entry point; firewall_transactions owns this operation."""
    return firewall_transactions.failed_apply_message(_admin_services, err, back_err)


def commit(policy_raw: dict, timeout: int, summary: str, fold=None, base=None,
           nft_text=None, reconnect=False, force_timed=False, force_keep=False) -> None:
    """Compatibility entry point; firewall_transactions owns this operation."""
    return firewall_transactions.commit(_admin_services, policy_raw, timeout, summary, fold, base, nft_text, reconnect, force_timed, force_keep)


def home_addresses() -> None:
    """A network was switched to or from Home (Trusted): Wi-Fi profiles follow now, with the real hardware address for
    Home networks, and reconnect to use it. Never stops the change that called it."""
    if os.geteuid() != 0:
        return                # profiles are changed by the root helper only
    try:
        fw.firewall_identity.home_address_sync(fw, current_policy())
    except (OSError, ValueError, SystemExit, subprocess.SubprocessError):
        pass


def public_pause_change(on: bool, *, undo_only: bool = False) -> dict:
    """One press saves Public and pauses in the same nft transaction, with a matching undo."""
    if waiting():
        return {"ok": False, "errors": BUSY}
    try:
        raw = json.loads(fw.POLICY.read_text())
        if not isinstance(raw, dict):
            raise ValueError("not firewall settings")
        before = fw.validate(raw)
    except (OSError, ValueError, fw.PolicyError):
        return {"ok": False, "errors": "The firewall settings couldn't be read, so nothing was changed."}
    if not before["enabled"]:
        return {"ok": False, "errors": "The firewall is off now, so nothing was changed."}

    def end_only(message):
        previous = fw.public_pause_state()
        err = fw.public_pause(False)
        pause = fw.public_pause_state()
        if not err and previous != pause:
            fw.snapshot(before, message, runtime_only=True)
        return {"ok": not err, "errors": err, "message": message, "publicPause": pause}

    undo_path = fw.PUBLIC_PAUSE.with_suffix(".undo.json")
    if on:
        # Repeated requests must not replace the original trust settings with Public as the undo target.
        if fw.public_pause_state()["on"]:
            return {"ok": True, "errors": "", "message": "Public pause is already on.",
                    "publicPause": fw.public_pause_state()}
        after, captured, undo = fw.public_pause_plan(before, fw.active_networks(), fw.zone_map(before))
        if not captured:
            return {"ok": False, "errors": "No network is connected that Public pause can pause."}
        try:
            undo["pause"] = json.loads(fw.PUBLIC_PAUSE.read_text())
        except (OSError, ValueError):
            undo["pause"] = []
        message = ("This network is now Public and new connections are paused." if len(captured) == 1
                   else "These networks are now Public and new connections are paused.")
    else:
        try:
            undo = json.loads(undo_path.read_text())
        except FileNotFoundError:
            # Pauses started before this feature have no saved trust change to undo.
            return end_only("Public pause ended. Your usual firewall permissions apply.")
        except (OSError, ValueError):
            undo = None
        if not fw.public_pause_undo_matches(before, undo):
            if undo_only:
                return {"ok": False, "errors": "A network setting changed after Public pause. Review it in Settings > Firewall before undoing."}
            # A later trust edit makes restoring both unsafe, but the switch can still end the pause.
            return end_only("Public pause ended. Later network settings were kept.")
        after = json.loads(json.dumps(before))
        after["networks"] = undo["beforeNetworks"]
        after = fw.validate(after)
        captured = undo["pause"]
        names = []
        for n in fw.active_networks():
            old = next((x for x in after['networks'] if x['uuid'] == n['uuid']), None)
            if old and old['zone'] == 'trusted':
                name = n.get('name', '')
                if re.fullmatch(r'Wired connection \d+', name) and 'ethernet' in n.get('type', ''): name = "Your cable (Ethernet) connection"
                names.append(name + " is Trusted again.")
        message = "Public pause ended. " + (" ".join(names) or "Your earlier network settings apply again.")
    state = capture_apply_state()
    before_nft = state[2].get(fw.NFT)
    try:
        fw.pause_write(fw.PUBLIC_PAUSE, json.dumps(captured) + "\n")
        if on:
            fw.pause_write(undo_path, json.dumps(undo) + "\n")
        err, _ = fw.apply(after)
        if err:
            raise RuntimeError(err)
        if not on:
            fw.pause_write(undo_path, None)
    except Exception as e:
        back_err = restore_apply_state(state, before, before_nft[0] if before_nft else None)
        return {"ok": False, "errors": failed_apply_message(str(e), back_err)}
    pause = fw.public_pause_state()
    if on and len(pause["ifaces"]) < len({n["iface"] for n in captured}):
        message = ("Connected networks are now Public and paused. Some networks disconnected before the pause finished."
                   if pause["on"] else "The network is now Public. It disconnected before the pause finished. Undo restores its earlier setting.")
    fw.snapshot(after, message, runtime_only=True)
    warning = " ".join(fw.WARNINGS)
    if on and run("systemctl", "is-active", "--quiet", "sshd.service").returncode == 0:
        warning = (warning + " " if warning else "") + (
            "Remote login is still on, so computers already signed in to this one stay connected. If you don't use it, turn it off in Settings > Security.")
    return {"ok": True, "errors": "", "message": message, "warning": warning,
            "publicPause": pause}


def restart_outgoing() -> None:
    """Recover outgoing checks without compiling or replacing incoming rules or pending file edits."""
    if waiting():
        die(BUSY)
    try:
        pol = fw.validate(current_policy())
        fw.WARNINGS.clear()
        fw.ensure_osn_dropin()
        err = fw.apply_opensnitch(pol, fw.zone_map(pol), reconnect=True)
    except (fw.PolicyError, OSError) as e:
        die(str(e))
    refresh_stats()
    print(json.dumps({"ok": not err, "errors": err, "warning": " ".join(fw.WARNINGS)}))


def reload_rules(reconnect=False, repair=False) -> None:
    """Repair unchanged rules immediately; changed compiled permissions need Keep, including handwritten edits.
    Compare against the last loaded file, so repairing drift doesn't ask to keep the same settings. Compile once
    and pass that exact text to commit: a handwritten edit or a newly listening app can't race the comparison.
    The existing waiting record saves the previous compiled text before loading, for timeout and reboot recovery.
    repair ("Put my rules back" after an outside change): load the saved rules exactly as they last ran, without
    reading firewall-extra.nft, so a hand-written edit not applied yet (even a broken one) can't stop the repair or
    slip in with it. With no saved rules, it is an ordinary reload.
    """
    if waiting():
        die(BUSY)
    try:
        pol = fw.validate(current_policy())
    except fw.PolicyError as e:
        die(str(e))
    saved_text = None
    if repair and pol["enabled"]:
        try:
            saved_text = fw.NFT.read_text() or None
        except (OSError, ValueError):
            saved_text = None
    try:
        text = (saved_text if saved_text is not None else
                fw.compile_nft(pol, fw.zone_map(pol), fw.listening())[0] if pol["enabled"] else None)
    except fw.PolicyError as e:
        die(str(e))
    observed = fw.capture_drift_audit(pol)
    if text is not None and saved_text is None:
        try:
            saved = fw.NFT.read_text()
        except (OSError, ValueError):
            saved = None                               # missing or unreadable: rebuilding it is the repair, as before
        if saved is not None and zoneless(fw.strip_unused_sets(text, pol)) != zoneless(fw.strip_unused_sets(saved, pol)):
            commit(pol, 30, "Loaded changed firewall rules.",
                   nft_text=text, reconnect=reconnect, force_timed=True)
            fw.audit_repair(pol, observed)
            return
    state = None

    def capture():
        nonlocal state
        state = capture_apply_state()

    try:
        if saved_text is not None:
            err, _ = fw.apply(pol, nft_text=saved_text, reconnect=reconnect, before_mutation=capture)
        else:
            err, _ = fw.apply(pol, prepared_text=text, reconnect=reconnect, before_mutation=capture)
    except Exception as e:
        err = str(e) or type(e).__name__
    if err:
        saved_nft = state[2].get(fw.NFT) if state else None
        back_err = restore_apply_state(state, pol, saved_nft[0] if saved_nft else None)
        err = failed_apply_message(err, back_err)
    if not err:
        if observed:
            fw.audit_repair(pol, observed)
        else:
            fw.snapshot(pol, "Loaded the firewall again", reload_only=True)
        refresh_stats_after_entry()
    print(json.dumps({"ok": not err, "errors": err}))


def boot_check() -> None:
    """starchaser-firewall.service, before the network starts: the computer restarted while a change waited for
    Keep, so it was never kept. Put the previous policy's files back (the unit then loads them); the daemons are
    only queued, nothing here waits for the network."""
    w = waiting()
    if not w:
        PENDING.unlink(missing_ok=True)
        return
    try:
        prev = fw.validate(w["prev"])
    except fw.PolicyError:
        prev = fw.validate({"enabled": False})
    fw.ETC.mkdir(parents=True, exist_ok=True)
    empty = {z: [] for z in fw.ZONES}
    if prev["enabled"]:
        try:
            text = w.get("prevNft") or fw.compile_nft(prev, empty, {})[0]
        except fw.PolicyError:                         # the hand-written file can't be used: start without it
            text = fw.compile_nft(prev, empty, {}, [])[0]
        tmp = fw.NFT.with_suffix(".nft.tmp")
        fw.write_atomic(tmp, text, 0o644)
        tmp.replace(fw.NFT)
        fw.NFT_OFF.unlink(missing_ok=True)
        mark_sum_after_boot()
        run("systemctl", "enable", "--no-reload", "starchaser-firewall.service")
    else:
        if fw.NFT.exists():
            fw.NFT.replace(fw.NFT_OFF)
        fw.NFT_SUM.unlink(missing_ok=True)
        run("systemctl", "disable", "--no-reload", "starchaser-firewall.service")
    fw.write_atomic(fw.POLICY, json.dumps(prev, indent=2) + "\n", 0o644)
    fw.apply_opensnitch(prev, empty, boot=True)
    fw.snapshot(prev, RESTARTED, undid=trial_history_id(w))
    if w.get("prevMissing") and not prev["enabled"]:
        forget_policy()
    clear_waiting()


def mark_sum_after_boot() -> None:
    """Saved rules the unit will load at the next start without anything loading them now: the first stats() after
    that records the shape of the table it finds (so the Rules tab can check the rules are running)."""
    fw.write_atomic(fw.NFT_SUM, fw.SUM_AFTER_BOOT + "\n")


def auto_summary(before: dict, after: dict) -> str:
    """What a commit changed, for History and the Undo card, when the caller gave no summary (the command line;
    Settings always sends its own): "Turned the firewall on; added Allow laptop to use TCP 8080 (from the command line)." """
    parts = []
    if bool(before.get("enabled")) != bool(after.get("enabled")):
        parts.append("turned the firewall " + ("on" if after.get("enabled") else "off"))
    name = lambda r: r.get("name") or r.get("app") or "a rule"
    old = {r.get("id"): r for r in before.get("rules") or []}
    new = {r.get("id"): r for r in after.get("rules") or []}
    added = [name(r) for i, r in new.items() if i not in old]
    removed = [name(r) for i, r in old.items() if i not in new]
    changed = [name(r) for i, r in new.items() if i in old and old[i] != r]
    for verb, names in (("added", added), ("removed", removed), ("changed", changed)):
        if names:
            parts.append(f"{verb} " + ", ".join(names[:3]) + (f" and {len(names) - 3} more" if len(names) > 3 else ""))
    if (before.get("networks") or []) != (after.get("networks") or []):
        parts.append("changed which networks you trust")
    for key, words in (("addresses", "address groups"), ("services", "port groups"), ("defaults", "the defaults")):
        if before.get(key) != after.get(key) and (before.get(key) or after.get(key)):
            parts.append(f"changed {words}")
    text = "; ".join(parts) or "loaded the same settings again"
    return fw.bounded_summary(text[0].upper() + text[1:] + " (from the command line)")


def first_rules() -> list:
    """Starchaser's first policy (the same as Settings > Firewall's, with the names it shows): incoming blocked
    except remote login, pairing and finding devices, from networks you trust and wherever the fleet's
    switches say (fw.fleet_zones(): Tailscale unless turned off). Remote login is let in even while it's off, so
    turning it on later in Security just works (nothing listens until then); the fast remote terminal only when it
    is installed."""
    apps = (("ssh", "Remote login"), ("tsshd", "Fast remote terminal"),
            ("starchaser-devices", "Fleet (joining)"), ("mdns", "Finding nearby devices"))
    return [{"id": "b-" + app, "name": name, "enabled": True, "dir": "in", "action": "allow",
             "zones": fw.fleet_zones(), "peers": ["any"], "user": "any", "app": app,
             "service": "app-default", "log": False, "managed": "basic"}
            for app, name in apps if app != "tsshd" or shutil.which("tsshd")]


def installer_network() -> dict:
    """The network the installer was told to trust (its trust_network answer, decided 2026-11-05 #4) as a policy
    entry, or {}. Read once: the file is removed whatever it holds. A cable comes with its router (the identity):
    the new system's automatic cable connection has a new id, and only that router makes it this network."""
    try:
        x = json.loads(fw.INSTALL_NETWORK.read_text())
    except (OSError, ValueError):
        x = None
    fw.INSTALL_NETWORK.unlink(missing_ok=True)
    if not isinstance(x, dict) or not UUID.fullmatch(str(x.get("uuid", ""))):
        return {}
    entry = {"uuid": x["uuid"], "name": fw.clean_name(x.get("name", ""), 80), "zone": "trusted"}
    if "identity" in x:
        ident = fw.clean_identity(x["identity"])
        if not ident:
            return {}                                  # a network it can't tell apart from others: trust none
        entry["identity"] = ident
    return entry


def default_on() -> None:
    """Setup (the installer runs the desktop setup in the new system): the firewall starts on even if the welcome
    is skipped. Only when there is no policy at all: someone's own choice, Off included, is never changed. In the
    installer nothing is loaded (the rules file and the unit are ready for the first start). No network is marked
    as a network you trust: each one counts as Public until you answer the one-time question (starchaser firewall ask asks
    "Is this a network you trust?" once per network) or choose in Settings > Firewall. The one exception is the
    network the installer ran on, when it was told to trust it (installer_network)."""
    if fw.POLICY.exists() or fw.NFT.exists() or fw.NFT_OFF.exists():
        fw.INSTALL_NETWORK.unlink(missing_ok=True)
        print(json.dumps({"ok": True, "errors": "", "changed": False}))
        return
    here = installer_network()
    pol = fw.validate({"enabled": True, "unknownZone": "public", "networks": [here] if here else [],
                       "rules": first_rules(), "privacy": fw.privacy_engine.DEFAULT, "recordActivity": False})
    # (never "(the first network after setup)": that names the retired self-trust, whose networks are asked again)
    summary = ("Turned on during setup" + (f"; {here['name'] or 'the network it was installed on'} counts as a "
                                           "network you trust, as chosen in the installer" if here else ""))[:150]
    fw.ETC.mkdir(parents=True, exist_ok=True)
    if run("systemd-detect-virt", "-q", "--chroot").returncode == 0:
        text, _ = fw.compile_nft(pol, {z: [] for z in fw.ZONES}, {})
        tmp = fw.NFT.with_suffix(".nft.tmp")
        fw.write_atomic(tmp, text, 0o644)
        tmp.replace(fw.NFT)
        fw.write_atomic(fw.POLICY, json.dumps(pol, indent=2) + "\n", 0o644)
        mark_sum_after_boot()
        en = run("systemctl", "enable", "starchaser-firewall.service")
        if en.returncode != 0 or run("systemctl", "is-enabled", "--quiet", "starchaser-firewall.service").returncode != 0:
            # a firewall that says On but won't start with the computer is worse than none: leave no policy, so
            # Settings and the welcome show it as off (and offer to turn it on), and setup says it failed
            for f in (fw.POLICY, fw.NFT, fw.TRUST_FIRST, fw.NFT_SUM):
                f.unlink(missing_ok=True)
            die("The firewall wasn't turned on: it couldn't be set to start with the computer ("
                + ((en.stderr or en.stdout).strip() or "systemctl enable failed") + ").")
        fw.snapshot(pol, summary)
        print(json.dumps({"ok": True, "errors": "", "changed": True}))
        return
    commit(pol, 0, summary)


SETUP_LOG = Path("/var/log/starchaser-install.log")     # the installer copies its log here as its very last step


def snaps() -> dict:
    r = subprocess.run(["snapper", "--jsonout", "-c", "root", "list"], capture_output=True, text=True)
    try:
        return {s["number"]: s for s in json.loads(r.stdout)["root"]}
    except (ValueError, KeyError):
        die("Settings couldn't read the list of snapshots. Nothing was changed.")


def tag(s: dict) -> str:
    """starchaser=setup (the installer's baseline), safety (taken before going back), hand (Take a snapshot now).
    Older safety and hand-made snapshots have no tag: they're known by their description."""
    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


def stamp(s: dict) -> float:
    try:
        return time.mktime(time.strptime(s.get("date", ""), "%Y-%m-%d %H:%M:%S"))
    except ValueError:
        return 0


def too_early(n: int, known: dict) -> bool:
    """Snapshots from before Starchaser finished installing: older than the installer's baseline or, on computers
    installed before there was one, taken before the install log was written. They hold a half-built system (no login
    screen) with the installer's no-password sudo rule still in place. starchaser recovery hides the same ones."""
    base = [m for m, s in known.items() if tag(s) == "setup"]
    if base:
        return n < min(base)
    try:
        return stamp(known[n]) <= SETUP_LOG.stat().st_mtime
    except OSError:
        return False


def keep_hand_made(known: dict) -> None:
    """Snapshots taken by hand and before going back used to have snapper's number cleanup, which deleted them
    although Settings said they're kept until you delete them. Take them out of the cleanup (once, quietly)."""
    for m, s in known.items():
        if s.get("type") == "single" and s.get("cleanup") == "number" and \
                tag(s) in ("hand", "safety"):
            subprocess.run(["snapper", "-c", "root", "modify", "--cleanup-algorithm", "", str(m)], capture_output=True)


def fmt(s: dict) -> str:
    t = stamp(s)
    return time.strftime("%b %-d, %-I:%M %p", time.localtime(t)) if t else "an earlier snapshot"


def _recovery_engine():
    from recovery_engine import RecoveryEngine
    return RecoveryEngine(
        take_pacman_lock=take_pacman_lock,
        update_rollback=update_rollback,
        installed_versions=installed_versions,
        undo_checked=undo_checked,
        note_update_undone=note_update_undone,
        sync_boot_menu=sync_boot_menu,
        PACMAN_LOCK=PACMAN_LOCK,
        snaps=snaps,
        refuse=refuse,
        too_early=too_early,
        PACKAGE_SETUP=PACKAGE_SETUP,
        BOOT_INPUTS=BOOT_INPUTS,
        undo_locked=undo_locked,
        keep_hand_made=keep_hand_made,
        go_back_names=go_back_names,
        tag=tag,
        fmt=fmt,
        recovery_destination=recovery_destination,
        update_channel=update_channel,
        local_packages=local_packages,
        log_go_back=log_go_back,
        rebuild_boot=rebuild_boot,
        stamp=stamp,
    )


def recovery_undo(n: int, clear_stale: bool = False) -> None:
    """Compatibility door; the recovery engine owns this transaction."""
    return _recovery_engine().recovery_undo(n, clear_stale)


def update_rollback(number=None) -> dict:
    import update_history
    if not Path("/etc/snapper/configs/root").exists():
        return {"ok": True, "available": False, "reason": "System snapshots aren't set up on this computer."}
    known = snaps()
    try:
        n = update_history.last_snapshot(known) if number is None else number
        if number is not None and number not in update_history.undo_targets(known):
            raise ValueError("That update's snapshot is no longer available. Nothing was changed.")
    except (OSError, ValueError) as error:
        return {"ok": True, "available": False, "reason": str(error) if isinstance(error, ValueError)
                else "The last update's snapshot couldn't be checked. Try again."}
    if too_early(n, known):
        return {"ok": True, "available": False, "reason": "That update was part of setting up Starchaser, so it can't be undone here."}
    if predates_package(n):
        # the go-back itself refuses this (undo_checked); say so here instead of after the password and a progress bar
        return {"ok": True, "available": False, "reason": "That update came before this computer got Starchaser's "
                "packages, so it can't be undone: going back would take away the desktop's own files. "
                "To undo a later change, open Recovery."}
    import updater
    undone = updater.read_undone()
    if undone and undone.get("target") == n:
        # already undone: offering the same undo again would only go back to where the computer already is
        return {"ok": True, "available": False, "undone": True,
                "reason": updater.undone_skip(undone) + " To undo going back, open Recovery."}
    from update_experience import settings_difference
    comparison = settings_difference(n) if number is not None else {'settings': [], 'settingsWarning': ''}
    return {"ok": True, "available": True, **comparison, "number": n, "time": int(stamp(known[n])), "date": fmt(known[n]), "undoUntil": update_history.deadline(known[n])}


def recovery_update_undo(n: int, historical=False) -> None:
    # Recheck under both locks: the confirmation must never silently undo a different, newer update.
    take_pacman_lock()
    try:
        current = update_rollback(n) if historical else update_rollback()
        if not current.get("available") or current["number"] != n:
            refuse("The last update's snapshot changed or is no longer available. Nothing was changed. Open Updates again and check before continuing.")
        before = installed_versions()
        undo_checked(n)
        note_update_undone(current, before)
        # the same as from Recovery (recovery_undo): the boot menu's own sync ran when the safety snapshot appeared,
        # while this held pacman's lock, so it saw "an update is running", and Recovery said an update was changing
        # the kernel until the next snapshot or restart (QA 20261107-1123 005). Written again now, under the same lock.
        sync_boot_menu(wait=10)
    finally:
        PACMAN_LOCK.unlink(missing_ok=True)


def note_update_undone(current: dict, before: dict, always: bool = True) -> None:
    """After going back to the last update's snapshot (current: update_rollback's answer): the versions this took
    away, which automatic updates don't put exactly back (updater.skip_undone), and the undo for Recent updates.
    always=False (a go-back from Recovery or the boot menu): only when it did take versions away."""
    after = installed_versions()
    undone = {name: version for name, version in before.items() if after.get(name) != version}
    log_went_back(current["number"], before, after)
    import updater
    if undone:
        updater.write_undone(current["number"], current["date"], undone)
    if undone or always:
        try:
            __import__("update_health").cancel()
            updater.note_undo(current["time"], current["date"])     # for Recent updates; the undo itself is done
        except OSError:
            pass


def log_went_back(n: int, before: dict, after: dict) -> None:
    """One line in pacman.log and the journal for an undo: /var/log is outside the snapshot, so pacman.log still said
    the update's packages were installed while pacman -Q said they were gone (QA 20261107-1549 003)."""
    groups = (("removed", [f"{p} {v}" for p, v in sorted(before.items()) if p not in after]),
              ("changed", [f"{p} ({v} -> {after[p]})" for p, v in sorted(before.items()) if p in after and after[p] != v]),
              ("added", [f"{p} {v}" for p, v in sorted(after.items()) if p not in before]))
    line = f"went back to snapshot {n}; " + ("; ".join(f"{w}: {', '.join(l)}" for w, l in groups if l) or "no package changed")
    try:
        with PACMAN_LOG.open("a") as f:
            f.write(f"[{time.strftime('%Y-%m-%dT%H:%M:%S%z')}] [STARCHASER] {line}\n")
    except OSError:
        pass
    try:
        import syslog
        syslog.openlog("starchaser-admin")
        syslog.syslog(syslog.LOG_NOTICE, line)
    except OSError:
        pass


def installed_versions() -> dict:
    try:
        r = subprocess.run(["pacman", "-Q"], capture_output=True, text=True)
    except OSError:
        return {}
    return dict(line.split(None, 1) for line in r.stdout.splitlines() if len(line.split()) == 2)


# Files the startup files are built from besides the kernel itself: a go-back that changes one of these (a bad
# mkinitcpio.conf, a hook, a module option, firmware, the kernel command line) must rebuild them too, or the broken
# initramfs built from the bad version stays in /boot while the page offers Restart
BOOT_INPUTS = (" /usr/lib/modules/", " /etc/mkinitcpio.conf", " /etc/mkinitcpio.d/", " /usr/lib/initcpio/",
               " /etc/initcpio/", " /etc/modprobe.d/", " /usr/lib/modprobe.d/", " /etc/vconsole.conf",
               " /usr/lib/firmware/", " /etc/kernel/", " /etc/default/limine", " /etc/limine-entry-tool.conf",
               " /usr/lib/limine/", " /usr/bin/mkinitcpio", " /etc/crypttab")


PACKAGE_SETUP = "/usr/share/starchaser/installer/starchaser-desktop-setup.sh"   # in starchaser-desktop


SNAPSHOTS = Path("/.snapshots")


def predates_package(n: int) -> bool:
    """Snapshot n has no starchaser-desktop although this computer has it now (undo_checked's "+" test, read from the
    snapshot's own files so the offer needs no root: wheel can read /.snapshots). Unreadable = not known, so the
    offer stays and undo_checked still refuses under the 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 undo_checked(n: int) -> None:
    """Compatibility door; the recovery engine owns this transaction."""
    return _recovery_engine().undo_checked(n)


def take_pacman_lock(clear_stale: bool = False) -> None:
    """Take pacman's lock, or refuse with nothing changed. A lock left by a crash or power cut (often exactly when
    going back is needed) is said plainly, with lockStale so the page can offer to clear it; it's never deleted here.
    Starchaser's own run lock first: between an update's AUR builds pacman's lock is free, but the update still runs
    (and keeps running after its page closes), so going back then would roll the system back under the build."""
    import updater
    if not updater.hold_run_lock():
        die(LOCK_FAILED if updater.lock_unavailable else "An install or update is running. Wait for it to finish, then try again. Nothing was changed.")
    # "Remove it and continue" (clear_stale): a lock judged stale is cleared here, under the same checks as
    # pacman-unlock, so one password prompt covers both the unlock and the retried job
    if clear_stale and updater.clear_stale_lock() == "busy":
        die("An install or update is running. Wait for it to finish, then try again. Nothing was changed.")
    try:
        os.close(os.open(PACMAN_LOCK, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644))
    except FileExistsError:
        if updater.pacman_lock_state() == "stale":
            print(json.dumps({"ok": False, "lockStale": True, "errors":
                              "An earlier install or update stopped partway (the power may have gone off) and left "
                              "behind a note saying it's still running. Nothing was changed. Nothing is running now, so "
                              "it's safe to remove."}))
            sys.exit(1)
        die("An install or update is running. Wait for it to finish, then try again. Nothing was changed.")


def scrub_lock(number: str) -> None:
    """The snapshot just taken by hand holds the pacman lock recovery-create held while taking it. Take it out of the
    snapshot (best effort), so booting into that snapshot from the boot menu doesn't find a note saying an install
    is running. If this fails nothing is lost: the snapper filter keeps db.lck out of going back, and a lock nobody
    holds is offered for removal as a stale one (snap-pac's automatic snapshots carry one the same way)."""
    lock = Path(f"/.snapshots/{number}/snapshot") / PACMAN_LOCK.relative_to("/")
    try:
        if not lock.exists():
            return
    except OSError:
        return
    rw = subprocess.run(["snapper", "-c", "root", "modify", "--read-write", number], capture_output=True)
    if rw.returncode != 0:
        return
    try:
        lock.unlink(missing_ok=True)
    except OSError:
        pass
    finally:
        for _ in range(3):                          # never leave the snapshot writable
            if subprocess.run(["snapper", "-c", "root", "modify", "--read-only", number],
                              capture_output=True).returncode == 0:
                break


def recovery_boot(clear_stale: bool = False) -> None:
    """Rebuild the startup files from the system files as they are now (after a go-back whose rebuild failed: going
    back to the same snapshot again changes no files, so it wouldn't rebuild them), then the boot menu's snapshot
    entries from them (Add them now). "bootMenu": how many it lists now, -1 when it couldn't be written."""
    import updater
    try:
        with updater.SystemChange("boot") as change:
            take_pacman_lock(clear_stale)
            try:
                boot = rebuild_boot()
                menu = -1 if boot else sync_boot_menu()
            finally:
                PACMAN_LOCK.unlink(missing_ok=True)
            change.result = {"ok": not boot, "boot": boot, "bootMenu": menu,
                             "errors": "The startup files still didn't rebuild." if boot else ""}
            print(json.dumps(change.result))
    except BlockingIOError:
        die("An install or update is running. Wait for it to finish, then try again. Nothing was changed.")


def sync_boot_menu(wait=None) -> int:
    """The boot menu's snapshot entries, written again as the pacman hook does (this holds pacman's lock, like the
    hook, and the startup files were just rebuilt): a startup image from before snapshot support otherwise gets them
    only at the next kernel update (QA 20261107-0828 003). The number listed, or -1; the menu keeps what it had.
    wait: give up after that many seconds when bootsnap's lock is held (None waits as long as it takes)."""
    try:
        import bootsnap
        manager = bootsnap.BootSnapshots()
        manager.state.mkdir(parents=True, exist_ok=True)
        with (manager.state / "boot-snapshots.lock").open("w") as lock:
            deadline = time.monotonic() + (wait or 0)
            while True:
                try:
                    fcntl.flock(lock, fcntl.LOCK_EX | (fcntl.LOCK_NB if wait is not None else 0))
                    break
                except BlockingIOError:
                    if time.monotonic() >= deadline:
                        return -1
                    time.sleep(0.5)
            return len(manager.sync(True).get("entries") or [])
    except (OSError, RuntimeError, ValueError):
        return -1


PACMAN_LOCK = Path("/var/lib/pacman/db.lck")
# Started from a snapshot in the boot menu, the system files are a copy in memory, but the boot partition, home and the
# package cache are the normal system's: an install there would be lost at restart, or leave a kernel in /boot that
# the normal system's files don't match. Going back in place has no system files of its own to change.
SNAPSHOT_REFUSED = ("update-run", "software-run", "switch-to-package", "tailscale-on", "recovery-create", "recovery-undo",
                    "recovery-go-back-undo", "recovery-update-undo", "recovery-update-undo-at", "recovery-delete", "recovery-boot", "pacman-unlock",
                    "user-add", "user-password", "user-remove", "user-administrator", "user-reset-keyring",
                    "own-password", "recovery-code-new", "recovery-code-use", "autologin")
SNAPSHOT_START = ("This computer started from a snapshot, so nothing was changed. Restart normally first, or choose "
                  "Go back to this snapshot.")


def started_from_snapshot() -> bool:
    import bootsnap
    return bootsnap.booted() is not None


def rebuild_boot() -> str:
    """Kernels live on the boot partition, outside snapshots: rebuild them from the restored files. "" when it worked."""
    try:
        if shutil.which("limine-mkinitcpio"):
            b = subprocess.run(["limine-mkinitcpio"], capture_output=True, text=True)
        else:
            for pb in Path("/usr/lib/modules").glob("*/pkgbase"):
                vml = pb.parent / "vmlinuz"
                if vml.exists():
                    # whole or not at all: a kernel cut short by a crash or a full /boot would not start
                    dst = Path(f"/boot/vmlinuz-{pb.read_text().strip()}")
                    tmp = dst.with_name(dst.name + f".{os.getpid()}.tmp")
                    try:
                        shutil.copyfile(vml, tmp)
                        fd = os.open(tmp, os.O_RDONLY)
                        try:
                            os.fsync(fd)
                        finally:
                            os.close(fd)
                        tmp.replace(dst)
                    finally:
                        tmp.unlink(missing_ok=True)
            b = subprocess.run(["mkinitcpio", "-P"], capture_output=True, text=True)
        if b.returncode == 0:
            # the boot menu as well: a Starchaser kernel added after the snapshot keeps its files in /boot but not its
            # modules, and an entry left pointing at it starts into emergency mode (QA 2026-11-03)
            import kernels
            manager = kernels.Kernels()
            manager.state.mkdir(parents=True, exist_ok=True)
            with (manager.state / "lock").open("w") as lock:
                fcntl.flock(lock, fcntl.LOCK_EX)
                manager.refresh()
                try:
                    manager.remove_unused_images()  # tidying only: the startup files are already right
                except OSError:
                    pass
    except (OSError, RuntimeError) as e:
        return str(e)
    return "" if b.returncode == 0 else (b.stderr or b.stdout).strip()[-600:] or f"exit code {b.returncode}"


PACMAN_LOCAL = Path("/var/lib/pacman/local")
PACMAN_LOG = Path("/var/log/pacman.log")


def local_packages() -> dict:
    """{name: version} from pacman's local database folders ("name-pkgver-pkgrel"), read without running pacman."""
    try:
        return {p[0]: f"{p[1]}-{p[2]}" for p in (d.name.rsplit("-", 2) for d in PACMAN_LOCAL.iterdir() if d.is_dir())
                if len(p) == 3}
    except OSError:
        return {}


def log_go_back(n: int, when: str, before: dict, after: dict) -> None:
    """One line in pacman's log for the packages a go-back changed. The log is outside snapshots, so it otherwise
    still ended with the install that was undone and disagreed with pacman -Q (QA 20261107-1243 002)."""
    changes = [f"removed {name} ({before[name]})" if name not in after else
               f"installed {name} ({after[name]})" if name not in before else
               f"{name} went back ({before[name]} -> {after[name]})"
               for name in sorted(before.keys() | after.keys()) if before.get(name) != after.get(name)]
    # Missing package records can make both inventories empty even when files were removed. Keep
    # the Recovery boundary so boot repair never mistakes the undone install for current state.
    try:
        with PACMAN_LOG.open("a") as log:
            log.write(time.strftime("[%Y-%m-%dT%H:%M:%S%z]") + f" [STARCHASER] went back to snapshot {n} ({when}): "
                      + (", ".join(changes) or "no package changed") + "\n")
    except OSError:
        pass


def go_back_names(target: dict) -> tuple:
    """(the name you typed for the snapshot gone back to, or ""; the safety snapshot's name). A snapshot you named
    (Take a snapshot now) is named in both, with its date: "Before going back to “Before recovery test” (Oct 9,
    8:05 PM)". Only a typed name: an automatic snapshot's description is pacman's command line. The prefix stays
    "Before going back", which is how older safety snapshots are still recognized (tag)."""
    desc = (target.get("description") or "").strip()
    name = desc if tag(target) == "hand" and desc not in ("Made by you", "Snapshot you took") else ""
    when = fmt(target)                              # "an earlier snapshot" when snapper gave no readable date
    if not name:
        return name, f"Before going back to {when}"
    dated = f" ({when})" if when != "an earlier snapshot" else ""
    return name, f"Before going back to “{name}”{dated}"


def recovery_destination(target: dict, number: int) -> str:
    """Keep the original destination through undo/redo, even if its snapshot is later deleted. Only a name the
    person typed: an unnamed snapshot gives "", so the redo row says "Go back again" with its date, never an internal
    snapshot number."""
    data = target.get("userdata") or {}
    if tag(target) == "safety":
        try:
            name = bytes.fromhex(data.get("recovery_name", "")).decode("utf-8")
            if name:
                return name
        except (ValueError, UnicodeDecodeError):
            pass
        # Older undo snapshots already carry the user's destination name in their description.
        match = re.match(r"Before going back to [‘“](.*)[’”](?: \(.*\))?$", target.get("description") or "")
        if match:
            return match[1]
        return ""
    name, _ = go_back_names(target)
    return name


def undo_locked(n: int, known: dict, files: int, kernel: bool, boot_inputs: bool = False) -> None:
    """Compatibility door; the recovery engine owns this transaction."""
    return _recovery_engine().undo_locked(n, known, files, kernel, boot_inputs)


def change_update_channel(choice):
    import pkgrepo
    import updater
    with updater.SystemChange("channel") as change:
        take_pacman_lock()
        try:
            change.result = pkgrepo.set_channel(choice)
            print(json.dumps(change.result))
            import updater
            updater.clear_channel_went_back()        # chosen now, so no longer on because of going back
        except ValueError as error:
            die(str(error))
        except OSError:
            die("The update channel could not be saved. Try again.")
        finally:
            PACMAN_LOCK.unlink(missing_ok=True)

def update_channel() -> str:
    """This computer's update channel, "release" or "testing", or "" when pacman.conf can't be read."""
    import pkgrepo
    try:
        return pkgrepo.channel_status()["channel"]
    except OSError:
        return ""


def recovery_delete(n: int) -> None:
    """Delete a snapshot that is kept until you delete it: one taken by hand, or an older safety snapshot. Never the
    baseline, never automatic ones (snapper's cleanup handles those), never the newest safety snapshot (the only way
    to undo the last go-back). starchaser recovery's "deletable" is the same rule."""
    known = snaps()
    keep_hand_made(known)
    known = snaps()
    s = known.get(n)
    if not s or n == 0:
        die("That snapshot isn't there anymore.")
    if s.get("type") != "single" or s.get("cleanup") or tag(s) not in ("hand", "safety"):
        die("This snapshot can't be deleted here.")
    safeties = [m for m, x in known.items() if tag(x) == "safety"]
    if tag(s) == "safety" and n == max(safeties):
        die("This snapshot is how you undo your last go-back, so it can't be deleted until you go back again.")
    r = subprocess.run(["snapper", "-c", "root", "delete", str(n)], capture_output=True, text=True)
    why = r.stderr.strip() or ("" if r.returncode == 0 else f"snapper stopped with exit code {r.returncode}")
    print(json.dumps({"ok": r.returncode == 0, "errors": why}))


def pwd_name(uid: int) -> str:
    import pwd
    try:
        return pwd.getpwuid(uid).pw_name if uid >= 1000 else ""
    except KeyError:
        return ""


BACKUP_FOLDER = "Starchaser Backups"       # bin/starchaser-backup FOLDER


def backup_folder(mount: str) -> None:
    """The backup folder on a drive the person at the computer mounted (udisks: /run/media/<them>/<drive>), owned by
    them. Each step opens the folder it made without following links, so a drive prepared with a link in that place
    can't point the change anywhere else on this computer."""
    uid = sitting_user()
    user = pwd_name(uid)
    if not user:
        die("Only a person signed in to this computer can do that.")
    base = f"/run/media/{user}/"
    if os.path.realpath(mount) != mount.rstrip("/") or not mount.startswith(base) or "/" in mount[len(base):].rstrip("/") \
            or not os.path.ismount(mount):
        die("That isn't a drive plugged into this computer. Plug it in again and try again.")
    flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
    fds = [os.open(mount, flags)]
    try:
        for name, mode in ((BACKUP_FOLDER, 0o755), (user, 0o700)):
            try:
                os.mkdir(name, mode, dir_fd=fds[-1])
            except FileExistsError:
                pass
            fds.append(os.open(name, flags, dir_fd=fds[-1]))
        st = os.fstat(fds[-1])
        if st.st_uid not in (0, uid):
            die("The backup folder on this drive belongs to another account. Use another drive.")
        os.fchown(fds[-1], uid, pwd.getpwuid(uid).pw_gid)
        os.fchmod(fds[-1], 0o700)
    except OSError as e:
        die(f"The backup folder couldn't be made on the drive ({e.strerror}).")
    finally:
        for fd in fds:
            os.close(fd)
    print(json.dumps({"ok": True, "errors": ""}))


def _run_tail(r) -> str:
    """The end of a failed command's own words, for "details"."""
    return ((r.stderr or "") + "\n" + (r.stdout or "")).strip()[-300:]


def tailscale_start(user: str, steps: list) -> dict:
    """Start Tailscale's service (installed already) and let the desktop user run it without sudo. Each step's result
    is checked: Settings must not say Tailscale is on when it didn't start."""
    r = subprocess.run(["systemctl", "enable", "--now", "tailscaled.service"], capture_output=True, text=True)
    if r.returncode != 0:
        return {"ok": False, "errors": "Couldn't start Tailscale. Try again, or restart the computer first.",
                "details": _run_tail(r), "steps": steps}
    for _ in range(20):                               # the daemon takes a moment to answer
        if subprocess.run(["tailscale", "status"], capture_output=True).returncode in (0, 1):
            break
        time.sleep(0.5)
    if user:
        r = subprocess.run(["tailscale", "set", f"--operator={user}"], capture_output=True, text=True)
        if r.returncode != 0:
            refresh_firewall_zones()
            return {"ok": False, "errors": "Tailscale started, but didn't answer when Settings set it up for you. "
                    "Turn it off and on again.", "details": _run_tail(r), "steps": steps}
    refresh_firewall_zones()                       # tailscale0 may be up already (signed in before)
    return {"ok": True, "errors": "", "steps": steps}


def tailscale_stop() -> dict:
    """Stop Tailscale's service and keep it from starting at boot; it stays installed and signed in. Whether it is
    off is asked of systemd afterward, not assumed."""
    # best-effort: when the service is already stopped, "tailscale down" fails, and that is not a failure here
    subprocess.run(["tailscale", "down"], capture_output=True)
    r = subprocess.run(["systemctl", "disable", "--now", "tailscaled.service"], capture_output=True, text=True)
    # systemd's own word for the state, not its exit code: any failure to ask (no answer from systemd) exits nonzero
    # too, and that must not read as "stopped" ("inactive" also covers a service that isn't installed)
    state = subprocess.run(["systemctl", "is-active", "tailscaled.service"], capture_output=True, text=True)
    refresh_firewall_zones()                       # its interface is gone: out of the Tailscale zone now
    if state.stdout.strip() not in ("inactive", "failed"):
        return {"ok": False, "errors": "Couldn't stop Tailscale. Try again, or restart the computer.",
                "details": _run_tail(r) or _run_tail(state)}
    if r.returncode != 0:
        boot = subprocess.run(["systemctl", "is-enabled", "tailscaled.service"], capture_output=True, text=True)
        if boot.stdout.strip() not in ("disabled", "masked", "masked-runtime", "not-found"):
            return {"ok": False, "errors": "Tailscale stopped, but it will start again when the computer restarts. "
                    "Try turning it off again.", "details": _run_tail(r)}
    return {"ok": True, "errors": ""}


def tailscale_install_error(out: str) -> str:
    """pacman's failure, in words a new user can act on (its own text goes in "details")."""
    low = out.lower()
    if "could not resolve" in low or "failed to connect" in low or "connection timed out" in low \
            or "operation too slow" in low:
        return "Couldn't install Tailscale. Check the internet connection and try again."
    if "failed retrieving" in low or "404" in low or "target not found" in low:
        # the package lists are older than the server's files: only a full update brings them up to date safely
        return "Couldn't install Tailscale: this computer's list of apps is out of date. " \
               "Install the waiting updates in Settings > Updates, then try again."
    if "unable to lock database" in low:
        return "Couldn't install Tailscale while another install or update is running. Try again when it's done."
    return "Couldn't install Tailscale. Try again, or install the waiting updates in Settings > Updates first."


def opt(argv, name, default=""):
    """Value of --flag in argv (the next word), or '' when not given; handles --flag=value too."""
    for i, a in enumerate(argv):
        if a == name:
            return argv[i + 1] if i + 1 < len(argv) else default
        if a.startswith(name + "="):
            return a[len(name) + 1:]
    return default


def timeout_opt(argv) -> int:
    """--timeout N, a whole number of seconds (0 when not given)."""
    for i, a in enumerate(argv):
        if a == "--timeout":
            if i + 1 >= len(argv):
                die("--timeout needs a number of seconds")
            v = argv[i + 1]
            break
        if a.startswith("--timeout="):
            v = a[len("--timeout="):]
            break
    else:
        return 0
    if not v.isdigit():
        die("--timeout must be a whole number of seconds")
    return int(v)


# ---------------------------------------------------------------------------------------------- USB devices
HOSTS = Path("/etc/hosts")
USBG = Path("/etc/usbguard")
USB_RELAXED = USBG / "rules.d/20-starchaser-relaxed.conf"
RELAXED_RULES = """# Starchaser Linux, USB devices at the Relaxed level (Settings > Privacy; starchaser-admin usb-level):
# Hubs and mice work immediately. A second keyboard waits when another USB keyboard already works.
# A device that is HID plus anything else (storage, network, ...) does not match: it waits for you like any new one.
allow with-interface all-of { 03:01:02 }
block with-interface one-of { 03:00:* 03:01:01 } if allowed-matches(with-interface one-of { 03:00:* 03:01:01 })
allow with-interface all-of { 03:*:* }
allow with-interface all-of { 09:*:* }
# Storage drives and phones (USB drives, cameras and phones sharing files, Android debugging) work while the computer is
# unlocked, with no password (decided 2026-11-16). While it is locked every new device waits (usb_lock.py). A device
# that is one of these PLUS something else (a keyboard hidden in a drive, a network adapter) does not match.
allow with-interface all-of { 08:*:* }
allow with-interface all-of { 06:01:01 }
allow with-interface all-of { ff:ff:00 }
allow with-interface all-of { ff:42:01 }
"""
# the Relaxed level's own class rules, as USBGuard lists them
RELAXED_OWN = ("allow with-interface all-of { 03:01:02 }", "allow with-interface all-of { 03:*:* }", "allow with-interface all-of { 09:*:* }",
               "allow with-interface all-of { 08:*:* }", "allow with-interface all-of { 06:01:01 }",
               "allow with-interface all-of { ff:ff:00 }", "allow with-interface all-of { ff:42:01 }")
# written when USB protection is turned off in Settings, so re-running desktop setup (usb-setup) leaves it off;
# choosing Relaxed or Strict again removes it
USB_OFF = USBG / "starchaser-off"
USB_OFF_PUBLIC = Path("/var/lib/starchaser/usb-off")
USB_ACL = ["-d", "list,listen", "-p", "list", "-e", "listen", "-P", "list"]
USB_SYSFS = Path("/sys/bus/usb/devices")
USB_RUN = Path("/run/user")


USB_READ_ACL = "Devices=list,listen\nPolicy=list\nExceptions=listen\nParameters=list\n"


def usb_access() -> tuple:
    """Replace old write-capable ACLs, including per-account files. add-user may refuse an existing file."""
    changed, errors = False, []
    folder = USBG / "IPCAccessControl.d"
    folder.mkdir(mode=0o700, parents=True, exist_ok=True)
    names = {":wheel", *usb_readers(), *(p.name for p in folder.iterdir() if p.is_file())} - {"root", "0"}
    for name in names:
        file = folder / name
        try:
            if not file.exists() or file.read_text() != USB_READ_ACL:
                fw.write_atomic(file, USB_READ_ACL, 0o600)
                changed = True
            if file.read_text() != USB_READ_ACL:
                raise OSError()
        except OSError:
            errors.append("Couldn't give your account read-only USB access. USB changes still need an administrator password.")
    config = USBG / "usbguard-daemon.conf"
    old = config.read_text() if config.exists() else ""
    text = old
    for key, value in (("IPCAllowedUsers", "root"), ("IPCAllowedGroups", ""), ("IPCAccessControlFiles", str(folder) + "/"), ("InsertedDevicePolicy", "block")):
        line = key + "=" + value
        text = re.sub(r"^" + key + r"=.*$", lambda _: line, text, flags=re.M) if re.search(r"^" + key + "=", text, re.M) else text.rstrip() + "\n" + line + "\n"
    if text != old:
        fw.write_atomic(config, text, 0o600)
        changed = True
    return changed, errors


def usb_readers() -> list:
    """Private account groups do not share a desktop-users group. Give each regular account read-only access."""
    return [u.pw_name for u in pwd.getpwall() if 1000 <= u.pw_uid < 60000 and getattr(u, "pw_shell", "/bin/bash") not in ("/usr/bin/nologin", "/bin/false", "/usr/bin/false")]


def usb_device(argv: list) -> dict:
    """Accept only an existing device number or a device-specific rule number, never caller-supplied rule text."""
    args = argv[1:]
    if len(args) == 2 and args[0] == "allow-group":
        numbers = args[1].split(",")
        if not 2 <= len(numbers) <= 32 or any(not number.isascii() or not number.isdigit() for number in numbers) or len(set(numbers)) != len(numbers):
            die("Choose the currently listed parts of one USB dock.")
        listed = run("usbguard", "list-devices")
        rules = [line.partition(": ")[2] for line in listed.stdout.splitlines() if line.partition(": ")[0] in numbers]
        ports = [re.search(r'via-port "([0-9]+-[0-9]+(?:\.[0-9]+)*)"', rule) for rule in rules]
        if listed.returncode or len(rules) != len(numbers) or not all(ports) or len({port.group(1).split(".")[0] for port in ports}) != 1:
            die("The dock changed or was unplugged. Check its parts again.")
        for number in numbers:
            usb_device(["usb-device", "allow-device", number])
        return {"ok": True, "message": "The listed dock parts are allowed until unplugged."}
    if len(args) not in (2, 3) or args[0] not in ("allow-device", "block-device", "remove-rule"):
        die("Choose one USB device to change.")
    verb, number = args[0], args[-1]
    permanent = len(args) == 3 and args[1] == "-p" and verb != "remove-rule"
    if not number.isascii() or not number.isdigit() or (len(args) == 3 and not permanent):
        die("Choose one USB device number.")
    USBG.mkdir(parents=True, exist_ok=True)
    with (USBG / ".starchaser-device.lock").open("w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        result = run("usbguard", "list-rules" if verb == "remove-rule" else "list-devices")
        if result.returncode:
            die("USB protection could not be read. Try again.")
        rule = next((line.partition(": ")[2] for line in result.stdout.splitlines() if line.startswith(number + ": ")), "")
        digest = re.search(r'(?<!-)\bhash "([^"\\]+)"', rule)
        identity = re.search(r'\bid ([0-9a-f]{4}:[0-9a-f]{4})\b', rule)
        if not digest or not identity:
            die("That device is no longer available. Check USB protection again.")
        if verb == "block-device" and not native_keyboard():
            def keyboard(candidate):
                return bool(re.search(r'with-interface.*03:(?:00:[0-9a-f*]+|01:01)', candidate))
            others = [line.partition(": ")[2] for line in result.stdout.splitlines()
                      if line.partition(": ")[0] != number and line.partition(": ")[2].startswith("allow ")]
            if keyboard(rule) and not any(keyboard(other) for other in others):
                die("Connect another keyboard before blocking this one. It is the last working keyboard.")
        if verb == "remove-rule":
            changed = run("usbguard", "remove-rule", number)
        elif permanent:
            listed = run("usbguard", "list-rules")
            if listed.returncode:
                die("USB rules could not be read. Nothing was changed.")
            # Remove only this device's own choices. A class rule can match thousands of keyboards.
            for line in listed.stdout.splitlines():
                old_number, _, old = line.partition(": ")
                old_hash = re.search(r'(?<!-)\bhash "([^"\\]+)"', old)
                if old_number.isdigit() and old_hash and old_hash.group(1) == digest.group(1):
                    removed = run("usbguard", "remove-rule", old_number)
                    if removed.returncode:
                        die("The earlier USB choice could not be removed. Check USB protection again.")
            target = "allow" if verb == "allow-device" else "block"
            own = f'{target} id {identity.group(1)} hash "{digest.group(1)}"'
            for pattern in (r'\bname "(?:[^"\\]|\\.)*"',
                            r'with-interface (?:one-of |all-of )?\{ [^}]* \}|with-interface [0-9a-f:]+'):
                attribute = re.search(pattern, rule)
                if attribute:
                    own += " " + attribute.group(0)
            if target == "allow":
                port = re.search(r'\bvia-port "([0-9]+-[0-9]+(?:\.[0-9]+)*)"', rule)
                if not port:
                    die("The USB socket could not be checked. Use Allow for now instead.")
                own += f' via-port "{port.group(1)}"'
            # Device blocks precede Relaxed's class rules; a later generic allow cannot win over this choice.
            parent = next((line.partition(": ")[0] for line in listed.stdout.splitlines()
                           if re.search(r'\bid 1d6b:', line) and re.search(r'(?<!-)\bhash "', line)), "")
            defaults = []
            if not parent:
                # Root id 0 is not an insertion point across USBGuard's separate rule files. With no controller
                # rule to follow, move only our two class rules after the device choice; existing input stays on.
                for line in listed.stdout.splitlines():
                    number_, _, rule_ = line.partition(": ")
                    if rule_.startswith("block with-interface one-of { 03:00:") or rule_ in RELAXED_OWN:
                        removed = run("usbguard", "remove-rule", number_)
                        if removed.returncode:
                            die("The USB choice could not be saved. Check USB protection again.")
                        defaults.append(rule_)
            try:
                changed = run("usbguard", "append-rule", *(["--after", parent] if parent else []), own)
            finally:
                for default in defaults:
                    if run("usbguard", "append-rule", default).returncode:
                        die("The device choice was saved, but Relaxed needs to be selected again in Settings > Privacy.")
            if not changed.returncode:
                changed = run("usbguard", verb, number)
        else:
            changed = run("usbguard", verb, number)
        if changed.returncode:
            die("The USB change could not be made. Check USB protection again.")
    return {"ok": True}


def usb_once_devices() -> dict:
    """Explicit Allow for now choices, still allowed on the same physical connection. Only accounts already
    permitted to allow devices through USBGuard may supply a record; a record alone never authorizes a device."""
    result = run("usbguard", "list-devices")
    if result.returncode:
        return {}
    records = []
    try:
        wheel = grp.getgrnam("wheel").gr_gid
        for user in pwd.getpwall():
            if user.pw_uid == 0 or 1000 <= user.pw_uid < 60000 or wheel in os.getgrouplist(user.pw_name, user.pw_gid):
                records.append(USB_RUN / str(user.pw_uid) / "starchaser-usb-once")
    except KeyError:
        return {}
    devices = {}
    for line in result.stdout.splitlines():
        match = re.match(r'^(\d+): (allow|block|reject) .*? hash "([^"\\]+)".*? via-port "([0-9]+-[0-9]+(?:\.[0-9]+)*)"', line)
        if not match:
            continue
        number, target, digest, port = match.groups()
        try:
            device = USB_SYSFS / port
            token = [digest, device.stat().st_ino, device.joinpath("devnum").read_text().strip()]
            for folder in records:
                try:
                    with (folder / port).open() as f:
                        saved = json.loads(f.read(1024))
                    if saved == token:
                        devices[port] = (number, target, token)
                        break
                except (OSError, ValueError):
                    continue
        except OSError:
            continue
    return devices


def usb_keep_rules(rules: Path) -> None:
    """Keep permanent device choices before replacing the Relaxed rules file. USBGuard appends a new
    Always allow rule to its last ruleset, which can be this file rather than rules.conf."""
    if not USB_RELAXED.exists():
        return
    defaults = {" ".join(line.split()) for line in RELAXED_RULES.splitlines() if line.startswith(("allow ", "block "))}
    # The built-in-keyboard variant is generated policy too, not a permanent personal block.
    defaults.update(line.split(" if allowed-matches(", 1)[0] for line in tuple(defaults) if line.startswith("block "))
    kept = [line for line in USB_RELAXED.read_text().splitlines()
            if line.strip() and not line.lstrip().startswith("#") and " ".join(line.split()) not in defaults]
    if kept:
        old = rules.read_text()
        # A previous write may have succeeded before setup stopped: don't duplicate those choices on retry.
        known = set(old.splitlines())
        added = [line for line in kept if line not in known]
        if added:
            fw.write_atomic(rules, old.rstrip() + "\n" + "\n".join(added) + "\n", 0o600)


def usb_keep_in_use(rules: Path) -> None:
    """Before Strict replaces Relaxed: a keyboard, mouse or hub working now only because Relaxed lets it in becomes
    Always allow (a rule for it in the same USB port), as Strict promises that only new ones wait. Removing the
    Relaxed rules switched off the keyboard that had just typed the password (QA qa-8 11-07). One you allowed for now
    is kept too: Relaxed let it in anyway, and the list showed it as Relaxed's, so it was blocked on its next plug-in
    after Strict had said it would be remembered (QA 20261107-1504 002). One already remembered or blocked is left
    as it is, and one you chose Always block for is never kept, even while it works for now (Derek 2026-11-07 #29)."""
    listed = run("usbguard", "list-devices")
    if listed.returncode:
        return
    old = rules.read_text()
    running = run("usbguard", "list-rules")
    blocked = set(re.findall(r'^(?:\d+: )?block .*?(?<!-)\bhash "([^"\\]+)"', old + "\n" + (running.stdout or ""), re.M))
    added = []
    for line in listed.stdout.splitlines():
        match = re.match(r'^\d+: (allow .*? hash "([^"\\]+)".*? via-port "([0-9]+-[0-9]+(?:\.[0-9]+)*)".*)$', line)
        if not match or re.search(r"\bid 1d6b:", line):
            continue                     # not allowed now, or one of the computer's own USB controllers
        rule, digest, _port = match.groups()
        found = re.search(r"with-interface (?:\{ ([^}]*) \}|([0-9a-f:]+))", rule)
        classes = {i.split(":")[0] for i in (found.group(1) or found.group(2)).split()} if found else set()
        if classes not in ({"03"}, {"09"}) or f'hash "{digest}"' in old or digest in blocked:
            continue
        added.append(rule)
    if added:
        fw.write_atomic(rules, old.rstrip() + "\n" + "\n".join(added) + "\n", 0o600)


def native_keyboard(base=Path("/sys/class/input")) -> bool:
    for device in base.glob("input*"):
        try:
            physical = str(device.resolve())
            keys = int("".join((device / "capabilities/key").read_text().split()), 16)
            if "/usb" not in physical and "/virtual/" not in physical and keys & (1 << 30) and keys & (1 << 44):
                return True
        except (OSError, ValueError):
            continue
    return False


def relaxed_policy() -> str:
    rules = RELAXED_RULES
    # A built-in non-USB keyboard cannot appear in USBGuard's allowed-matches query.
    if native_keyboard():
        rules = rules.replace(" if allowed-matches(with-interface one-of { 03:00:* 03:01:01 })", "")
    return rules


def usb_setup() -> dict:
    if not shutil.which("usbguard"):
        die("usbguard isn't installed (pacman -S usbguard)")
    if USB_OFF.exists():                 # turned off in Settings: setup doesn't turn it back on
        fw.write_atomic(USB_OFF_PUBLIC, "USB checks are off.\n", 0o644)
        if run("systemctl", "is-active", "--quiet", "usbguard.service").returncode != 0:
            usb_release()                # (and a controller left on "deny new devices" is put right)
        return {"ok": True, "level": "off", "errors": ""}
    rules = USBG / "rules.conf"
    # restart the daemon at the end only when it wasn't running or this call changed its files: a restart drops the
    # devices allowed just this once ("Allow once"), so a setup run that changes nothing must leave it alone
    was_active = run("systemctl", "is-active", "--quiet", "usbguard.service").returncode == 0
    changed = False
    # remember everything plugged in now, before the daemon blocks anything (only the first time: never drop a device)
    if not rules.exists() or not rules.read_text().strip():
        pol = run("usbguard", "generate-policy")
        if pol.returncode != 0 or "allow" not in pol.stdout:
            die("couldn't list the USB devices: " + pol.stderr.strip())
        fw.write_atomic(rules, "# Starchaser Linux: the USB devices you allowed (the ones present at setup, then each you chose to keep).\n"
                         + pol.stdout, 0o600)
        changed = True
    USB_RELAXED.parent.mkdir(parents=True, exist_ok=True)
    if not (USBG / "starchaser-strict").exists():
        try:
            same = USB_RELAXED.read_text() == relaxed_policy()
        except OSError:
            same = False
        if not same:
            usb_keep_rules(rules)
            usb_keep_in_use(rules)
            fw.write_atomic(USB_RELAXED, relaxed_policy(), 0o600)
            changed = True
    elif USB_RELAXED.exists():           # Strict picked over Relaxed: the running daemon still holds the relaxed rules,
        usb_keep_rules(rules)
        usb_keep_in_use(rules)
        USB_RELAXED.unlink()             # so this counts as a change and the restart below loads Strict right away
        changed = True
    access_changed, errors = usb_access()
    changed |= access_changed
    lock_service = run("systemctl", "enable", "--now", "starchaser-usb-lock.service")
    if lock_service.returncode:
        errors.append("Couldn't protect new USB devices while the screen is locked.")
    r = run("systemctl", "enable", "--now", "usbguard.service")
    if r.returncode:
        errors.append(r.stderr.strip() or f"systemctl exit {r.returncode}")
    elif was_active and changed:
        # A stopped daemon just loaded these files during enable --now. Restarting it immediately can
        # interrupt USB enumeration and leave the stop job waiting for its timeout.
        once = usb_once_devices()
        rs = run("systemctl", "restart", "usbguard.service")    # pick up the rules and the IPC access
        if rs.returncode:
            errors.append("USB protection kept its old rules: " + (rs.stderr.strip() or f"systemctl exit {rs.returncode}"))
        elif once:
            for port, (number, target, token) in usb_once_devices().items():
                before = once.get(port)
                if before and before[1] == "allow" and before[2] == token and target == "block":
                    allowed = run("usbguard", "allow-device", number)
                    if allowed.returncode:
                        errors.append("A device allowed for now couldn't be restored. Allow it again in USB protection.")
    if was_active:
        # A running Python monitor keeps its old code after an upgrade. Hold new insertions while replacing it.
        if run("usbguard", "set-parameter", "InsertedDevicePolicy", "block").returncode:
            errors.append("New USB devices could not be held while refreshing lock protection.")
        if run("systemctl", "restart", "starchaser-usb-lock.service").returncode:
            errors.append("USB lock protection could not be refreshed. Check again in Privacy.")
    return {"ok": not errors, "level": usb_level_now(), "errors": "; ".join(errors)}


def usb_level_now() -> str:
    if run("systemctl", "is-active", "--quiet", "usbguard.service").returncode != 0:
        return "off"
    return "relaxed" if USB_RELAXED.exists() else "strict"


def usb_release() -> list:
    """Let new USB devices in again (see usb_level("off")); the controllers it could not change."""
    bad = []
    for d in Path("/sys/bus/usb/devices").glob("usb*/authorized_default"):
        try:
            d.write_text("1")
            if d.read_text().strip() != "1":
                bad.append(d.parent.name)
        except OSError:
            bad.append(d.parent.name)
    for _ in range(2):
        for a in Path("/sys/bus/usb/devices").glob("*/authorized"):
            try:
                if a.read_text().strip() == "0":
                    a.write_text("1")
            except OSError:
                pass
        time.sleep(0.3)
    return bad


def usb_level(level: str) -> dict:
    if level == "off":
        USBG.mkdir(parents=True, exist_ok=True)
        USB_OFF.write_text("Settings > Privacy: USB devices = Off\n")
        fw.write_atomic(USB_OFF_PUBLIC, "USB checks are off.\n", 0o644)
        stop = run("systemctl", "disable", "--now", "usbguard.service")
        # the daemon sets each USB controller's authorized_default to 0 (deny new devices) while it runs; stopping it
        # leaves that at 0, so a keyboard plugged in afterward stayed blocked. Put the controllers back to "allow new
        # devices", then let in whatever is being held back right now (and the devices behind them, which appear once
        # their hub is let in: scan twice).
        bad = usb_release()
        if run("systemctl", "is-active", "--quiet", "usbguard.service").returncode == 0:
            return {"ok": False, "level": usb_level_now(),
                    "errors": stop.stderr.strip() or "Couldn't turn USB protection off. Try again."}
        if bad:
            return {"ok": False, "level": "off",
                    "errors": "Couldn't let new USB devices in on: " + ", ".join(bad)}
        return {"ok": True, "level": "off"}
    USB_OFF.unlink(missing_ok=True)
    USB_OFF_PUBLIC.unlink(missing_ok=True)
    flag = USBG / "starchaser-strict"
    if level == "strict":
        flag.write_text("Settings > Privacy: USB devices = Strict\n")    # usb_setup removes the relaxed rules
    else:
        flag.unlink(missing_ok=True)
    return usb_setup()


def add_allow(pol: dict, ip, proto: str, port: int, who: str, what: str, zone: str = "trusted", network: str = "") -> tuple:
    """(policy, device name, service name) with "allow <device> on <port>" added at the top, on networks of that kind
    (zone: where the connection came in; "any" only when chosen), unless such a rule is there already."""
    # a group that is this one device and nothing else: one holding other devices too would let them in as well
    one = {str(ip), f"{ip}/{ip.max_prefixlen}"}
    a = next((x for x in pol.get("addresses", []) if not x.get("ruleLocal") and len(x.get("addrs") or []) == 1 and x["addrs"][0] in one), None)
    if not a:
        a = {"id": "a-" + uuid.uuid4().hex[:8], "name": who, "addrs": [str(ip)]}
        pol.setdefault("addresses", []).append(a)
    svc = next((x for x in pol.get("services", []) if not x.get("ruleLocal") and x.get("ports") == [f"{proto}:{port}"]), None)
    if not svc:
        svc = {"id": "s-" + uuid.uuid4().hex[:8], "name": what, "ports": [f"{proto}:{port}"]}
        pol.setdefault("services", []).append(svc)
    zones = ["any"] if zone == "any" or network else [zone]
    # an existing Allow counts only when no enabled incoming Block or Refuse sits above it (that one could decide
    # first, and then the Allow below would not let the device in)
    seen_block = False
    have = False
    for r in pol.get("rules", []):
        if r.get("dir") == "in" and r.get("enabled", True) and r.get("action") != "allow":
            seen_block = True
        if (not seen_block and r.get("dir") == "in" and r.get("action") == "allow" and r.get("peers") == [a["id"]]
                and r.get("service") == [svc["id"]] and r.get("enabled", True)
                and r.get("network", "") == network and not fw.restricted({k: v for k, v in r.items() if k != "network"})
                and ((r.get("zones") or ["any"]) == ["any"] or (not network and zone in (r.get("zones") or [])))):
            have = True
            break
    if not have:
        pol.setdefault("rules", []).insert(0, {"id": "r-" + uuid.uuid4().hex[:8], "name": f"Allow {ip} on {proto.upper()} port {port}: your permission “{what or svc['name']}”",
                                               "enabled": True, "dir": "in", "action": "allow", "zones": zones, "peers": [a["id"]],
                                               "user": "any", "app": "any", "service": [svc["id"]], "log": False,
                                               **({"network": network} if network else {})})
    return pol, a["name"], svc["name"]


def allow_always(addr: str, proto: str, port: int, who: str, what: str, zone: str = "", network: str = "") -> None:
    """Add "allow <device> on <port>" to the policy and make it live (no confirm timer: it only opens a door). If a
    change is waiting for Keep, the policy that would come back gets the same rule, so the door stays open either
    way (and the waiting change is still only kept by Keep)."""
    try:
        ip = ipaddress.ip_address(addr)
    except ValueError:
        die("not an address")
    if proto not in ("tcp", "udp") or not 0 < port < 65536:
        die("bad port")
    clean = lambda t, n: re.sub(r"[^\w .()/:+-]", "", t)[:n].strip()
    who, what = clean(who, 60) or str(ip), clean(what, 40) or f"{proto.upper()} {port}"
    # the kind of network the connection came in on (the asker reads it from the log line); "other" (an interface
    # in no zone) or unknown: Trusted, the same as Settings > Firewall > Log's Allow always
    zone = zone if zone in fw.ZONES else "trusted"
    with locked():
        # the question was asked while the firewall was on; a late answer (the password box leaves time for the
        # firewall to be turned off, or to go back to Off) must not save an opening into a firewall that is off
        cur = current_policy()
        if not cur.get("enabled"):
            die("The firewall is off now, so nothing was changed.")
        if network and not fw.NET_UUID.fullmatch(network):
            die("That network is no longer available. Choose it again in Firewall settings.")
        if network and waiting():
            die("Keep or undo the pending change before saving a permission for one network.")
        pol, _, _ = add_allow(cur, ip, proto, port, who, what, zone, network)
        if network and not fw.network_ifaces(pol).get(network):
            die("This network cannot be recognized now. Nothing was changed. Remember it in Simple, then try again.")
        scope = "on this network only" if network else f"on {zone} networks"
        commit(pol, 0, f"Saved your permission “{what}”: allow {ip} on {proto.upper()} port {port} {scope} (asked when it was blocked)",
               fold=lambda prev: add_allow(prev, ip, proto, port, who, what, zone, network)[0])
        # the same device and port allowed for now (from Log) is ended: the saved permission replaces it, so Settings
        # doesn't go on listing it as ending at a time (QA u840)
        once = [o for o in fw.once_list() or [] if o["addr"] == str(ip) and o["proto"] == proto and o["port"] == port]
        for o in once:
            fw.revoke_once(o["addr"], proto, port, o["iface"], actor=account_caller())
        if once:
            refresh_stats()


def queue_bypass_upgrade(pol: dict) -> None:
    """With Block for everything going out, OpenSnitch's queue bypass is turned off (firewall.apply_opensnitch), so a
    crashed daemon holds new connections instead of letting them out. A computer set to Block before that change
    only got it at its next Apply; this writes it after the update (OpenSnitch restarts under the outgoing hold)."""
    if not pol.get("enabled") or (pol.get("defaults") or {}).get("out") != "block" or waiting():
        return
    try:
        if (json.loads(fw.OSN_CONFIG.read_text()).get("FwOptions") or {}).get("QueueBypass", True) is False:
            return
        p = fw.validate(pol)
        zmap = json.loads(fw.ZONEMAP.read_text()).get("zones") or fw.zone_map(p)
    except (OSError, ValueError, fw.PolicyError):
        return
    err = fw.apply_opensnitch(p, zmap)
    if err:
        print(f"starchaser-admin: OpenSnitch's queue bypass wasn't turned off: {err}", file=sys.stderr, flush=True)


def refresh_installed_basic_rules(boot: bool = False) -> tuple:
    """Follow optional installed fleet apps under the firewall lock, preserving the person's removals and edits.
    boot uses apply's queued outgoing restart, since waiting for the network here would hold up boot itself."""
    pol = current_policy()
    if waiting() or not any(fw.is_fleet_rule(r) for r in pol.get("rules", [])):
        return False, ""
    if not shutil.which("tsshd") or any(r.get("id") == "b-tsshd" or r.get("app") == "tsshd"
                                      for r in pol.get("rules", [])):
        return False, ""
    try:
        if "tsshd" in fw.removed_basic_rules(pol):
            return False, ""
        rule = next(r for r in first_rules() if r["id"] == "b-tsshd")
        pol = fw.validate({**pol, "rules": [*pol.get("rules", []), rule]})
        err, _ = fw.apply(pol, **({"boot": True} if boot else {}))
        if err:
            return False, err
        fw.snapshot(pol, "Allowed Fast remote terminal after it was installed")
        return True, ""
    except (OSError, ValueError, TypeError) as e:
        return False, str(e)


def upgrade_rules() -> None:
    """After an update (the package's install hook, qa vm-sync): the firewall unit loads the saved firewall.nft as
    it is, and nothing compiled it again, so a fix in the engine (the ping limit, say) only reached computers
    installed afterward while Settings already described it. Compile again from the unchanged policy when the
    saved file is older than this engine, and load it. Not at early boot: an app rule's ports learned from programs
    listening (firewall.learned_ports) need the session's programs running."""
    changed, err = refresh_installed_basic_rules()
    if changed or err:
        if changed:
            refresh_stats()
        print(json.dumps({"ok": not err, "errors": err, "changed": changed}))
        return
    pol = current_policy()
    queue_bypass_upgrade(pol)
    saved = fw.saved_compiler_version()
    # (also when the saved fingerprint is from an older engine: loading again makes a new one, fw.SHAPE_TAG)
    if not pol.get("enabled") or saved is None or (saved >= fw.COMPILER_VERSION and not fw.sum_outdated()):
        print(json.dumps({"ok": True, "errors": "", "changed": False}))
        return
    if waiting():
        print(json.dumps({"ok": True, "errors": "", "changed": False, "later": BUSY}))   # Keep / Go back now first
        return
    try:
        pol = fw.validate(pol)
    except fw.PolicyError as e:
        die(str(e))
    err, _ = fw.apply(pol)
    if not err:
        fw.snapshot(pol, "Brought the firewall rules up to date after an update")
        refresh_stats()
    print(json.dumps({"ok": not err, "errors": err, "changed": not err}))


ZONE_NAMES = {"trusted": "Networks you trust", "public": "Public", "vpn": "VPN", "tailscale": "Tailscale"}


def nm_profiles() -> dict:
    """{uuid: the file NetworkManager keeps it in ("" when it says none)} for every profile it knows; {} when it
    can't be asked."""
    try:
        out = run("nmcli", "-t", "-f", "UUID,FILENAME", "connection", "show").stdout
    except (OSError, subprocess.SubprocessError):
        return {}
    prof = {}
    for line in out.splitlines():
        f = [x.replace("\0", ":") for x in line.replace("\\:", "\0").split(":", 1)]
        if len(f) == 2 and UUID.fullmatch(f[0]):
            prof[f[0]] = f[1]
    return prof


def locally_administered(mac: str) -> bool:
    """A made-up hardware address (the 0x02 bit of the first byte): one that may change each time the adapter is
    plugged in, as a server's management port over USB does (Derek 2026-10-09: six in 46 minutes)."""
    try:
        return bool(int(mac.split(":")[0], 16) & 0x02)
    except (ValueError, IndexError):
        return False


# A virtual machine's network card has a made-up address too, but a fixed one (QEMU/KVM and libvirt give each card
# 52:54:00:… for good), so NetworkManager already keeps its connection: never pinned. Pinning one moved the
# connection to /etc and added a driver match that made "nmcli device reapply" fail (QA r32, Starchaser as a guest).
FIXED_VM_PREFIXES = ("52:54:00:",)
VM_NIC_DRIVERS = {"virtio_net", "vmxnet3", "hv_netvsc", "xen-netfront", "xen_netfront"}


def pin_network(uid: str, net: dict, sys_net: Path = Path("/sys/class/net")) -> str:
    """After the network question is answered for a cable connection NetworkManager made up by itself and keeps only
    in memory ("Wired connection 2"), on an adapter whose hardware address is made up anew each time it is plugged
    in: save that connection, tied to the adapter's name and its kind (the driver) instead of its address, so a
    different adapter that gets the same name (another USB adapter in the same port) is a new network, asked about
    like any other, never one that inherits this answer. NetworkManager names such a
    connection after the address, so each plug-in was a new network, asked about again (Derek 2026-10-09: six times
    in 46 minutes for one cable to a server's management port). Saved, it is the same connection, with the answer,
    every time; NetworkManager then makes no new one. An adapter with a fixed address already keeps its connection,
    and a Wi-Fi network is known by its name. Returns what went wrong, or ""."""
    dev = str(net.get("device") or "")
    if "ethernet" not in str(net.get("type") or "") or not re.fullmatch(r"[\w.-]{1,15}", dev):
        return ""
    fn = nm_profiles().get(uid)
    if fn is None or (fn and not fn.startswith("/run/")):
        return ""                                      # unknown, or saved already
    try:
        mac = (sys_net / dev / "address").read_text().strip()
    except OSError:
        return ""
    if not locally_administered(mac) or mac.lower().startswith(FIXED_VM_PREFIXES):
        return ""
    # the driver as NetworkManager itself sees it (what match.driver is compared with)
    try:
        driver = run("nmcli", "-g", "GENERAL.DRIVER", "device", "show", dev).stdout.strip()
    except (OSError, subprocess.SubprocessError, AttributeError):
        driver = ""
    if not re.fullmatch(r"[\w.-]{1,64}", driver):
        return ""                                      # no driver to tie it to: left as it is (asked again next time)
    if driver in VM_NIC_DRIVERS:
        return ""                                      # a virtual machine's own network card keeps its address (r33)
    r = run("nmcli", "connection", "modify", uid, "connection.interface-name", dev, "match.driver", driver,
            "802-3-ethernet.mac-address", "")
    if r.returncode != 0:
        print(f"starchaser-admin: couldn't save {uid} for {dev}: {r.stderr.strip()}", file=sys.stderr, flush=True)
        return r.stderr.strip() or "nmcli failed"
    return ""


def forget_stale(p: dict, uid: str, name: str, known: dict) -> dict:
    """The policy without networks of the same name NetworkManager no longer knows (the made-up connections an
    adapter left behind each time it was plugged in): only when NetworkManager could be asked."""
    if not known or not name:
        return p
    keep = [n for n in p.get("networks") or [] if n.get("uuid") == uid or n.get("name") != name or n.get("uuid") in known]
    return p if len(keep) == len(p.get("networks") or []) else dict(p, networks=keep)


UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")


def mark_network(uid: str, zone: str, only_unmarked: bool = False, over_public: bool = False) -> None:
    """The one-time question about a network (the welcome's "Is <network> your own network?"): Yes marks that network
    Trusted, No marks it Public, so it is asked only once. Only a network this computer is on now, never a VPN or
    Tailscale. Public only marks a network nobody has marked yet (it never undoes a choice made in Settings), which
    is why starchaser-firewall-keep may run it without a password: it can only make the firewall stricter.
    One more case for Public: a network an older setup counted as home by itself, unchanged since (fw.auto_trusted;
    the question is asked once more there, Derek 2026-10-08). No moves it to Public, also without a password, unless
    a rule works differently on Public networks in a way that could let more in (public_only_allows; left to Settings).
    over_public: fleet-ready, asked for by the person, may count a network marked Public as one they trust."""
    if not re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", uid) or zone not in ("trusted", "public"):
        die("bad network")
    net = next((n for n in fw.active_networks() if n.get("uuid") == uid), None)
    if not net or re.search(r"vpn|wireguard|tun", net.get("type", "")) or net.get("device") == "tailscale0":
        die("That network isn't connected now, so nothing was changed.")
    if zone == "trusted":
        reason = fw.network_trust_reason(net)
        if reason:
            die(reason)
    cur = current_policy()
    if not cur.get("enabled"):
        die("The firewall is off now, so nothing was changed.")
    old = next((n for n in cur.get("networks") or [] if n.get("uuid") == uid), None)
    # Yes is for a network nobody has chosen for: one marked Public (in Settings or by the Public pause) is never made
    # Trusted by the one-time question, whoever runs it. Matched as the zones match it (the same router and range, the
    # same Wi-Fi), so a new connection to that network counts too. A restart used to undo a saved Public choice this
    # way (QA r003). fleet-ready is the person's own request to trust the networks it names, Public ones included.
    was_public = "public" in ((old or {}).get("zone"),
                              (fw.match_network(cur, uid, net.get("type", ""), net.get("device", "")) or {}).get("zone"))
    if zone == "trusted" and was_public and not over_public:
        die(f"{net.get('name') or 'That network'} is marked Public, so nothing was changed. "
            "To trust it, change it in Settings > Firewall.")
    # Public without a password is only safe where the network already counts as Public (unmarked networks set to
    # Public): with unmarked networks counting as Trusted (or another kind), a rule that allows something only on
    # Public networks would start letting it in
    unmarked_public = (cur.get("unknownZone") or "public") == "public"
    if only_unmarked and old and old.get("zone") != zone:
        # the question was about an unmarked network; someone chose in Settings while it waited (or while the
        # password box was open): that choice stands
        die(f"You chose {ZONE_NAMES.get(old.get('zone'), old.get('zone'))} for it in Settings, so nothing was changed.")
    # Trusted by an older setup on its own and nobody's choice since: No to the question asked once more makes it Public
    auto = zone == "public" and bool(old) and old.get("zone") == "trusted" and uid in fw.auto_trusted(cur)
    if auto and public_only_allows(cur):
        die("One of your rules works differently on Public networks, so making this network Public could let more in. "
            "Choose for it in Settings > Firewall.")
    if not auto and ((old and zone == "public") or (old and old.get("zone") == zone)
                     or (zone == "public" and not unmarked_public)):
        if old and old.get("zone") == zone:            # the same answer again: the next plug-in is still this network
            pin_network(uid, net)                      # (never a Public answer for a Trusted network: no password)
        print(json.dumps({"ok": True, "errors": "", "changed": False}))      # already decided: leave it
        return
    name = net.get("name", "")[:80]
    known = nm_profiles()

    def mark(p: dict) -> dict:
        # (also folded into the policy a waiting change would go back to: Public never replaces a choice made
        # there, nor marks a network where unmarked ones don't count as Public; the one exception is the network an
        # older setup trusted by itself, while it is still Trusted there)
        was = next((n for n in p.get("networks") or [] if n.get("uuid") == uid), None)
        if zone == "public" and auto:
            if not was or was.get("zone") != "trusted" or public_only_allows(p):
                return p
        elif zone == "public" and ((p.get("unknownZone") or "public") != "public" or was):
            return p
        elif zone == "trusted" and was and was.get("zone") == "public" and not over_public:
            return p                                   # (marked Public meanwhile: that choice stands)
        p = forget_stale(dict(p), uid, name, known)
        p["networks"] = [n for n in p.get("networks") or [] if n.get("uuid") != uid] + \
            [{"uuid": uid, "name": name, "zone": zone}]
        return p
    # saved first, so the answer is kept with a connection that lasts (commit prints the result and returns)
    pin_network(uid, net)
    commit(mark(cur), 0, (f"Counted {name} as a network you trust" + (" instead of Public, to join a fleet" if was_public else "")
                          if zone == "trusted"
                          else f"Made {name} Public" if auto else f"Kept {name} Public")[:150]
           + (", as you answered when asked again (an older setup had trusted it by itself)" if auto
              else "")
           # (nobody answered through a password box: History says where it came from, not that the person did it)
           + ("" if "PKEXEC_UID" in os.environ else " (from the command line)"),
           fold=mark)                         # (commit prints the result)


def public_only_allows(pol: dict) -> bool:
    """Whether moving a network from Trusted to Public could let something through that wasn't before: an enabled
    Allow rule that applies on Public networks but not on Trusted ones starts applying, or an enabled Block/Reject
    rule that applies on Trusted networks but not on Public ones stops applying (a later Allow rule could then let
    that traffic through). Rules that apply the same on both, or only make Public stricter, don't count."""
    for r in pol.get("rules") or []:
        z = r.get("zones") or ["any"]
        if not r.get("enabled", True) or "any" in z or ("public" in z) == ("trusted" in z):
            continue
        if (r.get("action") == "allow") == ("public" in z):
            return True
    return False


PROC = Path("/proc")


def own_scope() -> str:
    """The login session this helper runs in (its cgroup's session-N.scope), or "" outside one."""
    try:
        m = re.search(r"/(session-[^/]+\.scope)", Path("/proc/self/cgroup").read_text())
    except OSError:
        return ""
    return m.group(1) if m else ""


# the SSH server's programs, by their file: a process's name (comm) is whatever it sets, so a user's own program named
# "sshd" in their desktop session must not be taken for one. " (deleted)": the file was replaced by an update since
SSH_EXES = {"/usr/bin/sshd", "/usr/sbin/sshd", "/usr/lib/ssh/sshd-session"}


def ssh_exe(d: Path) -> str:
    """"sshd" or "sshd-session" when /proc/PID (d) runs that SSH server program; "tsshd" when it runs a program file
    named tsshd (it installs to /usr/local/bin or the user's own ~/.local/bin, so any folder; callers only take one
    that sits in a remote login's session); else ""."""
    try:
        exe = str((d / "exe").readlink()).removesuffix(" (deleted)")
    except OSError:
        return ""
    name = exe.rsplit("/", 1)[-1]
    return name if exe in SSH_EXES or name == "tsshd" else ""


def tsshd_scopes() -> set:
    """The login-session scopes (session-N.scope, at the top of the cgroup tree) holding a running tsshd."""
    scopes = set()
    for d in PROC.iterdir():
        if not d.name.isdigit() or ssh_exe(d) != "tsshd":
            continue
        try:
            m = re.search(r"^0::/user\.slice/user-\d+\.slice/(session-[^/]+\.scope)$", (d / "cgroup").read_text(), re.M)
        except OSError:
            continue
        if m:
            scopes.add(m.group(1))
    return scopes


def end_remote_logins() -> tuple:
    """After the SSH server is stopped: sign out every computer still connected through it. Stopping sshd only
    stops NEW sign-ins (its KillMode=process leaves each connection running), so Settings' promise that turning remote
    login off disconnects other computers needs this. Ends each logind session that came in through sshd, then any
    SSH or tsshd connection process left outside one. The session this helper itself runs in (someone ran it from an
    SSH terminal) is left alone, so the answer still reaches them; it ends when they sign out. Returns how many
    connections were ended, and whether every sign-in could be checked (False: a loginctl call failed, so one may
    be left; Settings says so)."""
    mine, ended, tsshd, ssh_scopes, other_scopes = own_scope(), 0, tsshd_scopes(), set(), set()
    listing = run("loginctl", "list-sessions", "--no-legend")
    sure = listing.returncode == 0
    for sid in {l.split()[0] for l in listing.stdout.splitlines() if l.split()}:
        if not re.fullmatch(r"[\w-]+", sid) or f"session-{sid}.scope" == mine:
            continue
        shown = run("loginctl", "show-session", sid, "-p", "Service", "-p", "State")
        info = dict(l.split("=", 1) for l in shown.stdout.splitlines() if "=" in l)
        if shown.returncode or "Service" not in info:
            sure = False
            continue
        if info.get("Service") != "sshd":
            other_scopes.add(f"session-{sid}.scope")
            continue
        ssh_scopes.add(f"session-{sid}.scope")
        # a "closing" session's SSH connection has closed. Still signed in when it holds a tsshd: tsshd signs in over
        # SSH and then keeps the terminal going over UDP in that same session. Otherwise it's only something left
        # running: ended too, but not counted as a computer signed in now
        live = info.get("State") != "closing" or f"session-{sid}.scope" in tsshd
        if run("loginctl", "terminate-session", sid).returncode:
            sure = False
        elif live:
            ended += 1
    me, procs = os.getpid(), []
    for d in PROC.iterdir():
        if not d.name.isdigit() or int(d.name) == me:
            continue
        comm = ssh_exe(d)
        if not comm:
            continue
        try:
            cg = (d / "cgroup").read_text()
            ppid = (d / "stat").read_text().rsplit(")", 1)[1].split()[1]
            uid = int(next(l.split()[1] for l in (d / "status").read_text().splitlines() if l.startswith("Uid:")))
        except (OSError, IndexError, ValueError, StopIteration):
            continue
        # sshd-session: one per connection (OpenSSH 9.8+); "sshd": the listener is stopped, so any left are
        # connections (older OpenSSH); tsshd: a remote login that keeps going over UDP
        if mine and f"/{mine}" in cg:
            continue
        # only this computer's own remote logins: still in the SSH service's group or in a user's login session, at
        # the top of the cgroup tree. Anchored so an SSH server or session inside a container or VM (a nested
        # .../libpod-x.scope/container/system.slice/sshd.service, an nspawn payload, an LXC user.slice) is left alone
        if not re.search(r"^0::/(system\.slice/sshd\.service|user\.slice/user-\d+\.slice/session-[^/]+\.scope)$",
                         cg, re.M):
            continue
        # a tsshd (matched by its file's name only) only when it sits in a remote login: the SSH service's group or
        # an SSH session's scope, never a session known to be a desktop one. When a session lookup failed, any
        # session not known to be a desktop one counts, so a remote terminal isn't left running on a guess
        scope = m.group(1) if (m := re.search(r"^0::/user\.slice/user-\d+\.slice/(session-[^/]+\.scope)$", cg, re.M)) else ""
        if comm == "tsshd" and not ("0::/system.slice/sshd.service\n" in cg + "\n" or scope in ssh_scopes
                                    or (not sure and scope and scope not in other_scopes)):
            continue
        procs.append((int(d.name), comm, cg, ppid, uid, scope))
    try:
        sshd_uid = pwd.getpwnam("sshd").pw_uid
    except KeyError:
        sshd_uid = -1
    pids = {str(p[0]) for p in procs}
    guessed = set()            # sessions a failed lookup left unchecked whose tsshd was signed out: one computer each
    for pid, comm, cg, ppid, _uid, scope in procs:
        try:
            os.kill(pid, 15)
        except OSError:
            continue
        if comm == "tsshd" and scope and scope not in ssh_scopes and scope not in guessed:
            guessed.add(scope)
            ended += 1
        # a connection no logind session counted: its first SSH process (not the helpers it starts), and only once
        # someone has signed in through it (a child running as a real user, not root or the sshd sandbox user), so a
        # stranger sitting at the password prompt isn't reported as a signed-in computer
        if (comm != "tsshd" and "/session-" not in cg and ppid not in pids
                and any(q[3] == str(pid) and q[4] not in (0, sshd_uid, 65534) for q in procs)):
            ended += 1
    return ended, sure


def ssh_set(on: bool) -> dict:
    """Remote login on or off. Off also signs out the computers connected now (see end_remote_logins)."""
    r = run("systemctl", "enable" if on else "disable", "--now", "sshd.service")
    if r.returncode:
        return {"ok": False, "errors": r.stderr.strip() or "the SSH server didn't " + ("start" if on else "stop")}
    if on:
        return {"ok": True, "errors": "", "ended": 0}
    ended, sure = end_remote_logins()
    return {"ok": True, "errors": "", "ended": ended, "checkedAll": sure}


def autoupdate_status() -> dict:
    import updater
    import tested_releases
    setting = updater.read_level()
    import updates_restart
    labels = dict(updater.LEVELS)
    tested = tested_releases.enabled()
    if tested:
        labels.update(security='Tested system releases', starchaser='Tested system releases')
    return {"ok": True, "restartIdle": updates_restart.enabled(), "restartTonight": __import__("update_experience").read(updates_restart.TONIGHT).get("at", 0), "level": setting["level"], "user": setting["user"], "changed": setting["changed"],
            "labels": labels, "testedReleases": tested, "lastRun": updater.read_auto_last(), "restorePoints": updater.restore_points(),
            "undone": updater.read_undone(), "pause": __import__("update_experience").paused() or updater.undo_pause(), "wentBack": updater.read_went_back() if setting["level"] == "off" else None}


def autoupdate_set(level: str) -> dict:
    import updater
    try:
        uid = int(os.environ.get("PKEXEC_UID", "-1"))
        if level in ('restart-on', 'restart-off'):
            if uid < 1000:
                raise ValueError("Run this from Settings.")
            import updates_restart
            updates_restart.save(level == 'restart-on')
            return {'ok': True, 'errors': '', 'restartIdle': level == 'restart-on'}
        if level == "pause":
            if uid < 1000:
                raise ValueError("Run this from Settings.")
            import update_experience
            update_experience.pause()
            return {"ok": True, "errors": "", "pause": update_experience.paused()}
        if level in ("tonight", "tonight-off"):
            if uid < 1000:
                raise ValueError("Run this from Settings.")
            import updates_restart
            if level == "tonight-off":
                updates_restart.cancel_tonight()
            else:
                updates_restart.tonight()
            return {"ok": True, "errors": ""}
        if level == "resume":
            if uid < 1000:
                raise ValueError("Run this from Settings.")
            pwd.getpwuid(uid)
            updater.clear_undone()
            __import__("update_experience").resume()
            return {"ok": True, "errors": "", "level": updater.read_level()["level"]}
        updater.write_level(level, uid)
    except (ValueError, KeyError, OSError) as e:
        return {"ok": False, "errors": str(e) if not isinstance(e, KeyError) else "That person's account no longer exists."}
    try:
        action = "disable" if level == "off" else "enable"
        result = subprocess.run(["systemctl", action, "--now", "starchaser-autoupdate.timer"],
                                capture_output=True, text=True, timeout=30)
        error = "" if result.returncode == 0 else (
            "The choice was saved, but this computer's Starchaser is too old to run automatic updates. Update it first."
            if "not found" in result.stderr or "does not exist" in result.stderr else
            "The choice was saved, but the automatic update timer couldn't be changed. " + result.stderr.strip()[:300])
    except (OSError, subprocess.SubprocessError):
        error = "The choice was saved, but the automatic update timer couldn't be changed. Try again."
    return {"ok": not error, "errors": error, "level": level}


def autoupdate_default() -> dict:
    """Setup of a new install: automatic updates start at updater.DEFAULT_LEVEL, so a computer whose welcome was closed
    or skipped still gets security fixes. A saved choice (Off too) stays as it is. The timer is enabled with it; if it
    can't be, the default is taken back, so Settings never shows automatic updates that would never run."""
    import updater
    if not updater.write_default_level():
        return {"ok": True, "errors": "", "changed": False, "level": updater.read_level()["level"]}
    try:
        result = subprocess.run(["systemctl", "enable", "starchaser-autoupdate.timer"], capture_output=True, text=True, timeout=30)
        error = "" if result.returncode == 0 else result.stderr.strip()[:300] or "systemctl failed"
    except (OSError, subprocess.SubprocessError) as e:
        error = str(e)[:300] or "systemctl failed"
    if error:
        updater.LEVEL_FILE.unlink(missing_ok=True)
        return {"ok": False, "errors": "The automatic update timer couldn't be turned on, so automatic updates stay off: " + error,
                "changed": False, "level": "off"}
    return {"ok": True, "errors": "", "changed": True, "level": updater.DEFAULT_LEVEL}


def welcome_apply(req: dict) -> dict:
    """The first-run welcome's security choices, in one password prompt: USB protection level, remote login (SSH),
    automatic updates, and the firewall (on: Starchaser's first policy, incoming blocked except remote login, Tailscale, the fleet and
    local discovery from trusted networks; kept at once, there's no remote session to lose)."""
    errors, warnings = [], []
    if req.get("autoupdate"):
        result = autoupdate_set(req["autoupdate"])
        if not result["ok"]:
            errors.append(result["errors"])
    if req.get("usb") in ("relaxed", "strict", "off"):
        r = usb_level(req["usb"])
        if not r.get("ok", True):
            errors.append(r.get("errors", "USB protection"))
    if isinstance(req.get("ssh"), bool):
        r = ssh_set(req["ssh"])
        if not r["ok"]:
            errors.append(r["errors"])
    if isinstance(req.get("firewall"), bool) and waiting():
        errors.append(BUSY)
    elif isinstance(req.get("firewall"), bool):
        try:
            pol = json.loads(fw.POLICY.read_text())
        except (OSError, ValueError):
            pol = {}
        fw.TRUST_FIRST.unlink(missing_ok=True)        # (retired flag an older setup may have left)
        first = "rules" not in pol        # no policy yet; an empty rule list someone chose stays empty
        pol.setdefault("version", 2)
        pol.setdefault("unknownZone", "public")
        for k in ("networks", "addresses", "services", "rules"):
            pol.setdefault(k, [])
        pol["defaults"] = {"in": "block", "out": "allow", "logBlocked": True, **pol.get("defaults", {})}
        if first:                         # the same first policy as Settings > Firewall's
            pol["rules"] = first_rules()
            pol["privacy"] = fw.privacy_engine.DEFAULT
            pol["recordActivity"] = False       # off until the person turns it on (Settings > Firewall > Apps)
        # no network is marked as a network you trust by itself (decided 2026-10-07: ask once, no auto-trust): the networks
        # this computer is on count as Public until the one-time question (starchaser firewall ask) is answered
        pol["enabled"] = req["firewall"]
        commit(pol, 0, "Turned " + ("on" if req["firewall"] else "off") + " in the welcome")
        # what applied but went wrong on the way (a hand-written rules file with an error left out when it turned on):
        # commit prints it for Settings, which the welcome session doesn't read, so the result carries it
        warnings.extend(fw.WARNINGS)
    return {"ok": not errors, "errors": "; ".join(e for e in errors if e),
            **({"warning": " ".join(warnings)} if warnings else {})}


def software_door():
    path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "starchaser-admin-software")
    loader = importlib.machinery.SourceFileLoader("starchaser_admin_software", path)
    door = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
    loader.exec_module(door)
    return door


def stamp_software_grant() -> None:
    """The welcome's one password also opens the software window that starchaser-admin-software keeps (its grant for
    this login session), so Software and Updates don't ask again right after setup (decided 2026-10-08: the password
    once per sitting for installs and updates). Its own code writes it, so the grant's rules live in one place."""
    try:
        door = software_door()
        door.stamp(door.grant_file())
    except Exception:
        pass                                           # no grant: the next install asks again, nothing worse


def stamp_software_grant_after_password() -> None:
    """The rest of Settings > Updates shares that window (decisions 2026-11-07 #30): 50-starchaser-software.rules lets
    update-channel-set and autoupdate-set through while the grant is fresh, and when one of them asked for the
    password instead (no fresh grant), that password opens the window as an update's would. Like the door's runs, one
    the grant let in renews nothing, so these can't keep the window open by themselves."""
    try:
        door = software_door()
        f = door.grant_file()
        if not door.fresh(f):
            door.stamp(f)
    except Exception:
        pass                                           # no grant: the next change asks again, nothing worse


def welcome_session() -> None:
    """The first-run welcome's admin work after ONE password: it starts this through pkexec the first time it needs
    root, keeps it while the welcome is open, and sends jobs as JSON lines on stdin; it ends when stdin closes (the
    welcome closed). These kinds of job only, checked like their one-off versions:
        {"id": n, "op": "software", "request": {"action": "install", "source": "repo"|"aur", "names": [...]}}
        {"id": n, "op": "updates", "request": {"aur": [...], "flatpak": bool}} (full system update before apps)
        {"id": n, "op": "security", "request": {"usb": ..., "ssh": ..., "firewall": ...}}
        {"id": n, "op": "fleet-ready", "request": {"networks": [uuid, ...]}}   (the "Join your fleet" page)
        {"id": n, "op": "fleet-networks", "request": {"kind": "tailscale", "on": bool}}   (its Tailscale switch)
        {"id": n, "op": "trust-network", "request": {"network": uuid}}   (Yes to "Is <network> your own network?"; a
                                                  network nobody has marked only, like firewall-mark-network --only-unmarked)
        {"id": n, "op": "autologin-off", "request": {}}   (the Security page's "Require a password at startup")
        {"id": n, "op": "seal", "request": {"installs": k}}   (the welcome window closed with app installs still to go)
    After "seal" this session takes at most k more app installs and nothing else: no security or fleet change, and no
    more installs, until a new session (a new password) is opened. The welcome seals before it hides its window.
    Progress comes back as the usual "@@{json}" lines with "task": n added, then {"event": "task-exit", "task": n}."""
    import tempfile

    sealed = False
    installs_left = 0

    def say(ev: dict) -> None:
        print("@@" + json.dumps(ev), flush=True)

    say({"event": "ready"})
    stamp_software_grant()                            # the password, just now
    for line in sys.stdin:
        try:
            job = json.loads(line)
        except ValueError:
            continue
        if not isinstance(job, dict):
            continue
        tid, op, req = job.get("id"), job.get("op"), job.get("request") or {}
        # one job that throws must not end the session (the welcome would wait for its task-exit forever): log the
        # traceback for the journal, answer that job as failed, and keep reading
        try:
            if op == "seal":
                k = req.get("installs")
                left = k if isinstance(k, int) and not isinstance(k, bool) and k > 0 else 0
                installs_left = min(installs_left, left) if sealed else left    # a seal only ever narrows
                sealed = True
                say({"event": "task-exit", "task": tid, "code": 0, "result": {"ok": True}})
                continue
            if sealed and not (op == "software" and installs_left > 0):
                say({"event": "task-exit", "task": tid, "code": 1,
                     "result": {"ok": False, "errors": "Not done: the welcome was closed. Open it again and try again."}})
                continue
            if sealed:
                installs_left -= 1
            if op == "security":
                try:
                    with locked():
                        r = welcome_apply(req)
                except SystemExit:                        # die() inside: report it, keep the session
                    r = {"ok": False, "errors": "That didn't apply."}
                say({"event": "task-exit", "task": tid, "code": 0 if r.get("ok") else 1, "result": r})
            elif op == "fleet-ready":
                # the page sends the networks it named (maybe none): only those are counted as networks you trust
                named = req.get("networks")
                ids = [u for u in named or [] if isinstance(u, str) and UUID.fullmatch(u)]
                with locked():
                    r = fleet_ready(ids, named_only=isinstance(named, list))
                say({"event": "task-exit", "task": tid, "code": 0 if r.get("ok") else 1, "result": r})
            elif op == "fleet-networks" and req.get("kind") in ("tailscale", "vpn") and isinstance(req.get("on"), bool):
                r = quietly(fleet_networks_set, req["kind"], req["on"])
                say({"event": "task-exit", "task": tid, "code": 0 if r.get("ok") else 1, "result": r})
            elif op == "trust-network" and isinstance(req.get("network"), str) and UUID.fullmatch(req["network"]):
                # No needs no password (starchaser-firewall-keep); only Yes comes here. The answer carries the
                # fleet status, so the welcome's remote login and fleet pages follow at once
                with locked():
                    r = quietly(mark_network, req["network"], "trusted", True)
                r = {**fleet_status(), "ok": bool(r.get("ok")), "errors": r.get("errors") or ""}
                say({"event": "task-exit", "task": tid, "code": 0 if r["ok"] else 1, "result": r})
            elif op == "autologin-off":
                # only ever off from here: the welcome offers the safer choice; turning it on stays in Settings
                try:
                    r = autologin_set(False)
                except SystemExit:                        # die() inside: report it, keep the session
                    r = {"ok": False, "errors": "Couldn't change automatic sign-in. Try again or open Review sign-in settings."}
                say({"event": "task-exit", "task": tid, "code": 0 if r.get("ok") else 1, "result": r})
            elif op == "updates":
                import updater
                uid = int(os.environ.get("PKEXEC_UID", "-1"))
                if uid < 1000:
                    raise ValueError("A signed-in account must request updates.")
                aur = [n for n in req.get("aur", []) if isinstance(n, str) and updater.NAME.fullmatch(n) and not updater.starchaser_own(n)]
                request = {"aur": aur, "flatpak": req.get("flatpak") is True, "decisions": []}
                script = "import sys,json; sys.path.insert(0,sys.argv[1]); import updater; r=json.loads(sys.argv[3]); updater.manual_run(int(sys.argv[2]),r,r['aur'])"
                p = subprocess.Popen([sys.executable, "-c", script, os.path.dirname(os.path.realpath(__file__)), str(uid), json.dumps(request)], stdout=subprocess.PIPE, text=True, errors="replace")
                for line in p.stdout:
                    if line.startswith("@@"):
                        ev = json.loads(line[2:]); ev["task"] = tid; say(ev)
                    elif line.strip():
                        say({"event": "log", "task": tid, "text": line.rstrip()[:400]})
                code = p.wait()
                if code == 0:
                    stamp_software_grant()
                say({"event": "task-exit", "task": tid, "code": code})
            elif op == "software" and req.get("action") == "install":
                fd, path = tempfile.mkstemp(prefix="starchaser-welcome-", suffix=".json")
                with os.fdopen(fd, "w") as f:
                    json.dump(req, f)
                p = subprocess.Popen([sys.executable, os.path.realpath(__file__), "software-run", path],
                                     stdout=subprocess.PIPE, text=True, errors="replace")
                for l in p.stdout:                         # software.py validates the request itself
                    if l.startswith("@@"):
                        try:
                            ev = json.loads(l[2:])
                        except ValueError:
                            continue
                        ev["task"] = tid
                        say(ev)
                    elif l.strip():                        # the raw output: the welcome keeps the last lines for its log
                        say({"event": "log", "task": tid, "text": l.rstrip("\n")[:400]})
                code = p.wait()
                try:
                    os.unlink(path)
                except OSError:
                    pass
                if code == 0:                              # the window counts from the end of an install, as Software's
                    stamp_software_grant()
                say({"event": "task-exit", "task": tid, "code": code})
            else:
                say({"event": "task-exit", "task": tid, "code": 1, "result": {"ok": False, "errors": "not a welcome job"}})
        except Exception:
            import traceback
            traceback.print_exc(file=sys.stderr)
            say({"event": "task-exit", "task": tid, "code": 1, "result": {"ok": False, "errors": "That didn't work."}})

MC_ADMIN = Path(os.path.dirname(os.path.realpath(__file__))) / "starchaser-mission-control-admin"


def network_kinds(policy: dict) -> list:
    """This computer's networks now, each with the kind of network the firewall counts it as (fw.zone_map's
    reasoning, read without root)."""
    saved = [n for n in policy.get("networks") or [] if isinstance(n, dict)]
    # a connection's own entry first, else the one it is an alias of (a reinstalled profile, or the cable connection
    # NetworkManager made again after the install, the same network by its router: fw.record_identities); of two
    # entries that list it, the stricter holds, as in fw.match_network
    known = {}
    for n in saved:
        for a in n.get("aliases") or []:
            if known.get(a) != "public":
                known[a] = n.get("zone")
    known.update({n.get("uuid"): n.get("zone") for n in saved})
    out = []
    for n in fw.active_networks():
        dev, typ = n.get("device", ""), n.get("type", "")
        if typ == "bridge" or dev.startswith(("virbr", "docker", "vnet", "br-")):
            continue
        if typ in ("vpn", "wireguard", "tun") or dev.startswith(("wg", "tun", "ppp")):
            zone = "vpn"
        elif dev == "tailscale0":
            zone = "tailscale"
        else:
            zone = known.get(n.get("uuid")) or policy.get("unknownZone") or "public"
        # marked: someone chose its kind (the welcome's "Is <network> your own network?" or Settings); unmarked ones
        # are the only networks the welcome asks about
        out.append({"uuid": n.get("uuid", ""), "name": n.get("name", ""), "type": typ, "device": dev, "zone": zone,
                    "marked": n.get("uuid") in known})
    return out


def fleet_status() -> dict:
    """fleet-networks without arguments: read-only, so Settings, the welcome and the fleet's tools can ask without
    a password. ready: the fleet can reach this computer now (remote login on, and the firewall off or a network it
    is on counted as a fleet network)."""
    pol = current_policy()
    nets = fw.fleet_networks()
    zones = fw.fleet_zones(nets)
    kinds = network_kinds(pol)
    on = bool(pol.get("enabled"))
    remote = run("systemctl", "is-active", "sshd.service").stdout.strip() == "active"
    return {"ok": True, **nets, "zones": zones, "apps": list(fw.FLEET_APPS), "firewall": on, "networks": kinds,
            "remoteLogin": remote, "tailscaleUp": Path("/sys/class/net/tailscale0").exists(),
            "ready": remote and (not on or any(n["zone"] in zones for n in kinds))}


def refresh_mission_control() -> None:
    """Mission Control's web listener has its own address filter for Tailscale: written again for the switch now
    (only when web access is on; refresh changes no firewall rule)."""
    try:
        web = json.loads(Path("/etc/starchaser/mission-control.json").read_text()).get("web")
    except (OSError, ValueError, AttributeError):
        web = False
    if web and MC_ADMIN.exists():
        try:
            subprocess.run([str(MC_ADMIN), "refresh"], capture_output=True, timeout=60)
        except (OSError, subprocess.TimeoutExpired) as e:   # the firewall part already happened; Settings shows it
            print(f"starchaser-admin: Mission Control not refreshed: {e}", file=sys.stderr, flush=True)


def fleet_networks_set(kind: str, on: bool) -> None:
    """One of the fleet's switches (tailscale, vpn): the fleet's own firewall switches move with it in one change
    (fw.follow_fleet), then the switch is saved. Prints one JSON answer."""
    with locked():
        # read under the lock: two switches changed at once must not save a stale value for the other one
        nets = dict(fw.fleet_networks(), **{kind: on})
        pol = current_policy()
        moved, changed = fw.follow_fleet(pol, nets)
        what = {"tailscale": "Tailscale", "vpn": "your VPN"}[kind]
        if changed and pol.get("enabled"):
            # (commit prints the answer; on failure it stops here and the switch isn't saved)
            commit(moved, 0, f"Your fleet {'can' if on else 'can no longer'} reach this computer over {what}",
                   fold=lambda prev: fw.follow_fleet(prev, nets)[0])
        elif changed and fw.POLICY.exists():
            # the firewall is off: only the saved policy changes, for the next time it's turned on
            fw.write_atomic(fw.POLICY, json.dumps(fw.validate(moved), indent=2) + "\n", 0o644)
        fw.save_fleet_networks(nets)
        if not (changed and pol.get("enabled")):
            print(json.dumps({"ok": True, "errors": "", "changed": changed}))
    refresh_mission_control()


def quietly(fn, *args, **kwargs) -> dict:
    """Run a step that prints its own JSON answer (and may stop with die()), and return that answer instead."""
    import io
    buf = io.StringIO()
    try:
        with contextlib.redirect_stdout(buf):
            fn(*args, **kwargs)
    except SystemExit:
        pass
    for line in reversed(buf.getvalue().splitlines()):
        if line.startswith("{"):
            try:
                return json.loads(line)
            except ValueError:
                break
    return {"ok": False, "errors": "That didn't apply."}


def fleet_ready(uuids: list, named_only: bool = False) -> dict:
    """Ready to join a fleet: remote login on (paired computers talk through it), and the networks named, or the
    ones this computer is on now that aren't VPNs or Tailscale, counted as networks you trust (the person said so on the
    welcome's "Join your fleet" page; the same as answering Yes to "Is this a network you trust?"). named_only:
    no networks named means none (the welcome names the ones it showed). With the firewall off nothing needs marking."""
    errors, marked = [], []
    r = ssh_set(True)
    if not r.get("ok"):
        errors.append(r.get("errors") or "Remote login didn't start.")
    pol = current_policy()
    if pol.get("enabled"):
        kinds = network_kinds(pol)
        if not uuids and not named_only:
            uuids = [n["uuid"] for n in kinds if n["zone"] not in ("trusted", "vpn", "tailscale")]
        for uid in uuids:
            name = next((n["name"] for n in kinds if n["uuid"] == uid), "")
            res = quietly(mark_network, uid, "trusted", over_public=True)
            if res.get("ok"):
                marked.append(name or uid)
            else:
                errors.append(res.get("errors") or f"{name or 'That network'} wasn't counted as a network you trust.")
    if marked:
        home_addresses()      # trusted now: these Wi-Fi networks reconnect with the real address
    # (the status first: its own "ok" must not cover up what went wrong here)
    return {**fleet_status(), "ok": not errors, "errors": "; ".join(errors), "marked": marked}


FLEET_LINK_SWITCHES = (("ssh", "Remote login"), ("starchaser-devices", "Fleet (joining)"))


def fleet_switches_on() -> dict:
    """Fleet v2 rule 35.6: the fleet link uses only the two ports the firewall already lets in for the fleet, SSH and
    Fleet (joining) (TCP 47744), on the networks the fleet's switches cover. Turn on (and later Join) switches them
    on if they are off: remote login started, and Starchaser's own Allow rule for each enabled again if someone
    switched it off. Only switching on: no rule is added, moved or widened (one that is gone, or that the person
    changed, is theirs), so a firewall reload keeps exactly this."""
    errors = []
    r = ssh_set(True)
    if not r.get("ok"):
        errors.append(r.get("errors") or "Remote login didn't start.")
    pol = current_policy()
    if pol.get("enabled"):
        rules = [dict(x) for x in pol.get("rules") or []]
        changed = False
        for app, name in FLEET_LINK_SWITCHES:
            mine = [x for x in rules if fw.is_fleet_rule(x) and x.get("app") == app]
            if not mine:
                errors.append(f"Your firewall has no {name} switch; turn it on in Settings > Firewall.")
            elif not any(x.get("enabled", True) for x in mine):
                mine[0]["enabled"] = True
                changed = True
        if changed:
            # (only Starchaser's own Allows switched on: commit keeps it without a countdown, only_enables_basic_allows)
            res = quietly(commit, dict(pol, rules=rules), 120, "Your fleet can reach this computer: Remote login and "
                          "Fleet (joining) are on")
            if not res.get("ok"):
                errors.append(res.get("errors") or "The fleet's firewall switches didn't turn on.")
    return {"ok": not errors, "errors": "; ".join(errors)}


def refresh_firewall_zones() -> None:
    """Tailscale turned on or off here: the firewall's Tailscale zone follows now, not at the next check (up to a minute)
    (which also catches a sign-in done later, when tailscale0 appears)."""
    try:
        with locked():
            fw.refresh_zones()
    except Exception as e:                             # the firewall's upkeep must not fail the Tailscale switch
        print(f"starchaser-admin: firewall zones not refreshed: {e}", file=sys.stderr, flush=True)


def refresh_stats_after_entry() -> None:
    """refresh_stats() for a change that just wrote its History entry: a check Settings counts must come more than a
    second after that entry (FirewallPage liveConfirmed), or the page keeps saying "making sure the new settings are
    working…" until the timer comes round. Both times are whole seconds, so the check waits for the second
    after next (a fixed 1.2 s could land on +1)."""
    done = int(time.time())                           # the entry's second, or a later one
    time.sleep(max(0.0, done + 2 - time.time()) + 0.05)
    refresh_stats()


def refresh_stats() -> None:
    """Rewrite the stats file now (it holds the list of 15-minute allows that Settings shows), so a page that reads
    the state right after allowing or stopping new connections sees the change instead of the timer's last snapshot."""
    try:
        fw.stats(zones_checked=_held > 0)
    except Exception as e:                             # the allow itself already worked; the timer catches up
        print(f"starchaser-admin: stats not refreshed: {e}", file=sys.stderr, flush=True)


# ---- Sign in automatically after a restart (Settings > Security): greetd's [initial_session], once per boot.
# The choice is saved in AUTOLOGIN_SAVED, so running the desktop setup again keeps it (starchaser-desktop-setup.sh
# reads it) instead of putting its own default back. Nothing restarts: greetd reads its config at the next start.
GREETD_CONF = Path("/etc/greetd/config.toml")
AUTOLOGIN_SAVED = Path("/var/lib/starchaser/autologin.json")
SESSION_CMD = "/usr/local/lib/starchaser/starchaser-session"   # off PATH since the one command
USERNAME = re.compile(r"[a-z_][a-z0-9_-]{0,31}")
def autologin_block(user: str) -> str:
    return (f"\n# AUTOLOGIN=yes: log {user} in at boot (remote desktop works after a restart with nobody here)\n"
            f"[initial_session]\ncommand = \"{SESSION_CMD}\"\nuser = \"{user}\"\n")


def autologin_strip(text: str) -> str:
    """The config without its [initial_session] section (and the setup's comment line above it). Line by line:
    comments are kept (one before a later section belongs to that section), the section's own lines are not."""
    out, skip = [], False
    for line in text.splitlines():
        s = line.strip()
        if s.startswith("["):
            skip = s.startswith("[initial_session]")
            if skip:
                while out and (not out[-1].strip() or out[-1].startswith("# AUTOLOGIN=yes")):
                    out.pop()
                continue
        if skip and s and not s.startswith("#"):
            continue
        out.append(line)
    return "\n".join(out).rstrip("\n") + "\n"


def autologin_status() -> dict:
    """No root needed (the config is world-readable): whether greetd signs someone in at boot, and whom."""
    try:
        text = GREETD_CONF.read_text()
    except OSError:
        return {"ok": True, "available": False, "on": False, "user": ""}
    # only Starchaser's own login screen: another greetd setup is left alone (the switch isn't shown)
    available = "[default_session]" in text and "/usr/share/starchaser/greeter/" in text
    m = re.search(r"(?ms)^[ \t]*\[initial_session\][^\n]*\n?(.*?)(?=^[ \t]*\[|\Z)", text)
    user = ""
    if m:
        u = re.search(r'(?m)^\s*user\s*=\s*"([^"]*)"', m.group(1))
        user = u.group(1) if u else ""
    return {"ok": True, "available": available, "on": bool(m), "user": user}


def autologin_set(on: bool) -> dict:
    user = pwd_name(int(os.environ.get("PKEXEC_UID", "0")))
    if not user or not USERNAME.fullmatch(user):
        die("Nothing was changed: Settings couldn't tell which account asked.")
    # one change at a time: the login screen's config and the saved choice are written together, so a second change
    # made at the same moment can't leave the saved choice saying the opposite of the config
    AUTOLOGIN_SAVED.parent.mkdir(parents=True, exist_ok=True)
    with open(AUTOLOGIN_SAVED.with_name("autologin.lock"), "w") as lk:
        fcntl.flock(lk, fcntl.LOCK_EX)
        return _autologin_set(on, user)


def _autologin_set(on: bool, user: str) -> dict:
    if not autologin_status()["available"]:
        die("Nothing was changed: this computer doesn't use the Starchaser login screen.")
    text = GREETD_CONF.read_text()
    new = autologin_strip(text)
    if on:
        new += autologin_block(user)
    if new != text:
        tmp = GREETD_CONF.with_name(GREETD_CONF.name + ".starchaser-new")
        tmp.write_text(new)
        os.chmod(tmp, 0o644)
        os.replace(tmp, GREETD_CONF)
    tmp = AUTOLOGIN_SAVED.with_name(AUTOLOGIN_SAVED.name + ".new")
    tmp.write_text(json.dumps({"on": on, "user": user if on else "", "by": user, "at": int(time.time())}) + "\n")
    os.chmod(tmp, 0o644)
    os.replace(tmp, AUTOLOGIN_SAVED)
    st = autologin_status()
    ok = st["on"] == on and (not on or st["user"] == user)
    return {**st, "ok": ok, "errors": "" if ok else "The sign-in screen's settings didn't change. Try again."}


# ---- A restart from the lock screen skips automatic sign-in once (decided 2026-11-07 #21). The lock screen's
# Restart (Can't unlock?, and the power key's choices there) writes this mark just before it restarts; greetd.service's
# drop-in runs `password-next-start check` before greetd starts. At the next boot that turns the mark into greetd's own
# runfile ("the automatic sign-in already ran this boot"), so the login screen asks for the password, and removes it.
# Normal restarts and power loss never write it. It holds the boot it was written in: greetd restarting in that same
# boot (Restart=always) leaves it for the real restart.
PASSWORD_NEXT_START = Path("/var/lib/starchaser/password-next-start")
GREETD_RUNFILE = Path("/run/greetd.run")
BOOT_ID = Path("/proc/sys/kernel/random/boot_id")


def password_next_start(word: str) -> dict:
    boot = BOOT_ID.read_text().strip()
    try:
        marked = PASSWORD_NEXT_START.read_text().strip()
    except FileNotFoundError:
        marked = None
    if word == "on":
        PASSWORD_NEXT_START.parent.mkdir(parents=True, exist_ok=True)
        tmp = PASSWORD_NEXT_START.with_name(PASSWORD_NEXT_START.name + ".new")
        tmp.write_text(boot + "\n")
        os.chmod(tmp, 0o644)
        os.replace(tmp, PASSWORD_NEXT_START)
        return {"ok": True, "marked": True}
    if word == "off":                                 # the restart was refused: power loss later keeps signing in
        if marked == boot:                            # only this boot's own mark (a waiting one is the next start's)
            PASSWORD_NEXT_START.unlink(missing_ok=True)
        return {"ok": True, "marked": False}
    if marked is None or marked == boot:              # check: nothing marked, or not restarted yet
        return {"ok": True, "skipped": False}
    GREETD_RUNFILE.touch()                            # first, so a failure leaves the mark for the next try
    PASSWORD_NEXT_START.unlink(missing_ok=True)
    return {"ok": True, "skipped": True}


def once_args(argv: list) -> tuple:
    """Parse temporary-permission arguments strictly; interface names are exact, never patterns."""
    rest = list(argv[1:])
    iface = ""
    if "--iface" in rest:
        at = rest.index("--iface")
        if at != len(rest) - 2 or not fw.ONCE_IFACE.fullmatch(rest[-1]):
            die("Nothing was changed: --iface needs one network adapter name at the end.")
        iface = rest[-1]
        rest = rest[:at]
    allowed = (3, 4) if argv[0] == "firewall-allow-once" else (3,)
    if len(rest) not in allowed or rest[1] not in ("tcp", "udp") or not rest[2].isdigit():
        die("Nothing was changed: use an address, tcp or udp, and a port from 1 to 65535.")
    try:
        # "any": every device on the network the adapter is on (Simple's For 15 minutes), never without one
        addr = "any" if rest[0] == "any" and iface else str(ipaddress.ip_address(rest[0]))
    except ValueError:
        die("not an address")
    if len(rest) == 4 and not rest[3].isdigit():
        die("Nothing was changed: the minutes have to be a whole number.")
    return addr, rest[1], int(rest[2]), int(rest[3]) if len(rest) == 4 else 15, iface


def end_once(spec: str) -> None:
    """--end-once addr/proto/port[/adapter],...: the temporary permissions (from Log) for a permission an Apply just
    turned off or removed, ended with it, so turning an app off blocks it in one step (QA 2026-11-05). Settings names
    them; this only tightens, so the quick command does it too. One that ran out or can't be read is skipped (Settings
    still lists any that is left, with End this permission)."""
    ended = False
    for item in filter(None, spec.split(",")):
        parts = item.split("/")
        if len(parts) not in (3, 4) or not parts[2].isdigit():
            continue
        try:
            ended = not fw.revoke_once(parts[0], parts[1], int(parts[2]), parts[3] if len(parts) == 4 else "",
                                       actor=account_caller()) or ended
        except ValueError:
            continue
    if ended:
        refresh_stats()


def account_caller():
    return int(os.environ.get("PKEXEC_UID", str(os.getuid())))


def users_status():
    users = account.accounts(caller=account_caller())
    viewer_admin = any(u["you"] and u["admin"] for u in users)
    return {"ok": True, "users": users, "admin": viewer_admin}


def user_change(cmd, argv, root=Path("/"), caller=None):
    caller = account_caller() if caller is None else caller
    if len(argv) < 2 or (cmd != "user-add" and len(argv) != 2) or (cmd == "user-add" and len(argv) < 3):
        raise ValueError("Choose an account and fill in its details.")
    name = account.valid_name(argv[1])
    if cmd == "user-add":
        # Check all records, including service accounts, before asking useradd to create anything.
        if any(line.split(":")[0] == name for line in (root / "etc/passwd").read_text().splitlines()):
            raise ValueError("That account name is already in use.")
        full = " ".join(argv[2:])
        if len(full) > 256 or any(c in full for c in ":\r\n\0"):
            raise ValueError("Enter a full name on one line without a colon.")
        password = account.password_line(sys.stdin)
        # Standard accounts use the installer's shell, without its administrator group.
        account.checked(["useradd", "--root", str(root), "-m", "-U", "-K", "UID_MIN=1000", "-K", "UID_MAX=59999",
                         "-s", "/bin/bash", "-c", full, name], "The account could not be added.")
        try:
            account.write_password(root, name, password)
            user = next(a for a in account.accounts(root, caller) if a["name"] == name)
            code = recovery_code.new_code()
            recovery_code.save(root, name, user["uid"], code)
        except (OSError, ValueError):
            account.checked(["userdel", "--root", str(root), name], "The account was added, but its password or password recovery code could not be set. Reset its password before using it.")
            recovery_code.forget(root, name)
            raise ValueError("The account couldn't be added. Any home folder created was kept.") from None
        account.create_login_keyring(root, name, password)
        added = {"ok": True, "name": name, "code": code, "version": recovery_code.status(root, name)["version"]}
        if root == Path("/") and USBG.exists() and shutil.which("usbguard"):
            result = usb_setup()
            if not result["ok"]:
                added["note"] = "Account added. USB protection needs attention in Settings > Security."
        return added
    user = account.find_account(name, root, caller, removing=cmd == "user-remove")
    if cmd == "user-administrator":
        account.checked(["usermod", "--root", str(root), "-a", "-G", "wheel", name],
                        "The account could not be made an administrator.")
        return {"ok": True, "name": name}
    if cmd == "user-password":
        account.write_password(root, name, account.password_line(sys.stdin))
        return {"ok": True, "name": name, "keyring": account.KEYRING_NOTE}
    if cmd == "user-remove":
        account.checked(["userdel", "--root", str(root), name], "The account could not be removed. Its files were kept.")
        recovery_code.forget(root, name)
        return {"ok": True, "name": name, "home": user["home"], "note": "The account was removed. Its files were kept in " + user["home"] + "."}
    if cmd == "user-reset-keyring":
        return {"ok": True, "name": name, "keyring": account.reset_keyring(root, user)}
    raise ValueError("That account command wasn't found.")


def recovery_code_change(cmd, argv, root=Path("/"), caller=None, stdin=sys.stdin):
    """recovery-code-new for the caller's own account; recovery-code-use for the caller's own account, or any regular
    account when the login screen (the greeter account, through its sudoers line) asks."""
    if caller is None:                                # pkexec (the lock screen, Settings) or sudo (the login screen)
        caller = int(os.environ.get("PKEXEC_UID") or os.environ.get("SUDO_UID") or os.getuid())
    if cmd == "recovery-code-new":
        if len(argv) != 1:
            raise ValueError("recovery-code-new takes no arguments: it makes a code for your own account.")
        user = next((a for a in account.accounts(root, caller) if a["you"]), None)
        if not user:
            raise ValueError("Only a regular account can have a recovery code.")
        code = recovery_code.new_code()
        recovery_code.save(root, user["name"], user["uid"], code)
        recovery_code.note(f"new recovery code made for {user['name']}")
        return {"ok": True, "name": user["name"], "code": code, "version": recovery_code.status(root, user["name"])["version"]}
    if len(argv) != 2:
        raise ValueError("Choose the account to set a new password for.")
    name = account.valid_name(argv[1])
    user = next((a for a in account.accounts(root, caller) if a["name"] == name), None)
    if not user:
        raise ValueError("That regular account wasn't found.")
    try:
        greeter = pwd.getpwnam("greeter").pw_uid == caller
    except KeyError:
        greeter = False
    if not greeter and user["uid"] != caller:
        raise ValueError("A recovery code sets a new password for your own account only.")
    code, password = (stdin.read().split("\n") + ["", ""])[:2]
    return recovery_code.use(root, name, user["uid"], code, password)


POLICY_INPUT_LIMIT = 1024 * 1024


def read_policy_input(path: str) -> dict:
    """Read a bounded regular file without blocking on a FIFO, before taking the firewall lock."""
    import stat
    fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
    with os.fdopen(fd, "rb") as stream:
        info = os.fstat(stream.fileno())
        if not stat.S_ISREG(info.st_mode) or info.st_size > POLICY_INPUT_LIMIT:
            raise ValueError("Choose a regular policy file smaller than 1 MB.")
        data = stream.read(POLICY_INPUT_LIMIT + 1)
        if len(data) > POLICY_INPUT_LIMIT:
            raise ValueError("The policy file is larger than 1 MB.")
    value = json.loads(data)
    if not isinstance(value, dict):
        raise ValueError("The policy must be an object.")
    return value


def settle_expired() -> bool:
    """Second Keep watchdog, called by the stats timer with the lock held."""
    pending = waiting()
    if not pending:
        return False
    try:
        expired = 0 < float(pending.get("deadline") or 0) <= time.time()
    except (TypeError, ValueError):
        return False
    if not expired:
        return False
    error = go_back(pending, "Not kept: went back by itself after the countdown")
    if error:
        print("starchaser-admin: couldn't go back after the countdown: " + error, file=sys.stderr, flush=True)
    return not waiting()


def set_language(value, root=Path("/"), execute=run):
    """Generate one supported locale before selecting it; leave every other locale enabled."""
    locale_file = root / "etc/locale.gen"
    original = locale_file.read_text()
    supported = {line.lstrip("# ").strip() for line in original.splitlines()}
    requested = value + " UTF-8"
    if not re.fullmatch(r"[a-z]{2,3}_[A-Z]{2}\.UTF-8(?:@[A-Za-z0-9_-]+)?", value) or requested not in supported:
        raise ValueError("Choose a supported language from the list.")
    lock_path = root / "run/starchaser-language.lock"
    with lock_path.open("w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        original = locale_file.read_text()
        lines = [requested if line.lstrip("# ").strip() == requested else line for line in original.splitlines()]
        fw.write_atomic(locale_file, "\n".join(lines) + "\n", 0o644)
        generated = execute("locale-gen")
        if generated.returncode:
            fw.write_atomic(locale_file, original, 0o644)
            raise ValueError("Couldn't prepare that language. Your language choice didn't change.")
        selected = execute("localectl", "set-locale", "LANG=" + value)
        if selected.returncode:
            raise ValueError("The language is installed, but couldn't be selected. Try again.")


def main(argv: list) -> None:
    global _firewall_authorization
    cmd = argv[0] if argv else ""
    if cmd in ("-h", "--help", "help") or any(a in ("-h", "--help") for a in argv[1:]):   # usage on request: no root
        print(__doc__.strip())                                                          # needed, nothing changes
        return
    if cmd == "commands":                             # read-only, so no root needed (see COMMANDS)
        if len(argv) != 1:
            print(json.dumps({"ok": False, "errors": "commands takes no arguments. Run '/usr/local/lib/starchaser/starchaser-admin --help' for available commands."}))
            sys.exit(2)
        print(json.dumps({"ok": True, "commands": list(COMMANDS)}))
        return
    if cmd not in COMMANDS:
        if cmd and not cmd.startswith("-") and (os.environ.get("PKEXEC_UID") or not sys.stdout.isatty()):
            # Settings (through the password box) or any other program: the newer-Settings-older-tools answer
            print(json.dumps({"ok": False, "errors": older_message(), "unknown": cmd[:40]}))
            sys.exit(2)
        message = (f"Unknown option {cmd!r}." if cmd.startswith("-") else
                   f"Unknown command {cmd!r}." if cmd else "No command given.")
        print(json.dumps({"ok": False, "errors": message +
                          " Run '/usr/local/lib/starchaser/starchaser-admin --help' for available commands.",
                          "unknown": cmd[:40]}))
        sys.exit(2)
    # the read-only answers below need no root; with the wrong number of words they say what they take instead of
    # falling through to the administrator-permission refusal (the command is wrong, not the caller's rights)
    if cmd in ("firewall-opens", "firewall-password-mode", "fleet-networks", "autologin", "home-versions", "autoupdate",
               "update-channel", "update-channel-check", "update-rollback", "users", "sharing-status"):
        if cmd == "firewall-opens":
            right, words = (len(argv) in (2, 3),
                            "a policy file or a history id: 'firewall-opens <policy.json>' or 'firewall-opens --history <id>'")
        elif cmd == "update-rollback":
            right, words = (len(argv) == 1 or (len(argv) == 2 and argv[1].isdigit()), "an optional update snapshot number")
        elif cmd == "firewall-password-mode":
            # reading it takes no words; changing it takes one ('sitting' or 'each'), the same the change itself accepts
            right = len(argv) in (1, 2) and (len(argv) == 1 or argv[1] in ("sitting", "each"))
            words = "no arguments, or one word: 'sitting' or 'each'"
        elif cmd == "autologin":
            # reading it takes no words; the switch below changes it with 'on' or 'off'
            right = len(argv) in (1, 2) and (len(argv) == 1 or argv[1] in ("on", "off"))
            words = "no arguments, or one word: 'on' or 'off'"
        elif cmd == "home-versions":
            right = len(argv) in (1, 2) and (len(argv) == 1 or argv[1] in ("on", "off"))
            words = "no arguments, or one word: 'on' or 'off'"
        elif cmd == "fleet-networks":
            # reading it takes no words; the two switches change one network each
            right = len(argv) in (1, 3) and (len(argv) == 1 or (argv[1] in ("tailscale", "vpn") and argv[2] in ("on", "off")))
            words = "no arguments, or a network kind and a switch: 'tailscale' or 'vpn', then 'on' or 'off'"
        else:
            right, words = len(argv) == 1, "no arguments"
        if not right:
            print(json.dumps({"ok": False, "errors": f"{cmd} takes {words}. "
                              "Run '/usr/local/lib/starchaser/starchaser-admin --help' for available commands."}))
            sys.exit(2)
    if cmd == "firewall-opens" and len(argv) in (2, 3):   # read-only: does this change need a fresh password?
        print(json.dumps(firewall_opens(argv)))
        return
    if argv == ["firewall-password-mode"]:
        print(json.dumps(password_mode(argv)))
        return
    if argv == ["fleet-networks"]:                    # read-only too
        print(json.dumps(fleet_status()))
        return
    if argv == ["autologin"]:                         # read-only too
        print(json.dumps(autologin_status()))
        return
    if argv == ["home-versions"]:                     # read-only too (the setting file is world-readable)
        import recovery_health
        print(json.dumps({"ok": True, "on": recovery_health.versions_enabled()}))
        return
    if argv == ["autoupdate"]:
        print(json.dumps(autoupdate_status()))
        return
    if argv == ["update-channel"]:
        import pkgrepo
        import updater
        try:
            status = pkgrepo.channel_status()
            # going back turned testing on (undo_locked): Settings > Updates says so until the channel changes
            status["wentBack"] = updater.read_channel_went_back() if status["channel"] == "testing" else None
            print(json.dumps(status))
        except OSError:
            die("The update channel could not be read. Try again.")
        return
    if argv == ["update-channel-check"]:
        import pkgrepo
        print(json.dumps(pkgrepo.testing_available()))
        return
    if cmd == "update-rollback" and (len(argv) == 1 or (len(argv) == 2 and argv[1].isdigit())):
        print(json.dumps(update_rollback(int(argv[1]) if len(argv) == 2 else None)))
        return
    if argv == ["users"]:
        try:
            print(json.dumps(users_status()))
        except (OSError, ValueError):
            die("The computer accounts could not be read.")
        return
    if cmd in SNAPSHOT_REFUSED and started_from_snapshot():
        die(SNAPSHOT_START)
    if cmd == "own-password":                         # the caller's own account, checked by passwd: no root
        if len(argv) != 1:
            print(json.dumps({"ok": False, "errors": "own-password takes no arguments; the passwords go on stdin."}))
            sys.exit(2)
        if os.geteuid() == 0:                         # as root, passwd would change root's password without asking
            die("Run own-password as yourself, not as an administrator. Nothing was changed.")
        try:
            current, new = (sys.stdin.read().split("\n") + ["", ""])[:2]
            result = account.change_own_password(current, new)
        except (OSError, ValueError, subprocess.SubprocessError) as e:
            die(str(e) if isinstance(e, ValueError) else "Your password could not be changed. Try again.")
        print(json.dumps(result))
        sys.exit(0 if result["ok"] else 1)
    if cmd == "recovery-code-status" and len(argv) <= 2:   # whether a code exists, never the code: no root
        try:
            name = account.valid_name(argv[1]) if len(argv) == 2 else pwd.getpwuid(os.getuid()).pw_name
            print(json.dumps(recovery_code.status(Path("/"), name)))
        except (KeyError, ValueError):
            die("Choose a regular account.")
        return
    if argv == ["sharing-status"]:
        import sharing
        try:
            print(json.dumps(sharing.status()))
        except (OSError, ValueError, subprocess.SubprocessError):
            die("Sharing could not be checked. Try again.")
        return
    if os.geteuid() != 0:
        die("This command needs administrator permission. Run it through Settings, or use "
            "'pkexec /usr/local/lib/starchaser/starchaser-admin' followed by the command and its arguments.")
    if cmd in SNAPSHOT_REFUSED and started_from_snapshot():
        die(SNAPSHOT_START)
    if cmd == "firmware":
        import firmware
        try:
            if len(argv) != 2:
                raise ValueError("Choose a firmware update or refresh.")
            if argv[1] != "refresh":
                stamp_software_grant_after_password()
            print(json.dumps(firmware.refresh() if argv[1] == "refresh" else firmware.install(argv[1])))
        except (ValueError, OSError, subprocess.SubprocessError) as error:
            die(str(error) if isinstance(error, ValueError) else "Firmware could not be updated. Keep the computer plugged in and check again.")
        return
    if cmd in ("recovery-start", "recovery-sizes"):
        import rescue
        if len(argv) != 1:
            die("This recovery action takes no arguments.")
        try:
            if cmd == "recovery-sizes":
                result = rescue.snapshot_sizes()
            else:
                entry = Path('/boot/loader/entries/starchaser-recovery.conf')
                if not entry.is_file() or entry.is_symlink():
                    raise ValueError("Independent recovery isn't installed. Start Recovery from your USB stick.")
                rescue.checked(['bootctl', 'set-oneshot', 'starchaser-recovery.conf'])
                rescue.checked(['systemctl', 'reboot'])
                result = {'ok': True}
            print(json.dumps(result))
        except (ValueError, OSError) as error:
            die(str(error))
        return
    if cmd == "drive-unlock":
        import drive_unlock
        try:
            if len(argv) != 2:
                raise ValueError("Choose a drive unlock action.")
            payload = json.loads(sys.stdin.read(16385))
            if not isinstance(payload, dict):
                raise ValueError("Enter the drive unlock details.")
            result = drive_unlock.renew_sheet(payload, account_caller()) if argv[1] == "sheet" else drive_unlock.change(argv[1], payload, restart_root=Path('/'))
            drive_unlock.record_boot()
            print(json.dumps(result))
        except (ValueError, OSError, subprocess.SubprocessError) as error:
            die(str(error) if type(error) is ValueError else "Drive unlock could not be changed. Check the current drive key and try again.")
        return
    if cmd == "hardware-restart":
        import hardware
        try:
            if len(argv) != 2:
                raise ValueError("Choose one device to restart.")
            print(json.dumps(hardware.restart(argv[1])))
        except (ValueError, OSError, subprocess.SubprocessError) as error:
            die(str(error) if isinstance(error, ValueError) else "The device could not restart. Try again.")
        return
    if cmd == "hardware-fix":
        import hardware
        try:
            if len(argv) != 2:
                raise ValueError("Choose one hardware item to fix.")
            print(json.dumps(hardware.fix(argv[1])))
        except (ValueError, OSError, subprocess.SubprocessError) as error:
            die(str(error) if isinstance(error, ValueError) else "Hardware support could not be set up. Try again.")
        return
    if cmd in ("sharing-start", "sharing-stop"):
        import sharing
        try:
            print(json.dumps(sharing.change(sys.modules[__name__], argv, account_caller(), sys.stdin)))
        except (ValueError, OSError, subprocess.SubprocessError) as error:
            die(str(error) if isinstance(error, ValueError) else "Sharing could not finish. Try Stop sharing, then start again.")
        return
    if cmd in ("user-password", "user-add", "user-remove", "user-reset-keyring", "user-administrator"):
        try:
            print(json.dumps(user_change(cmd, argv)))
        except ValueError as error:
            die(str(error))
        except OSError:
            die("The account change could not finish. Try again.")
        return
    if cmd in ("recovery-code-new", "recovery-code-use"):
        try:
            result = recovery_code_change(cmd, argv)
        except ValueError as error:
            die(str(error))
        except OSError:
            die("The recovery code could not be checked or saved. Try again.")
        print(json.dumps(result))
        sys.exit(0 if result["ok"] else 1)
    if cmd == "switch-to-package":
        return main_cmd(cmd, argv)                      # dry run must not repair or write any state
    fw.repair_readable_state()
    if cmd == "watchdog":
        # waits outside the lock, until the deadline Settings shows (read again each time: the screen and the undo
        # go by the same clock); decides inside the lock. argv[2], the timeout, is the fallback for a record
        # without a deadline.
        try:
            if len(argv) != 3:
                raise ValueError
            end = time.time() + float(argv[2])
        except ValueError:
            die("watchdog takes a change id and a number of seconds")
        while True:
            w = waiting()
            if not w or w.get("id") != argv[1]:
                # kept, gone back, or replaced by a newer change: checked again under the lock, since a replacement
                # takes over the record while it applies and puts this one back if that fails
                with locked():
                    w = waiting()
                if not w or w.get("id") != argv[1]:
                    return
            try:
                end = float(w.get("deadline") or end)
            except (TypeError, ValueError):
                pass
            left = end - time.time()
            if left <= 0:
                break
            time.sleep(min(left, 5))
        # going back can fail (nft busy, a rules file that won't load): the record stays (go_back), so try again a
        # few times; after that the restart check still puts the previous firewall back
        for _ in range(6):
            with locked():
                w = waiting()
                if not w or w.get("id") != argv[1]:
                    return
                # An extension can arrive after the outside-lock deadline read.
                if (w.get("deadline") or 0) > time.time():
                    subprocess.Popen([sys.executable, os.path.realpath(__file__), "watchdog", argv[1],
                                      str(w["deadline"] - time.time())], start_new_session=True,
                                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                    return
                err = go_back(w, "Not kept: went back by itself after the countdown")
                if not waiting():
                    refresh_stats_after_entry()        # the page says it went back now, not at the timer's turn
                    return
            print(f"starchaser-admin: going back failed, trying again: {err}", file=sys.stderr, flush=True)
            time.sleep(5)
        return
    if cmd == "firewall-stats":
        # the timer, every 60 seconds (every 10 while Settings > Firewall is open): reading counters needs no lock; its upkeep (zones, the outgoing hold,
        # OpenSnitch following the asker) changes shared state, so it runs only when no change is under way
        # (with the lock, the zone sets can be checked too: nothing is setting them at that moment)
        # fw.tick(): its reads are answered without starting a program where they can be (an idle desktop's budget)
        with try_locked() as got, fw.tick():
            if got:
                settle_restarted()
                settle_expired()
            loaded = fw.stats(zones_checked=got)
            if got:
                fw.maintain(loaded)
        return
    if cmd == "firewall-outgoing-hold" and len(argv) == 2 and argv[1] in ("started", "stopping", "stopped", "watch"):
        # OpenSnitch's own unit (fw.OSN_DROPIN), when it starts or stops: app/default Blocks hold new outgoing
        # connections while OpenSnitch isn't checking them. No lock: an Apply holds it while it restarts OpenSnitch
        # and waits for the restart, which waits for this. Putting the hold in place is always safe; it is only
        # taken down here when OpenSnitch is checking again, and Apply and the timer settle it under the lock.
        # "stopping" is the unit's ExecStop, run before OpenSnitch is signaled: the hold goes in while OpenSnitch is
        # still checking, so there is no moment between its queue going away and the hold coming up
        if argv[1] == "watch":
            time.sleep(15)                              # detached from the service's restart
            for _ in range(12):
                with try_locked() as got:
                    if got:
                        fw.outblock_sync()
                        fw.stats()
                        return
                time.sleep(5)                          # an Apply may still hold the lock during the restart
            return
        # A checker that cannot start pauses the app firewall instead of holding every new connection for good
        # (fw.CHECKER_PAUSED): "stopped" counts the unit's failed runs, "started" ends the pause once a new try is
        # checking connections
        paused_now = False
        if argv[1] == "stopped":
            was = fw.checker_paused()
            paused_now = fw.checker_stopped(os.environ.get("SERVICE_RESULT", "")) and not was
        elif argv[1] == "started" and fw.checker_paused():
            deadline = time.time() + 15
            while not fw.osn_intercepting() and fw.osn_alive() and time.time() < deadline:
                time.sleep(0.25)
            if fw.osn_intercepting():
                fw.checker_resume()
        fw.outblock_sync(wait=15 if argv[1] == "started" else 0, stopping=argv[1] == "stopping")
        if paused_now:                                 # Settings and the notice read the check's answer: make one now
            subprocess.run(["systemctl", "--no-block", "start", "starchaser-firewall-stats.service"],
                           stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if argv[1] == "stopped" and fw.OUTGOING_DOWN.exists():
            subprocess.Popen([sys.executable, os.path.realpath(__file__), "firewall-outgoing-hold", "watch"],
                             start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                             stderr=subprocess.DEVNULL)
        if argv[1] == "stopping":
            # an upkeep already part-way through (it saw OpenSnitch checking and no hold) could take the hold just
            # loaded down again (it asks whether the unit is stopping just before; the gap is a few nft calls).
            # OpenSnitch keeps checking until this exits, so: wait for that upkeep to finish (the lock, at most a
            # second: an Apply holding it, restarting OpenSnitch, keeps the upkeep out anyway, and an upkeep past
            # its check is done within that), then make sure the hold is in place. An upkeep after this sees the
            # unit stopping and leaves the hold alone.
            deadline = time.time() + 1
            while True:
                with try_locked() as got:
                    if got or time.time() >= deadline:
                        fw.outblock_sync(stopping=True)
                        return
                time.sleep(0.1)
        return
    if cmd in ("welcome-session",) or not cmd.startswith(("firewall-", "welcome-")):
        return main_cmd(cmd, argv)
    prepared = None
    if cmd in ("firewall-commit", "firewall-commit-quick") and len(argv) >= 2:
        try:
            prepared = (read_policy_input(argv[1]), read_policy_input(opt(argv, "--base")) if opt(argv, "--base") else None)
        except (OSError, ValueError) as e:
            die(f"can't read the policy: {e}")
    if cmd in firewall_grants.QUICK + firewall_grants.OTHER and sitting_user() >= 0:
        try:
            _firewall_authorization = firewall_grants.consume(os.getpid(), sitting_user(), argv, prepared)
        except (OSError, ValueError, KeyError, TypeError, StopIteration) as error:
            die(str(error))
    with locked():                                     # every other firewall change (and welcome-apply)
        if cmd not in ("firewall-boot-check", "firewall-boot-load"):
            settle_restarted()
        main_cmd(cmd, argv, prepared=prepared)


# commands that can switch a network to or from Home (Trusted) or put an earlier policy back
HOME_CHANGE_COMMANDS = ("firewall-commit", "firewall-commit-quick", "firewall-mark-network", "firewall-confirm",
                        "firewall-revert", "firewall-rollback", "firewall-rollback-quick", "firewall-extend")


def main_cmd(cmd: str, argv: list, prepared=None) -> None:
    try:
        _main_cmd(cmd, argv, prepared)
    finally:
        if cmd in HOME_CHANGE_COMMANDS:
            home_addresses()


def _main_cmd(cmd: str, argv: list, prepared=None) -> None:
    if cmd == "switch-to-package":
        import pkgrepo
        try:
            args = pkgrepo.switch_parser().parse_args(argv[1:])
            if not args.user:
                raise ValueError("Name the account that asked for this switch with --user.")
            # its password opens the 15-minute window too, and the full update it runs ends with a fresh one, so the
            # Update now pressed right after doesn't ask again (QA 20261108-1446 004)
            if not args.dry_run:
                stamp_software_grant_after_password()
            pkgrepo.run_switch(args)
            if not args.dry_run:
                stamp_software_grant()
        except (OSError, ValueError, subprocess.CalledProcessError) as e:
            # read in the terminal Settings opens for the switch (starchaser switch to package passes it on): plain
            # words, not the {"ok": false, ...} that pages reading this helper's output get
            sys.exit(f"The switch didn't finish. {e}")
    elif cmd == "firewall-password-mode" and len(argv) == 2:
        print(json.dumps(password_mode(argv)))
    elif cmd in ("firewall-commit", "firewall-commit-quick") and len(argv) >= 2:
        timeout_opt(argv)
        if prepared is None:
            try:
                prepared = (read_policy_input(argv[1]), read_policy_input(opt(argv, "--base")) if opt(argv, "--base") else None)
            except (OSError, ValueError) as e:
                die(f"can't read the policy: {e}")
        raw, base = prepared
        sit = Sitting(cmd)
        quick_check(cmd, raw)
        commit(raw, timeout_opt(argv), opt(argv, "--summary"), base=base, force_keep="--force-keep" in argv)
        end_once(opt(argv, "--end-once"))
        sit.done()
    elif cmd in ("firewall-rollback", "firewall-rollback-quick") and len(argv) >= 2:
        timeout_opt(argv)                              # (a bad --timeout is refused before anything is read)
        if not fw.HISTORY_ID.fullmatch(argv[1]):
            die("bad history id")
        try:
            snap = json.loads((fw.HISTORY / f"{argv[1]}.json").read_text())
        except (OSError, ValueError):
            die("no such commit")
        if snap.get("runtimeOnly"):
            die("This entry is for reference and cannot be restored from History.")
        # Settings says what going back does ("Went back to how it was on Oct 7, 9:55 PM. That turned off Remote login.",
        # "Undid the change that turned on Remote login."); the command line gets the snapshot id
        sit = Sitting(cmd)
        quick_check(cmd, snap["policy"])
        commit(snap["policy"], timeout_opt(argv), opt(argv, "--summary") or f"Rolled back to {argv[1]}")
        sit.done()
    elif cmd == "firewall-confirm":
        w = waiting()
        if not w:
            print(json.dumps({"ok": False, "settled": True, "errors": SETTLED}))
            sys.exit(1)
        if len(argv) > 1 and w.get("id") != argv[1]:
            die(REPLACED)
        clear_waiting()
        if w and not current_policy().get("enabled"):     # kept Off: the unit was only held on for the countdown
            run("systemctl", "disable", "starchaser-firewall.service")
        # a fresh check once kept, so the line under the title stops saying "making sure the new settings are
        # working…" now rather than at the timer's next turn (the countdown's first second already passed: Keep
        # is armed only after it, so the check lands more than a second after the change's History entry)
        refresh_stats()
        print(json.dumps({"ok": True, "errors": ""}))
    elif cmd == "firewall-extend":
        w = waiting()
        if not w:
            die(SETTLED)
        if len(argv) != 2 or w.get("id") != argv[1]:
            die(REPLACED)
        deadline = w.get("deadline")
        if not isinstance(deadline, (int, float)) or deadline <= time.time():
            die(SETTLED)
        w["deadline"] = deadline + 60
        save_waiting(w)
        print(json.dumps({"ok": True, "errors": "", "deadline": w["deadline"]}))
    elif cmd == "firewall-revert":
        w = waiting()
        if not w:
            die(SETTLED)
        if len(argv) > 1 and w.get("id") != argv[1]:
            die(REPLACED)
        err = go_back(w, "Reverted")
        if not waiting():                              # went back: the line under the title says so now, not after
            refresh_stats_after_entry()                # 13 s of "making sure the new settings are working…"
        print(json.dumps({"ok": not err, "errors": err}))
    elif cmd == "firewall-boot-check":
        boot_check()
    elif cmd == "firewall-boot-load":
        # the unit's start, before the network: never leaves the computer open (firewall.py boot_load); exit code 1
        # only when nothing at all could be loaded, so the unit's own last resort runs
        how = fw.boot_load()
        print(f"starchaser-admin: firewall at start-up: {how}", file=sys.stderr if how != "saved" else sys.stdout, flush=True)
        if how == "failed":
            sys.exit(1)
    elif cmd == "firewall-default-on":
        default_on()
    elif cmd == "firewall-upgrade":
        upgrade_rules()
    elif cmd == "firewall-restart-outgoing" and len(argv) == 1:
        restart_outgoing()
    elif cmd == "firewall-reload":
        reload_rules(reconnect="--reconnect" in argv[1:], repair="--repair" in argv[1:])
        Sitting(cmd).done()
    elif cmd == "firewall-zones-refresh":
        _, err = refresh_installed_basic_rules(boot="--boot" in argv[1:])
        if err:
            print(f"starchaser-admin: installed app rules weren't updated: {err}", file=sys.stderr, flush=True)
        error = fw.refresh_zones(boot="--boot" in argv[1:])
        if "--boot" not in argv[1:]:
            home_addresses()      # a reinstalled or restored profile for a Home network gets the real address too
        if error:
            die(error)
    elif cmd == "route-guard-refresh" and len(argv) == 1:
        import route_guard  # beside this file, root-owned like the engine
        res = route_guard.refresh()
        print(json.dumps({k: res[k] for k in ("ok", "errors", "added", "removed")}))
    elif cmd == "route-guard-watch" and len(argv) == 1:
        import route_guard
        route_guard.watch()
    elif ((cmd in ("firewall-public-pause-on", "firewall-public-pause-off") and len(argv) == 1)
          or (cmd == "firewall-public-pause-off" and argv[1:] == ["--undo"])):
        # Decision #18 combines marking Public and pausing, with no timed connection check.
        # 50-starchaser-public-pause.rules lets an active local wheel member start it without a password.
        # Ending it uses auth_admin unless the optional all-changes sitting grant covers it.
        result = (public_pause_change(False, undo_only=True) if argv[1:] == ["--undo"]
                  else public_pause_change(cmd == "firewall-public-pause-on"))
        refresh_stats()
        print(json.dumps(result))
    elif cmd == "firewall-child-requests" and len(argv) == 2 and argv[1].isdigit():
        uid = int(argv[1])
        policy = current_policy()
        if not any(c.get("uid") == uid for c in policy.get("children", [])): die("Choose an account with saved child controls.")
        import firewall_requests
        print(json.dumps({"ok": True, "uid": uid, "requests": [r for r in firewall_requests.pending(policy) if r['uid'] == uid]}))
    elif cmd == "firewall-child-allow" and len(argv) == 3 and argv[1].isdigit():
        import firewall_requests
        uid, app = int(argv[1]), argv[2]
        policy = current_policy()
        request = next((r for r in firewall_requests.pending(policy) if r['uid'] == uid and r['app'] == app), None)
        if request is None: die("This app request is no longer waiting. Nothing changed.")
        after = json.loads(json.dumps(policy))
        rule = {"id": "child-" + uuid.uuid4().hex, "name": request['name'] + " approved by a parent", "enabled": True,
                "dir": "out", "action": "allow", "app": app, "service": "any", "zones": ["any"], "peers": ["any"],
                "user": str(uid), "log": False, "managed": "child"}
        after['rules'].insert(0, rule)
        commit(after, 30, request['child'] + " can use " + request['name'] + ".", base=policy)
        refresh_stats()
    elif cmd == "firewall-allow-app-temporary" and len(argv) == 4:
        if not argv[3].isdigit(): die("Choose a temporary access duration.")
        err = fw.allow_app_once(argv[1], argv[2], int(argv[3]), actor=account_caller())
        if err: die(err)
        refresh_stats()
        print(json.dumps({"ok": True, "errors": "", "message": "Temporary app access saved; leaving this network ends it."}))
    elif cmd in ("firewall-allow-once", "firewall-revoke-once"):
        addr, proto, port, mins, iface = once_args(argv)
        actor = account_caller()
        err = (fw.allow_once(addr, proto, port, mins, iface, actor=actor) if cmd == "firewall-allow-once"
               else fw.revoke_once(addr, proto, port, iface, actor=actor))
        refresh_stats()
        print(json.dumps({"ok": not err, "errors": err, "publicPause": fw.public_pause_state()}))
        if not err:
            Sitting(cmd).done()
    elif cmd == "firewall-allow-always" and len(argv) >= 4 and argv[3].isdigit():
        zone, network = opt(argv, "--zone"), opt(argv, "--network")
        if any(a == "--network" or a.startswith("--network=") for a in argv) and not network:
            die("Choose a network for this permission; nothing was changed.")
        rest = [a for i, a in enumerate(argv) if i >= 4 and a not in ("--zone", "--network") and argv[i - 1] not in ("--zone", "--network")]
        allow_always(argv[1], argv[2], int(argv[3]), rest[0] if rest else "", rest[1] if len(rest) > 1 else "", zone, network)
        Sitting(cmd).done()
    elif cmd == "firewall-mark-network" and (len(argv) == 3 or (len(argv) == 4 and argv[3] == "--only-unmarked")):
        mark_network(argv[1], argv[2], only_unmarked=len(argv) == 4)
        if argv[2] == "trusted":
            Sitting(cmd).done()
    elif cmd == "firewall-forget-asked" and len(argv) == 2 and re.fullmatch(r"sc-asked-[a-z0-9-]+\.json", argv[1]):
        f = Path("/etc/opensnitchd/rules") / argv[1]
        # Older askers could save duplicate copies. Forget the same answer and scope together.
        try: target = json.loads(f.read_text())
        except (OSError, ValueError): target = None
        if target:
            signature = lambda r: (r.get('action'), r.get('operator'))
            for sibling in f.parent.glob('sc-asked-*.json'):
                try:
                    if not sibling.is_symlink() and sibling.stat().st_size <= 131072 and signature(json.loads(sibling.read_text())) == signature(target): sibling.unlink()
                except (OSError, ValueError): pass
        f.unlink(missing_ok=True)
        print(json.dumps({"ok": True, "errors": ""}))      # OpenSnitch notices the rule folder changed
        Sitting(cmd).done()
    elif cmd == "welcome-session":
        welcome_session()
    elif cmd == "welcome-apply" and len(argv) == 2:
        try:
            req = json.loads(Path(argv[1]).read_text())
        except (OSError, ValueError) as e:
            die(f"can't read the choices: {e}")
        print(json.dumps(welcome_apply(req)))
    elif cmd == "usb-setup":
        print(json.dumps(usb_setup()))
    elif cmd == "autoupdate-default" and len(argv) == 1:
        result = autoupdate_default()
        print(json.dumps(result))
        if not result["ok"]:
            sys.exit(1)
    elif cmd == "autoupdate-set" and len(argv) == 2:
        stamp_software_grant_after_password()
        result = autoupdate_set(argv[1])
        print(json.dumps(result))
        if not result["ok"]:
            sys.exit(1)
    elif cmd == "update-channel-set" and len(argv) == 2 and argv[1] in ("release", "testing"):
        stamp_software_grant_after_password()
        import pkgrepo
        change_update_channel(argv[1])
    elif cmd == "power-owner":
        import device_care
        if len(argv) != 2:
            die("Choose one owner for power modes.")
        try:
            print(json.dumps(device_care.set_power_owner(argv[1])))
        except (OSError, ValueError) as error:
            die(str(error))
    elif cmd == "battery-limit":
        import device_care
        if len(argv) != 3:
            die("Choose one battery and a charge limit.")
        try:
            print(json.dumps(device_care.set_charge_limit(argv[1], argv[2])))
        except (OSError, ValueError) as error:
            die(str(error))
    elif cmd == "thunderbolt-device":
        import thunderbolt
        try:
            print(json.dumps(thunderbolt.change(argv[1:])))
        except thunderbolt.ThunderboltError as e:
            die(str(e))
    elif cmd == "usb-device":
        print(json.dumps(usb_device(argv)))
    elif cmd == "usb-level" and len(argv) == 2 and argv[1] in ("relaxed", "strict", "off"):
        print(json.dumps(usb_level(argv[1])))
    elif cmd == "autologin" and len(argv) == 2 and argv[1] in ("on", "off"):
        print(json.dumps(autologin_set(argv[1] == "on")))
    elif cmd == "home-versions" and len(argv) == 2 and argv[1] in ("on", "off"):
        import recovery_health
        print(json.dumps(recovery_health.set_versions(argv[1] == "on")))
    elif cmd == "password-next-start" and len(argv) == 2 and argv[1] in ("on", "off", "check"):
        try:
            print(json.dumps(password_next_start(argv[1])))
        except OSError:
            die("The login screen couldn't be set to ask for your password. Nothing was changed.")
    elif cmd == "ssh" and len(argv) == 2 and argv[1] in ("on", "off"):
        print(json.dumps(ssh_set(argv[1] == "on")))
    elif cmd == "fleet-networks" and len(argv) == 3 and argv[1] in ("tailscale", "vpn") and argv[2] in ("on", "off"):
        fleet_networks_set(argv[1], argv[2] == "on")
    elif cmd == "fleet-ready" and all(UUID.fullmatch(u) for u in argv[1:]):
        with locked():
            print(json.dumps(fleet_ready(argv[1:])))
    elif cmd == "fleet-switches-on" and len(argv) == 1:
        with locked():
            print(json.dumps(fleet_switches_on()))
    elif cmd == "update-run" and len(argv) == 2:
        import updater
        updater.main(argv[1])
    elif cmd == "software-run" and len(argv) == 2:
        import software
        software.main(argv[1])
    elif cmd == "language" and len(argv) == 2:
        set_language(argv[1])
        print(json.dumps({"ok": True}))
    elif cmd == "printing-on" and len(argv) == 1:
        # Settings > Printers on a computer set up before printing support came (the setup and the desktop package
        # turn it on too): the socket only, never cups.service at boot
        if run("systemctl", "enable", "--now", "cups.socket").returncode:
            die("Printing could not be turned on. Install Starchaser updates in Settings > Updates, then try again.")
        print(json.dumps({"ok": True, "errors": ""}))
    elif cmd == "backup-folder" and len(argv) == 2:
        backup_folder(argv[1])
    elif cmd == "pacman-unlock":
        import updater
        state = updater.clear_stale_lock()              # checked here as root, and again as it's moved aside
        if state == "busy":
            die("Something is installing or updating right now, so the lock was left alone. Wait for it to finish.")
        print(json.dumps({"ok": True, "errors": "", "cleared": state == "stale"}))
    elif cmd == "tailscale-on":
        user = pwd_name(int(os.environ.get("PKEXEC_UID", "0")))
        steps = []
        if not shutil.which("tailscale"):
            import updater
            with updater.SystemChange("software") as change:
                # never between an update's steps (its AUR builds leave pacman's own lock free)
                if not updater.hold_run_lock():
                    print(json.dumps({"ok": False, "errors": LOCK_FAILED if updater.lock_unavailable else "An install or update is running. Try again when it's done.",
                                      "details": "starchaser run lock held"}))
                    sys.exit(1)
                # The package lists may already be newer than the installed packages (Software and Updates refresh them),
                # so install only the smallest safe set (targeted.py, the same check Software uses), and refuse when that
                # reaches a core piece of the system. No refresh here: the lists stay whatever they are.
                try:
                    import targeted
                    import tested_releases
                    plan = targeted.plan(str(tested_releases.PACMAN_SYNC.parent), ["tailscale"])
                except Exception as e:
                    print(json.dumps({"ok": False, "errors": "Settings can't check what Tailscale needs right now, so nothing was "
                                      "installed. Install the waiting updates in Settings > Updates, then try again.",
                                      "details": str(e)[-300:]}))
                    sys.exit(1)
                if plan["core"]:
                    print(json.dumps({"ok": False, "errors": "Tailscale needs part of a system update first (" + ", ".join(plan["core"])
                                      + "). Install the waiting updates in Settings > Updates, then try again.", "needsUpdate": True}))
                    sys.exit(1)
                if plan["missing"] and not plan["install"]:
                    print(json.dumps({"ok": False, "errors": tailscale_install_error("target not found"),
                                      "details": "missing: " + ", ".join(plan["missing"])}))
                    sys.exit(1)
                # tailscale by name (pacman adds what it needs as dependencies) and the installed packages that must update with it
                argv = ["pacman", "-S", "--needed", "--noconfirm", "--"] + ["tailscale"] + plan["upgrade"]
                try:
                    import tested_releases
                    tested_releases.guard_installer(argv)
                except (OSError, ValueError, subprocess.SubprocessError) as exc:
                    print(json.dumps({"ok": False, "errors": str(exc), "needsUpdate": True}))
                    sys.exit(1)
                r = subprocess.run(argv, capture_output=True, text=True)
                if r.returncode != 0:
                    print(json.dumps({"ok": False, "errors": tailscale_install_error(r.stdout + "\n" + r.stderr),
                                      "details": (r.stderr or r.stdout).strip()[-300:]}))
                    sys.exit(1)
                steps.append("installed")
                change.result = {"ok": True}

        res = tailscale_start(user, steps)
        print(json.dumps(res))
        if not res["ok"]:
            sys.exit(1)
    elif cmd == "tailscale-off":
        res = tailscale_stop()
        print(json.dumps(res))
        if not res["ok"]:
            sys.exit(1)
    elif cmd == "recovery-create":
        # "Remove it and continue" adds --clear-stale-lock: never part of the snapshot's name
        clear_stale = argv[-1] == "--clear-stale-lock" and len(argv) > 1
        words = argv[1:-1] if clear_stale else argv[1:]
        label = re.sub(r"[^\w .,:'()-]", "", " ".join(words))[:60] or "Snapshot you took"
        # never in the middle of an install or update: a snapshot taken halfway through a pacman transaction holds a
        # half-installed system, and going back to it restores that. Starchaser's run lock is held while it's taken
        # (no Starchaser run can start), and pacman's own lock is TAKEN (atomically) and held through snapper create,
        # so a `sudo pacman -S` typed in a terminal can't start in between either (checking the lock once left a
        # window of seconds: the snapper list and modify calls run before create).
        import updater
        if not updater.hold_run_lock():
            die(LOCK_FAILED if updater.lock_unavailable else "An install or update is running. Take the snapshot when it's done.")
        if clear_stale and updater.clear_stale_lock() == "busy":
            die("An install or update is running. Take the snapshot when it's done.")
        keep_hand_made(snaps())                     # before pacman's lock: nothing here needs it
        try:
            os.close(os.open(PACMAN_LOCK, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644))
        except FileExistsError:
            # a lock left by a run that never finished (a power cut): said plainly, and the page offers to clear it
            if updater.pacman_lock_state() == "stale":
                print(json.dumps({"ok": False, "lockStale": True, "errors":
                                  "An earlier install or update stopped partway (the power may have gone off) and left "
                                  "behind a note saying it's still running. No snapshot was taken. Nothing is running "
                                  "now, so it's safe to remove."}))
                sys.exit(1)
            die("An install or update is running. Take the snapshot when it's done.")
        try:
            # no cleanup rule: kept until you delete it (recovery-delete), as Settings > Recovery says
            r = subprocess.run(["snapper", "-c", "root", "create", "-t", "single", "-d", label,
                                "--userdata", "important=yes,starchaser=hand", "-p"], capture_output=True, text=True)
        finally:
            PACMAN_LOCK.unlink(missing_ok=True)     # only the lock this command took
        number = r.stdout.strip()
        if r.returncode == 0 and number.isdigit():
            scrub_lock(number)
        why = r.stderr.strip() or ("" if r.returncode == 0 else f"snapper stopped with exit code {r.returncode}")
        print(json.dumps({"ok": r.returncode == 0, "errors": why, "number": number}))
    elif cmd == "recovery-keep":                    # the desktop setup runs it, for snapshots kept by an older version
        keep_hand_made(snaps())
        print(json.dumps({"ok": True, "errors": ""}))
    elif cmd in ("recovery-undo", "recovery-go-back-undo") and len(argv) in (2, 3) and argv[1].isdigit() and argv[2:] in ([], ["--clear-stale-lock"]):
        # recovery-go-back-undo is the same go-back; its own name only makes the password box say "undo the last
        # go-back" when that is what the person chose in Settings
        recovery_undo(int(argv[1]), clear_stale=len(argv) == 3)
    elif cmd in ("recovery-update-undo", "recovery-update-undo-at") and len(argv) == 2 and argv[1].isdigit():
        recovery_update_undo(int(argv[1]), historical=cmd.endswith('-at'))
    elif cmd == "recovery-boot" and argv[1:] in ([], ["--clear-stale-lock"]):
        recovery_boot(clear_stale=len(argv) == 2)
    elif cmd == "recovery-delete" and len(argv) == 2 and argv[1].isdigit():
        recovery_delete(int(argv[1]))
    elif cmd == "recovery-snapshot-go-back" and len(argv) == 2 and argv[1].isdigit():
        import bootsnap
        import updater
        try:
            with updater.SystemChange("undo"):
                manager = bootsnap.BootSnapshots()
                with (manager.snapdir / '.go-back.lock').open('w') as lock:
                    fcntl.flock(lock, fcntl.LOCK_EX)
                    answer = manager.swap_from_session(int(argv[1]))
        except (ValueError, RuntimeError, subprocess.SubprocessError) as error:
            die(str(error))
        except OSError as error:
            die(f"Going back couldn't be set up: {error.strerror or error}. Nothing was changed.")
        print(json.dumps(answer))
    elif cmd == "hostname" and len(argv) == 2:
        name = argv[1]
        if not re.fullmatch(r"[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?", name):
            die("use lowercase letters, numbers and dashes (no dash at the start or end), up to 63 characters")
        r = run("hostnamectl", "set-hostname", name)
        err = r.stderr.strip() if r.returncode else ""
        if r.returncode == 0:
            try:
                hosts = HOSTS.read_text()
                line = f"127.0.1.1\t{name}.localdomain {name}"
                hosts, n = re.subn(r"(?m)^127\.0\.1\.1\s+.*$", line, hosts)
                if not n:                           # no line for this computer's own name yet: add one
                    hosts = hosts + ("" if hosts.endswith("\n") or not hosts else "\n") + line + "\n"
                fw.write_atomic(HOSTS, hosts, 0o644)   # whole or not at all: a half file breaks name lookups
            except OSError as e:
                err = f"the name changed, but /etc/hosts couldn't be updated: {e.strerror or e}"
            # the fleet finds this computer by what Avahi announces: Avahi keeps the old name until it restarts, and
            # each account's link announcer (starchaser link daemon) publishes again, with the new name, when its
            # publisher exits with it. Best-effort: the rename itself is done either way
            run("systemctl", "try-restart", "avahi-daemon.service")
        print(json.dumps({"ok": not err, "errors": err}))
    elif cmd == "":
        die("No command given. Run '/usr/local/lib/starchaser/starchaser-admin --help' to see them.")
    else:                                             # a known command with missing or invalid details
        # a value that simply isn't one of the allowed ones names them (the help points terminal callers here);
        # the Settings wording stays for a request that is missing or short
        takes = {"usb-level": "relaxed, strict or off", "ssh": "on or off",
                 "update-channel-set": "release or testing",
                 "recovery-undo": "the number of the snapshot to go back to",
                 "recovery-go-back-undo": "the number of the snapshot to go back to",
                 "recovery-update-undo": "the number of the snapshot to undo",
                 "recovery-delete": "the number of the snapshot to delete",
                 "recovery-snapshot-go-back": "the number of the snapshot this computer started from"}
        if cmd in takes and len(argv) > 1:
            die(f"{cmd} takes {takes[cmd]}. Nothing was changed.")
        die("Nothing was changed: Settings sent an incomplete request. Close Settings, open it again and retry. "
            "(From a terminal: run '/usr/local/lib/starchaser/starchaser-admin --help' for what each command takes.)")


if __name__ == "__main__":
    main(sys.argv[1:])
