#!/usr/bin/env python3
# summary: Use system desktop defaults, with backups and Undo.
"""starchaser defaults: Starchaser's settings come from the system copy; your own files in ~/.config win.

  starchaser defaults status          which of Starchaser's files this account still keeps its own copies of
  starchaser defaults apply --dry-run show what moving to the system copy would change, without changing anything
  starchaser defaults apply           move: copies that match a Starchaser default are removed (the system copy is
                                      used instead), files you changed are kept and stay in use. Everything is
                                      backed up first. With the desktop running, it happens at your next sign-in
                                      (--now: right away).
  starchaser defaults undo [ID]       put back what the last move (or move ID) changed; a file you changed since
                                      is kept
  starchaser defaults last [--json]   the last move, and whether it can still be undone (Settings > Updates)
  starchaser defaults auto            what each sign-in runs before the desktop starts: the move, once per account,
                                      for the groups that passed their test-VM checks (testing-channel computers
                                      first; the main channel once the version that carries it is promoted there).
                                      A move that fails is put back and said once.
  starchaser defaults notice          show the result of that move once (with Undo), when the desktop is up
  starchaser defaults init            a new account: write the small ~/.config/hypr/hyprland.lua that loads
                                      Starchaser's Hyprland settings (exit 3: this account has its own full copy)
  starchaser defaults preset         switch on Starchaser's services for an account that was never set up (no other)
  starchaser defaults features       new features an update brought, still off: they wait for your yes
                                      (features on NAME|all turns one on; features dismiss NAME|all leaves it off)
  starchaser defaults path FILE       the file in use for config/FILE (e.g. hypr/scripts/volume.sh): your own copy
                                      in ~/.config when there is one, else Starchaser's

Your own Hyprland settings go in ~/.config/hypr/user.lua: it is loaded last and never changed by Starchaser.
Backups and reports: ~/.local/state/starchaser/migrations/.
"""
import fcntl
import hashlib
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams, usage_error  # noqa: E402
from starchaser_system_defaults import ROOT, config_file, home_variants, loader_text, personal_dir, read_loader  # noqa: E402

PROG = "starchaser defaults"
COMMANDS = ("status", "apply", "undo", "last", "auto", "notice", "init", "path", "preset", "features")
HOME = Path.home()
STATE = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser"
MIGRATIONS = STATE / "migrations"
MARKER = STATE / "system-defaults.json"
PENDING = STATE / "system-defaults.pending"
NOTICE = STATE / "system-defaults.notice"
PACMAN_CONF = Path("/etc/pacman.conf")
# the person's own Hyprland settings: no move, undo or rollback ever writes or removes it, whatever a list says
NEVER = (".config/hypr/user.lua",)
DATA = ROOT / "data/system-defaults"


def write_atomic(path: Path, data: bytes, mode: int = 0o644) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    try:
        with open(tmp, "wb") as f:
            f.write(data)
            f.flush()
            os.fsync(f.fileno())
        os.chmod(tmp, mode)
        os.replace(tmp, path)
    finally:
        tmp.unlink(missing_ok=True)


def write_json(path: Path, data) -> None:
    write_atomic(path, (json.dumps(data, indent=1) + "\n").encode(), 0o600)


def sha256(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 16), b""):
            h.update(block)
    return h.hexdigest()


def shown(path: Path) -> str:
    try:
        return "~/" + str(path.relative_to(HOME))
    except ValueError:
        return str(path)


# ---------------------------------------------------------------- what a home file is

def unsafe_parent(path: Path):
    """Why a file's folders can't be changed safely, or None: every folder between the home folder and the file must
    be a real folder of this account, on the home folder's drive (a link there may lead into a dotfile manager's tree,
    another drive may be a backup)."""
    home_dev = HOME.stat().st_dev
    if not path.is_relative_to(HOME):
        return f"{shown(path)} is outside your home folder"   # a custom XDG folder elsewhere: reported, never changed
    for parent in reversed(path.relative_to(HOME).parents[:-1]):
        p = HOME / parent
        try:
            st = p.lstat()
        except FileNotFoundError:
            return None
        if stat.S_ISLNK(st.st_mode):
            return f"{shown(p)} is a link"
        if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid():
            return f"{shown(p)} isn't a folder of yours"
        if st.st_dev != home_dev:
            return f"{shown(p)} is on another drive"
    return None


def classify(path: Path, known: set, executable: bool = False) -> dict:
    """{state, why, ...}: absent, default (byte for byte a version Starchaser shipped), loader, changed, or kept for
    another reason (a link, a hard link, someone else's file, a folder on another drive)."""
    try:
        st = path.lstat()
    except FileNotFoundError:
        return {"state": "absent"}
    why = unsafe_parent(path)
    if why:
        return {"state": "kept", "why": why}
    if stat.S_ISLNK(st.st_mode):
        return {"state": "kept", "why": "it is a link"}
    if not stat.S_ISREG(st.st_mode):
        return {"state": "kept", "why": "it isn't a plain file"}
    if st.st_uid != os.getuid():
        return {"state": "kept", "why": "it belongs to another account"}
    if st.st_nlink > 1:
        return {"state": "kept", "why": "it has another name too (a hard link)"}
    info = {"sha256": sha256(path), "mode": stat.S_IMODE(st.st_mode), "mtime_ns": st.st_mtime_ns, "inode": st.st_ino, "size": st.st_size}
    if info["sha256"] in known:
        # the owner's execute bit is the one that matters (group and others follow the account's umask)
        if bool(info["mode"] & 0o100) != executable:
            return dict(info, state="changed", why="its permissions were changed")
        return dict(info, state="default")
    return dict(info, state="changed", why="you changed it")


def same_as_planned(path: Path, before: dict) -> bool:
    """Nothing changed the file between the plan and now (an editor saving it, a theme writing it)."""
    try:
        st = path.lstat()
    except FileNotFoundError:
        return False
    # Older numbered-migration journals omitted identity fields. Without them
    # we cannot prove the file is unchanged, so Undo keeps it conservatively.
    return (stat.S_ISREG(st.st_mode) and st.st_ino == before.get("inode") and st.st_mtime_ns == before["mtime_ns"]
            and st.st_size == before.get("size") and sha256(path) == before["sha256"])


# ---------------------------------------------------------------- the plan

class Plan:
    def __init__(self):
        self.groups = []        # (id, name, [(word, path, why)]) for the report
        self.actions = []       # {"group", "path", "action": "remove"|"loader", "before": classify(...)}
        self.system = set()     # groups that use Starchaser's system copy already
        self.deferred = []

    def group(self, gid, name):
        lines = []
        self.groups.append((gid, name, lines))
        return lines


def load_data():
    manifest = json.loads((DATA / "manifest.json").read_text())
    known = {k: set(v) for k, v in json.loads((DATA / "known-defaults.json").read_text())["files"].items()}
    return manifest, known


def known_for(item, known, root: Path) -> set:
    out = set(known.get(item["home"], ()))
    current = root / item["system"]
    if current.is_file():
        out.add(sha256(current))         # the version this Starchaser ships, even before the list is regenerated
    return out


def default_apps(path: Path) -> dict:
    """{file type: apps} from a mimeapps list's [Default Applications] ({} when it is missing or can't be read)."""
    out, section = {}, ""
    try:
        text = path.read_text(errors="replace")
    except OSError:
        return out
    for line in text.splitlines():
        line = line.strip()
        if line.startswith("["):
            section = line
        elif section == "[Default Applications]" and "=" in line and not line.startswith("#"):
            key, value = line.split("=", 1)
            out[key.strip()] = value.strip()
    return out


def still_needed(item):
    """Why a copy that matches a default has to stay, or None. The default-apps list in ~/.config is read before your
    other default-apps lists (~/.config/mimeapps.list and the older ones in ~/.local/share/applications), so it hides
    the apps they name; without the copy those apps would open those files."""
    mine = default_apps(HOME / item["home"]) if item.get("yields_to") else {}
    for rel in item.get("yields_to", []):
        theirs = default_apps(HOME / rel)
        hidden = [k for k in mine if k in theirs and theirs[k] != mine[k]]
        if hidden:
            return (f"{shown(HOME / rel)} names other apps for {len(hidden)} file type"
                    f"{'s' if len(hidden) != 1 else ''}, which this copy keeps in front of them")
    return None


def switch_links(item, path: Path):
    """(link, what it names) for each link that switches a user service on (<target>.wants/<unit>) and exists."""
    out = []
    for target in item.get("wanted_by", []):
        link = path.parent / f"{target}.wants" / path.name
        if os.path.islink(link):
            out.append((link, os.readlink(link)))
    return out


def ours(link: Path, named: str, path: Path) -> bool:
    """The link names this home copy the way setup (../unit) or systemctl enable (its full path) wrote it."""
    return named in (f"../{path.name}", str(path)) and not unsafe_parent(link)


def unknown_links(item, path: Path):
    """Links that lead to this home copy some other way: moving it would leave them pointing at nothing."""
    out = []
    for link, named in switch_links(item, path):
        if not ours(link, named, path) and os.path.realpath(link) == os.path.realpath(path):
            out.append(link)
    return out


def plan_links(plan, lines, gid, item, path: Path, replacement: Path) -> None:
    """A user service stays switched on: its link is pointed at the system copy in the same move, after the copy
    is removed."""
    for link, named in switch_links(item, path):
        if ours(link, named, path):
            st = link.lstat()
            plan.actions.append({"group": gid, "path": str(link), "action": "relink", "unit": str(path), "target": str(replacement),
                                 "before": {"link": named, "inode": st.st_ino, "mtime_ns": st.st_mtime_ns}})
            lines.append(("replace", link, "now names Starchaser's copy, so the service stays switched on"))


def same_link(path: Path, before: dict) -> bool:
    try:
        st = path.lstat()
        return stat.S_ISLNK(st.st_mode) and st.st_ino == before["inode"] and os.readlink(path) == before["link"]
    except OSError:
        return False


def write_link(path: Path, named: str, mtime_ns=None) -> None:
    tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    tmp.unlink(missing_ok=True)
    os.symlink(named, tmp)
    if mtime_ns is not None:
        os.utime(tmp, ns=(mtime_ns, mtime_ns), follow_symlinks=False)
    os.replace(tmp, path)


def tell_systemd(journal: dict) -> None:
    """After a move or undo of user services: the user manager reads its unit files again (where one runs)."""
    if any(e.get("group") == "user-services" and e["state"] in ("done", "restored") for e in journal["entries"]):
        try:
            subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True, timeout=60)
        except (OSError, subprocess.TimeoutExpired):
            pass


def named_tools(spec) -> dict:
    """{tool: the file that names it by its ~/.local/bin path}: registrations written for other programs (agent hooks,
    a fleet device's forced command, service drop-ins, your own Hyprland lines) that need the link to stay."""
    out = {}
    for pattern in spec.get("named_in", []):
        for f in sorted(HOME.glob(pattern)):
            try:
                text = f.read_text(errors="replace") if f.is_file() else ""
            except OSError:
                continue
            for name in re.findall(r"\.local/bin/([\w.@+-]+)", text):
                out.setdefault(name, f)
    return out


def plan_links_folder(plan, lines, gid, spec, root) -> None:
    """Links to Starchaser's tools (~/.local/bin/<tool> -> <Starchaser>/bin/<tool>): removed where the package's own
    link (/usr/bin/<tool>) starts the same file, so the tool is still found by name. Your own programs, links to
    anything else, and a link something still names by its full path stay."""
    folder = HOME / spec["home"]
    if not folder.is_dir() or folder.is_symlink() or unsafe_parent(folder / "x"):
        return
    named = named_tools(spec)
    moved, kept = 0, 0
    for link in sorted(folder.iterdir()):
        name = link.name
        if not link.is_symlink() or name in spec.get("keep", []):
            continue
        target = os.readlink(link)
        ours = root / spec["system"] / name
        if target != str(ours):
            continue
        installed = Path(spec["installed"]) / name
        if os.path.realpath(installed) != os.path.realpath(ours) or not ours.is_file():
            kept += 1
            continue
        if name in named:
            lines.append(("keep", link, f"{shown(named[name])} names it"))
            continue
        st = link.lstat()
        plan.actions.append({"group": gid, "path": str(link), "action": "unlink",
                             "before": {"link": target, "inode": st.st_ino, "mtime_ns": st.st_mtime_ns}})
        moved += 1
    if moved:
        lines.append(("remove", folder, f"{moved} link{'s' if moved != 1 else ''} to Starchaser's tools: the same tools "
                                        f"are found in {spec['installed']}"))
    if kept:
        lines.append(("keep", folder, f"{kept} link{'s' if kept != 1 else ''} to tools {spec['installed']} doesn't have yet"))


def plan_files(plan, lines, gid, items, known, root, reason_kept=None):
    """Each file on its own: a copy that matches a Starchaser default is removed once Starchaser's copy is there."""
    for item, tree, path in [(i, t, p) for i in items for t, p in home_variants(i["home"])]:
        c = classify(path, known_for(item, known, root), item.get("executable", False))
        if c["state"] == "absent":
            continue
        if reason_kept:
            lines.append(("keep", path, reason_kept))
        elif c["state"] == "default" and tree == "active" and (item.get("wanted_by") or item.get("yields_to")):
            # the links and the other lists that decide this are only inventoried in the standard folder
            lines.append(("keep", path, "it is in your custom XDG folder, whose links and other lists aren't followed; both folders stay separate"))
        elif c["state"] == "default" and (needed := still_needed(item)):
            lines.append(("keep", path, needed))
        elif c["state"] == "default":
            replacement = Path(item["installed"]) if item.get("installed") else root / item["system"]
            odd = unknown_links(item, path)
            if odd:
                lines.append(("keep", path, f"{shown(odd[0])} switches it on in a way this can't follow"))
            elif replacement.is_file() and os.access(replacement, os.R_OK):
                plan.actions.append({"group": gid, "path": str(path), "action": "remove", "before": c})
                lines.append(("remove", path, "the same as a Starchaser default, so Starchaser's copy is used instead"))
                plan_links(plan, lines, gid, item, path, replacement)
            else:
                lines.append(("keep", path, "Starchaser's system copy isn't installed yet"))
        elif c["state"] == "changed":
            lines.append(("keep", path, c["why"] + ("; yours stays in use" if c["why"] == "you changed it" else "")))
        else:
            lines.append(("keep", path, c["why"]))


def plan_folder(plan, lines, gid, folder, known, root, reason_kept=None):
    """A folder used as a whole (the corner shaders): removed only when every file in it is a Starchaser default."""
    path = HOME / folder["home"]
    try:
        st = path.lstat()
    except FileNotFoundError:
        return
    if reason_kept:
        lines.append(("keep", path, reason_kept))
        return
    if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
        lines.append(("keep", path, "it is a link" if stat.S_ISLNK(st.st_mode) else "it isn't a folder"))
        return
    system = root / folder["system"]
    found = []
    for child in sorted(path.iterdir()):
        rel = f"{folder['home']}/{child.name}"
        system_file = system / child.name
        c = classify(child, set(known.get(rel, ())) | ({sha256(system_file)} if system_file.is_file() else set()))
        if c["state"] != "default":
            why = c.get("why", "it isn't one of Starchaser's") if rel in known else "it isn't one of Starchaser's files"
            lines.append(("keep", path, f"{child.name} in it: {why}; the whole folder stays in use"))
            return
        found.append((child, c))
    if not system.is_dir():
        lines.append(("keep", path, "Starchaser's system copy isn't installed yet"))
        return
    for child, c in found:
        plan.actions.append({"group": gid, "path": str(child), "action": "remove", "before": c})
    lines.append(("remove", path, "every file in it is a Starchaser default, so Starchaser's folder is used instead"))


def make_plan(only=None) -> Plan:
    """The plan for every ready group, or for the groups named in only."""
    manifest, known = load_data()
    plan = Plan()
    for g in manifest["groups"]:
        if g["status"] != "ready":
            plan.deferred.append(g["name"])
            continue
        if only is not None and g["id"] not in only:
            continue
        lines = plan.group(g["id"], g["name"])
        if g["id"] != "hyprland":
            plan_files(plan, lines, g["id"], g.get("files", []), known, ROOT)
            if g.get("links"):
                plan_links_folder(plan, lines, g["id"], g["links"], ROOT)
            for rel in g.get("personal", []):
                if os.path.lexists(HOME / rel):
                    lines.append(("never", HOME / rel, g.get("personal_why", "your own settings: never changed")))
            continue
        # Hyprland: the entry point decides. An edited one reads its own copies by their home paths, so everything it
        # may load stays; a Starchaser one becomes the small loader in the same move.
        entry = HOME / g["entry"]["home"]
        root, kept = ROOT, None
        found = None
        if entry.is_file() and not entry.is_symlink() and not unsafe_parent(entry):
            found = read_loader(entry.read_text(errors="replace"))
        if found:
            root = Path(found[0])
            if (root / g["entry"]["system"]).is_file():
                plan.system.add(g["id"])
                lines.append(("ok", entry, "already the small file that loads Starchaser's settings"))
            else:
                lines.append(("keep", entry, f"the folder it names ({found[0]}) is missing"))
                kept = "kept until hyprland.lua names a Starchaser folder that is there"
        else:
            c = classify(entry, known_for(g["entry"], known, ROOT))
            body = ROOT / g["entry"]["system"]
            if c["state"] == "absent":
                lines.append(("ok", entry, "Hyprland isn't set up on this account: nothing to move"))
                continue
            if c["state"] == "default" and body.is_file() and "STARCHASER_SYSTEM" in body.read_text(errors="replace"):
                plan.actions.append({"group": g["id"], "path": str(entry), "action": "loader", "before": c})
                lines.append(("replace", entry, "the same as a Starchaser default, so it becomes the small file that loads Starchaser's"))
            elif c["state"] == "default":
                lines.append(("keep", entry, "this Starchaser can't load its settings from the system copy yet"))
                kept = "kept with hyprland.lua"
            else:
                lines.append(("keep", entry, c["why"] + ("; it keeps working as it is" if c["state"] == "changed" else "")))
                kept = "kept for your own hyprland.lua, which may load it"
        plan_files(plan, lines, g["id"], g.get("files", []), known, root, kept)
        for folder in g.get("folders", []):
            plan_folder(plan, lines, g["id"], folder, known, root, kept)
        for rel in g.get("personal", []):
            if os.path.lexists(HOME / rel):
                lines.append(("never", HOME / rel, "your own settings: never changed"))
    plan.actions = [a for a in plan.actions if not never(Path(a["path"]))]
    return plan


def never(path: Path) -> bool:
    return any(path == HOME / rel for rel in NEVER)


def print_plan(plan: Plan, out=None) -> None:
    out = out or sys.stdout
    words = {"remove": "remove", "replace": "replace", "keep": "keep", "ok": "ok", "never": "keep"}
    for _, name, lines in plan.groups:
        print(name, file=out)
        if not lines:
            print("  nothing here on this account", file=out)
        for kind, path, why in lines:
            print(f"  {words[kind]:<8}{shown(path)}: {why}", file=out)
    if plan.deferred:
        print("Still copied into your home folder (not moved yet): " + "; ".join(plan.deferred), file=out)


# ---------------------------------------------------------------- locks, desktop, journal

def lock(path: Path, wait: float):
    path.parent.mkdir(parents=True, exist_ok=True)
    f = open(path, "w")
    end = time.monotonic() + wait
    while True:
        try:
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            return f
        except BlockingIOError:
            if time.monotonic() >= end:
                f.close()
                return None
            time.sleep(0.2)


def desktop_running() -> bool:
    if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
        return True
    for proc in Path("/proc").iterdir():
        if not proc.name.isdigit():
            continue
        try:
            if proc.stat().st_uid == os.getuid() and (proc / "comm").read_text().strip() == "Hyprland":
                return True
        except OSError:
            continue
    return False


def journals():
    out = []
    if MIGRATIONS.is_dir():
        for d in sorted(MIGRATIONS.iterdir()):
            try:
                out.append((d, json.loads((d / "journal.json").read_text())))
            except (OSError, ValueError):
                continue
    return out


def read_marker() -> dict:
    try:
        marker = json.loads(MARKER.read_text())
    except (OSError, ValueError):
        marker = {}
    marker = marker if isinstance(marker, dict) else {}
    for key in ("groups", "automatic"):
        if not isinstance(marker.get(key), dict):
            marker[key] = {}
    return marker


def set_marker(tx_id, moved, undone=False, automatic=None) -> None:
    """groups: what uses the system copy, by the move that did it. automatic: each group the sign-in move has
    tried, with how it went; it is tried once per account, so an undo (or a failure) is never redone by itself."""
    marker = read_marker()
    groups = marker["groups"]
    if undone:
        groups = {g: v for g, v in groups.items() if v.get("transaction") != tx_id}
        for v in marker["automatic"].values():
            if v.get("transaction") == tx_id and v.get("result") == "moved":
                v["result"] = "undone"
    else:
        for g in moved:
            groups.setdefault(g, {"transaction": tx_id, "at": time.strftime("%Y-%m-%dT%H:%M:%S")})
    marker["groups"] = groups
    marker["automatic"].update(automatic or {})
    write_json(MARKER, {"schema": 1, "groups": groups, "automatic": marker["automatic"]})


# ---------------------------------------------------------------- apply

class BackupFailed(Exception):
    pass


def take_locks():
    """(own lock, refresh lock) or None: one move at a time, and never while the user refresh copies into the same
    folders."""
    own = lock(MIGRATIONS / ".lock", 5)
    if not own:
        return None
    runtime = os.environ.get("XDG_RUNTIME_DIR")
    refresh = lock(Path(runtime) / "starchaser-user-refresh.lock", 120) if runtime and Path(runtime).is_dir() else True
    if not refresh:
        own.close()
        return None
    return own, refresh


def run_move(plan: Plan, tx: Path, journal: dict):
    """Back up every planned file (each checked) and write the journal, then change the home folder, checking each
    file again just before. Returns (files changed, paths left as they were). BackupFailed: nothing was changed."""
    (tx / "files").mkdir(parents=True, exist_ok=True)
    os.chmod(tx, 0o700)
    waiting = {e["path"] for e in journal["entries"] if e["state"] == "backed-up"}
    for a in plan.actions:
        if a["path"] in waiting:
            continue
        path = Path(a["path"])
        if a["action"] in ("relink", "unlink"):   # nothing to copy: the journal keeps what the link named
            journal["entries"].append(dict(a, state="backed-up"))
            continue
        backup = tx / "files" / path.relative_to(HOME)
        backup.parent.mkdir(parents=True, exist_ok=True)
        try:
            shutil.copy2(path, backup, follow_symlinks=False)
            if sha256(backup) != a["before"]["sha256"]:
                raise OSError(0, "the backup doesn't match")
        except OSError as e:
            write_json(tx / "journal.json", journal)
            raise BackupFailed(f"couldn't back up {shown(path)} ({e.strerror})")
        journal["entries"].append(dict(a, backup=str(backup.relative_to(tx)), state="backed-up"))
    write_json(tx / "journal.json", journal)
    changed, skipped = 0, []
    loader_bytes = loader_text(ROOT).encode()
    for e in journal["entries"]:
        if e["state"] != "backed-up":
            continue
        path = Path(e["path"])
        if e["action"] == "unlink":
            if not same_link(path, e["before"]):
                e["state"] = "skipped"
                skipped.append(path)
            else:
                try:
                    path.unlink()
                    e["state"] = "done"
                    changed += 1
                except OSError as err:
                    e["state"], e["error"] = "failed", err.strerror
                    skipped.append(path)
            write_json(tx / "journal.json", journal)
            continue
        if e["action"] == "relink":
            unit_moved = any(u["path"] == e["unit"] and u["state"] == "done" for u in journal["entries"])
            if not unit_moved:
                e["state"] = "skipped"        # its copy stayed, so the link stays as it was
            elif not same_link(path, e["before"]):
                e["state"] = "skipped"
                skipped.append(path)
            else:
                try:
                    write_link(path, e["target"])
                    e["state"] = "done"
                    changed += 1
                except OSError as err:
                    e["state"], e["error"] = "failed", err.strerror
                    skipped.append(path)
            write_json(tx / "journal.json", journal)
            continue
        if never(path) or not same_as_planned(path, e["before"]):
            e["state"] = "skipped"
            skipped.append(path)
        else:
            try:
                if e["action"] == "remove":
                    path.unlink()
                else:
                    write_atomic(path, loader_bytes, 0o644)
                    e["after"] = hashlib.sha256(loader_bytes).hexdigest()
                e["state"] = "done"
                changed += 1
            except OSError as err:
                e["state"] = "failed"
                e["error"] = err.strerror
                skipped.append(path)
        write_json(tx / "journal.json", journal)
    # Hyprland's scripts, profiles and shaders folders when the move left them empty (never one with anything in it)
    for e in journal["entries"]:
        if e["state"] == "done" and e["action"] == "remove":
            d = Path(e["path"]).parent
            if d.parent == HOME / ".config/hypr" and d.is_dir() and not any(d.iterdir()) and str(d) not in journal["removed_dirs"]:
                d.rmdir()
                journal["removed_dirs"].append(str(d))
    # the user refresh switches some services on the first time it sees them: a moved one has been seen
    moved_units = [Path(e["path"]).name for e in journal["entries"]
                   if e["state"] == "done" and e["group"] == "user-services" and e["action"] == "remove"]
    if moved_units:
        seen = STATE / "user-units.seen"
        try:
            have = set(seen.read_text().split())
        except OSError:
            have = set()
        write_atomic(seen, ("\n".join(sorted(have | set(moved_units))) + "\n").encode(), 0o644)
    tell_systemd(journal)
    return changed, skipped


def new_transaction(automatic=False):
    tx = MIGRATIONS / (time.strftime("%Y%m%d-%H%M%S") + f"-{os.getpid()}")
    return tx, {"schema": 1, "id": tx.name, "root": str(ROOT), "status": "running", "automatic": automatic,
                "started": time.strftime("%Y-%m-%dT%H:%M:%S"), "entries": [], "removed_dirs": []}


def finish(tx: Path, journal: dict, plan: Plan) -> None:
    journal["status"] = "done"
    journal["finished"] = time.strftime("%Y-%m-%dT%H:%M:%S")
    write_json(tx / "journal.json", journal)
    set_marker(journal["id"], {e["group"] for e in journal["entries"] if e["state"] == "done"})
    with open(tx / "report.txt", "w") as report:
        print_plan(plan, report)


def cmd_apply(args) -> int:
    dry = "--dry-run" in args
    now = "--now" in args
    extra = [a for a in args if a not in ("--dry-run", "--now")]
    if extra or (dry and now):
        return usage_error(PROG, f"apply doesn't take {extra[0]!r}" if extra else "--dry-run and --now don't go together",
                           "apply [--dry-run | --now]")
    try:
        plan = make_plan()
    except (OSError, ValueError, KeyError) as e:
        print(f"{PROG}: Starchaser's list of default files can't be read ({e}); nothing was changed.", file=sys.stderr)
        return 1
    if dry:
        print_plan(plan)
        print("Dry run: nothing was changed." + (" Run 'starchaser defaults apply' to make these changes; everything is backed up "
                                                 "first and 'starchaser defaults undo' puts it back." if plan.actions else ""))
        return 0
    if not now and desktop_running():
        STATE.mkdir(parents=True, exist_ok=True)
        PENDING.write_text("apply\n")
        print("Your desktop is running, so the move happens the next time you sign in.")
        print("To see what will change: starchaser defaults apply --dry-run")
        return 0
    locks = take_locks()
    if not locks:
        print(f"{PROG}: another move or a desktop update is running. Try again in a minute.", file=sys.stderr)
        return 1
    plan = make_plan()          # again, inside the locks
    # Numbered migrations share backups and Undo, but only their runner may
    # resume them: run_move interprets replacement entries as Hyprland loaders.
    unfinished = [(d, j) for d, j in journals() if j.get("status") == "running"
                  and not j.get("automatic") and "migration" not in j]
    if not plan.actions and not unfinished:
        PENDING.unlink(missing_ok=True)
        set_marker(None, [])
        print_plan(plan)
        print("Nothing to move: this account already uses Starchaser's system copy wherever it can.")
        return 0
    # an earlier move that stopped part way: finish it in the same backup
    tx, journal = unfinished[-1] if unfinished else new_transaction()
    try:
        changed, skipped = run_move(plan, tx, journal)
    except BackupFailed as e:
        print(f"{PROG}: {e}; nothing was changed.", file=sys.stderr)
        return 1
    finish(tx, journal, plan)
    PENDING.unlink(missing_ok=True)
    print_plan(plan)
    print(f"Done: {changed} file{'s' if changed != 1 else ''} changed. Your edited files were kept.")
    for path in skipped:
        print(f"  not changed: {shown(path)} (it changed while this ran, or couldn't be written)")
    print(f"Backup and report: {shown(tx)}. To put everything back: starchaser defaults undo")
    return 0 if not skipped else 1


# ---------------------------------------------------------------- undo

def put_back(tx: Path, journal: dict):
    """Restore every path the move changed that still holds the move's result; a later change of the person's own
    wins. Returns (files put back, paths kept)."""
    for d in journal.get("removed_dirs", []):
        Path(d).mkdir(parents=True, exist_ok=True)
    restored, kept = 0, []
    for e in reversed(journal["entries"]):
        if e["state"] not in ("done", "backed-up"):
            continue
        path = Path(e["path"])
        if e["action"] == "create":
            # A numbered migration created this file. Remove only its unchanged result.
            if not os.path.lexists(path):
                e["state"] = "restored"
            elif path.is_file() and not path.is_symlink() and sha256(path) == e.get("after"):
                path.unlink()
                try:
                    path.parent.rmdir()
                except OSError:
                    pass  # A personal edit or another file keeps its folder.
                e["state"] = "restored"
                restored += 1
            else:
                e["state"] = "kept"
                kept.append(path)
            continue
        if e["action"] == "unlink":
            if not os.path.lexists(path) and e["state"] == "done":
                path.parent.mkdir(parents=True, exist_ok=True)
                write_link(path, e["before"]["link"], e["before"]["mtime_ns"])
                e["state"] = "restored"
                restored += 1
            elif os.path.islink(path) and os.readlink(path) == e["before"]["link"]:
                e["state"] = "restored"           # the move never got to it, or the same link is back
            else:
                kept.append(path)                 # something of yours has that name now
                e["state"] = "kept"
            continue
        if e["action"] == "relink":
            try:
                named = os.readlink(path)
            except OSError:
                named = None
            if named == e["target"]:
                write_link(path, e["before"]["link"], e["before"]["mtime_ns"])
                e["state"] = "restored"
                restored += 1
            elif e["state"] == "backed-up" and named == e["before"]["link"]:
                e["state"] = "restored"           # the move never got to it
            else:
                kept.append(path)
                e["state"] = "kept"
            continue
        backup = tx / e["backup"]
        if never(path):
            e["state"] = "kept"
            continue
        if e["action"] == "remove":
            ours = not os.path.lexists(path)          # still gone: the move's result
        else:
            try:
                ours = path.is_file() and not path.is_symlink() and sha256(path) == e.get("after", hashlib.sha256(loader_text(ROOT).encode()).hexdigest())
            except OSError:
                ours = False
            if not ours and e["state"] == "backed-up" and same_as_planned(path, e["before"]):
                e["state"] = "restored"           # the move never got to it
                continue
        if not ours:
            if e["state"] == "backed-up" and e["action"] == "remove":
                e["state"] = "restored"           # the move never got to it: it is still there
                continue
            kept.append(path)
            e["state"] = "kept"
            continue
        path.parent.mkdir(parents=True, exist_ok=True)
        tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
        shutil.copy2(backup, tmp)
        os.chmod(tmp, e["before"]["mode"])
        if "uid" in e["before"] and os.geteuid() == 0:
            os.chown(tmp, e["before"]["uid"], e["before"]["gid"])
        os.utime(tmp, ns=(e["before"]["mtime_ns"], e["before"]["mtime_ns"]))
        os.replace(tmp, path)
        e["state"] = "restored"
        restored += 1
    journal["status"] = "undone"
    journal["undone"] = time.strftime("%Y-%m-%dT%H:%M:%S")
    write_json(tx / "journal.json", journal)
    set_marker(journal["id"], [], undone=True)
    tell_systemd(journal)
    return restored, kept


def cmd_undo(args) -> int:
    if len(args) > 1 or (args and args[0].startswith("-")):
        return usage_error(PROG, f"undo doesn't take {args[-1]!r}", "undo [ID]")
    own = lock(MIGRATIONS / ".lock", 5)
    if not own:
        print(f"{PROG}: a move is running. Try again in a minute.", file=sys.stderr)
        return 1
    found = [(d, j) for d, j in journals() if j.get("status") in ("done", "running") and (not args or d.name == args[0])]
    if not found:
        print(f"{PROG}: " + (f"there is no move called {args[0]} to undo." if args else "there is nothing to undo."), file=sys.stderr)
        return 1
    tx, journal = found[-1]
    restored, kept = put_back(tx, journal)
    NOTICE.unlink(missing_ok=True)        # the sign-in notice's Undo would have nothing left to do
    print(f"Put back {restored} file{'s' if restored != 1 else ''} from {shown(tx)}.")
    for path in kept:
        print(f"  kept {shown(path)}: you changed it after the move (the old one is in the backup)")
    return 0


def cmd_last(args) -> int:
    if args not in ([], ["--json"]):
        return usage_error(PROG, f"last doesn't take {args[-1]!r}", "last [--json]")
    found = [(d, j) for d, j in journals() if j.get("status") in ("done", "undone")]
    info = {}
    if found:
        tx, j = found[-1]
        info = {"id": tx.name, "status": j["status"], "automatic": bool(j.get("automatic")),
                "migration": j.get("migration", ""),
                "at": j.get("finished") or j.get("started") or "", "undone": j.get("undone", ""),
                "files": sum(1 for e in j["entries"] if e["state"] in ("done", "restored", "kept"))}
    if args:
        print(json.dumps(info))
    elif not info:
        print("No move yet: this account's files are as the setup left them.")
    else:
        print(f"Last move: {info['id']} ({info['files']} file{'s' if info['files'] != 1 else ''}"
              + (", at sign-in" if info["automatic"] else "") + ")"
              + (f", put back {info['undone']}" if info["status"] == "undone" else ". To put it back: starchaser defaults undo"))
    return 0


# ---------------------------------------------------------------- the move at sign-in (decision 2026-11-02 #12)

def update_channel():
    """'testing' when this computer gets Starchaser's fixes early (Settings > Updates), else 'release'."""
    try:
        text = PACMAN_CONF.read_text()
    except OSError:
        return "release"
    return "testing" if re.search(r"(?m)^[ \t]*\[starchaser-testing\]", text) else "release"


def promoted() -> bool:
    """The installed starchaser-desktop is the version the main channel has, which it gets only after two days in
    testing with no problem recorded (tools/release promote). A checkout, or a version that came from testing before
    this computer left it, isn't."""
    def pacman(*args):
        try:
            r = subprocess.run(["pacman", *args], capture_output=True, text=True, timeout=30)
        except (OSError, subprocess.TimeoutExpired):
            return ""
        return r.stdout if r.returncode == 0 else ""
    installed = pacman("-Q", "starchaser-desktop").split()
    if len(installed) != 2:
        return False
    for line in pacman("-Sl", "starchaser").splitlines():
        words = line.split()
        if len(words) >= 3 and words[1] == "starchaser-desktop" and words[2] == installed[1]:
            return True
    return False


def version() -> str:
    try:
        return (ROOT / "VERSION").read_text().strip()
    except OSError:
        return ""


def set_notice(kind, tx=None, files=0, why="") -> None:
    write_json(NOTICE, {"kind": kind, "id": tx.name if tx else "", "files": files, "why": why,
                        "at": time.strftime("%Y-%m-%dT%H:%M:%S")})


def cmd_auto(args) -> int:
    if args:
        return usage_error(PROG, f"auto takes nothing after it (got {args[0]!r})", "auto")
    try:
        manifest, _ = load_data()
    except (OSError, ValueError, KeyError) as e:
        print(f"{PROG}: Starchaser's list of default files can't be read ({e}); nothing was changed.", file=sys.stderr)
        return 1
    tried = read_marker()["automatic"]
    # a group moves at sign-in only once its move has passed the checks on a test VM (its "automatic" note says which)
    due = [g["id"] for g in manifest["groups"] if g.get("status") == "ready" and g.get("automatic") and g["id"] not in tried]
    cut_short = [(d, j) for d, j in journals() if j.get("status") == "running" and j.get("automatic")]
    if not due and not cut_short:
        return 0
    if desktop_running():
        print("The desktop is running: the move waits for the next sign-in.")
        return 0
    if update_channel() != "testing" and not promoted():
        print("This computer gets Starchaser's updates after testing: the move waits until this version is promoted.")
        return 0
    locks = take_locks()
    if not locks:
        print(f"{PROG}: another move or a desktop update is running; trying again at the next sign-in.", file=sys.stderr)
        return 1
    stamp = {"at": time.strftime("%Y-%m-%dT%H:%M:%S"), "version": version()}
    # a sign-in move that was cut short (power lost): put back what it changed, and say so once
    for tx, journal in cut_short:
        put_back(tx, journal)
        journal["failed"] = "it was cut short"
        write_json(tx / "journal.json", journal)
        set_marker(None, [], automatic={g: dict(stamp, result="failed", transaction=tx.name)
                                        for g in {e["group"] for e in journal["entries"]} | set(journal.get("groups", []))})
        set_notice("failed", tx, why="it was cut short")
        print(f"The move at an earlier sign-in was cut short; everything it changed was put back ({shown(tx)}).")
    tried = read_marker()["automatic"]
    due = [g for g in due if g not in tried]
    if not due:
        return 0
    tx, journal = new_transaction(automatic=True)
    journal["groups"] = due
    try:
        plan = make_plan(only=due)
        if not plan.actions:
            set_marker(None, [], automatic={g: dict(stamp, result="nothing") for g in due})
            print("Nothing to move on this account.")
            return 0
        changed, skipped = run_move(plan, tx, journal)
        failed = f"{len(skipped)} file{'s' if len(skipped) != 1 else ''} changed while it ran or couldn't be written" if skipped else ""
    except BackupFailed as e:
        failed, changed = str(e), 0
    except Exception as e:      # whatever went wrong, the person's files go back as they were
        failed, changed = f"{type(e).__name__}: {e}", 0
    if failed:
        if journal["entries"]:
            restored, kept = put_back(tx, journal)
        else:
            tx.mkdir(parents=True, exist_ok=True)
            kept = []
        journal["status"], journal["failed"] = "undone", failed
        write_json(tx / "journal.json", journal)
        set_marker(None, [], automatic={g: dict(stamp, result="failed", transaction=tx.name) for g in due})
        set_notice("failed", tx, why=failed)
        print(f"The move didn't finish ({failed}); every file was left as it was. Details: {shown(tx)}")
        for path in kept:
            print(f"  kept {shown(path)}: it changed while the move ran")
        return 1
    finish(tx, journal, plan)
    set_marker(None, [], automatic={g: dict(stamp, result="moved", transaction=tx.name) for g in due})
    if changed:
        set_notice("done", tx, files=changed)
    print_plan(plan)
    print(f"Done: {changed} file{'s' if changed != 1 else ''} changed at sign-in. Backup and report: {shown(tx)}")
    return 0


def cmd_notice(args) -> int:
    """Once, when the desktop is up: what the sign-in move did, with Undo. Waits up to 2 minutes for the
    notification service; the note is removed once a notification has been shown."""
    if args:
        return usage_error(PROG, f"notice takes nothing after it (got {args[0]!r})", "notice")
    try:
        note = json.loads(NOTICE.read_text())
    except (OSError, ValueError):
        return 0
    if note.get("kind") == "done":
        title = "Your desktop defaults were updated"
        body = ("Starchaser's own copies in your home folder were replaced by the up-to-date system ones. Files you "
                "changed were kept, and everything was backed up first. Undo is also in Settings > Updates.")
        cmd = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "system-software-update", "-A", "undo=Undo", title, body]
    else:
        title = "Your desktop defaults weren't updated"
        body = ("Something went wrong, so every file in your home folder was left exactly as it was. Nothing needs "
                "doing; Starchaser won't try this again by itself.")
        cmd = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "dialog-information", title, body]
    end = time.monotonic() + 120
    while True:
        try:
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
        except OSError:
            return 1
        try:
            out, _ = p.communicate(timeout=3)
            shown_ok = p.returncode == 0
        except subprocess.TimeoutExpired:
            out, shown_ok = None, True        # still open, waiting for a click: it is on screen
        if shown_ok:
            break
        if time.monotonic() > end:
            return 1
        time.sleep(5)
    NOTICE.unlink(missing_ok=True)
    if out is None:
        out = p.communicate()[0]
    if note.get("kind") == "done" and out.strip() == "undo" and note.get("id"):
        r = subprocess.run([sys.executable, str(Path(__file__).resolve()), "undo", note["id"]], capture_output=True, text=True)
        if r.returncode == 0:
            subprocess.run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "edit-undo", "Your previous files are back",
                            "Sign out and back in for every app to use them again."], stderr=subprocess.DEVNULL)
        else:
            subprocess.run([*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "dialog-warning", "Undo didn't finish",
                            "Try again in Settings > Updates."], stderr=subprocess.DEVNULL)
    return 0


# ---------------------------------------------------------------- status

def cmd_status(args) -> int:
    if args:
        return usage_error(PROG, f"status takes nothing after it (got {args[0]!r})", "status")
    try:
        plan = make_plan()
    except (OSError, ValueError, KeyError) as e:
        print(f"{PROG}: Starchaser's list of default files can't be read ({e}).", file=sys.stderr)
        return 1
    moving = {a["group"] for a in plan.actions}
    for gid, name, lines in plan.groups:
        own = any(k == "keep" for k, _, _ in lines)
        if gid in moving:
            state = "your home folder has copies that can move to Starchaser's system copy"
        elif gid in plan.system:
            state = "uses Starchaser's system copy" + (", with files of your own" if own else "")
        elif own:
            state = "uses your own files, kept as they are"
        else:
            state = "nothing to move"
        print(f"{name}: {state}")
    if plan.deferred:
        print("Still copied into your home folder (not moved yet): " + "; ".join(plan.deferred))
    if PENDING.exists():
        print("A move is waiting for your next sign-in.")
    last = [(d, j) for d, j in journals() if j.get("status") in ("done", "running")]
    if last:
        print(f"Last move: {last[-1][0].name}. To put it back: starchaser defaults undo")
    if plan.actions:
        print("To see what would move: starchaser defaults apply --dry-run")
    return 0


# ---------------------------------------------------------------- init, path

def cmd_init(args) -> int:
    """The setup's Hyprland step: a new account gets the small loader for this Starchaser folder; an account that has
    it keeps its own lines and follows this folder (the setup always installs from the folder it runs from)."""
    if args:
        return usage_error(PROG, f"init takes nothing after it (got {args[0]!r})", "init")
    entry = personal_dir() / "hypr/hyprland.lua"
    found = None
    if entry.is_file() and not entry.is_symlink():
        found = read_loader(entry.read_text(errors="replace"))
    if entry.is_symlink() or (entry.exists() and not found):
        print("This account has its own full hyprland.lua: it is kept as it is.")
        return 3
    if found and found[0] == str(ROOT):
        print(f"Hyprland loads Starchaser's settings from {ROOT}.")
        return 0
    text = loader_text(ROOT)
    if found and found[1]:
        text += found[1] + "\n"
    try:
        write_atomic(entry, text.encode())
    except OSError as e:
        print(f"{PROG}: couldn't write {entry}: {e.strerror}", file=sys.stderr)
        return 1
    print(f"Hyprland loads Starchaser's settings from {ROOT}. Your own settings go in ~/.config/hypr/user.lua.")
    return 0


def preset_file() -> Path:
    return Path(os.environ.get("STARCHASER_PRESET") or "/usr/lib/systemd/user-preset/50-starchaser.preset")


def account_initialized() -> bool:
    """A Starchaser setup or refresh has run for this account before: its unit list, its migration marker or any
    Starchaser unit link of its own is there."""
    if (STATE / "user-units.seen").exists() or MARKER.exists():
        return True
    units = HOME / ".config/systemd/user"
    return units.is_dir() and any(units.glob("*.wants/starchaser-*"))


def cmd_preset(args) -> int:
    """Apply Starchaser's new-account preset to this account's named units, once, and only when the account was never
    set up. It needs a running user manager (it never starts one) and never touches an account that has any history."""
    if args:
        return usage_error(PROG, f"preset takes nothing after it (got {args[0]!r})", "preset")
    if account_initialized():
        print("This account was set up before: its services stay as they are.")
        return 0
    try:
        named = [ln.split()[1] for ln in preset_file().read_text().splitlines() if ln.startswith("enable ")]
    except OSError:
        print(f"{PROG}: Starchaser's new-account list isn't installed.", file=sys.stderr)
        return 1
    if subprocess.run(["systemctl", "--user", "is-system-running"], capture_output=True, text=True).stdout.strip() not in ("running", "degraded"):
        print("The account's services aren't running yet, so nothing was switched on; run this again after sign-in.")
        return 0
    done = subprocess.run(["systemctl", "--user", "preset", "--", *named]).returncode
    return 0 if done == 0 else 1


def cmd_path(args) -> int:
    if len(args) != 1 or not args[0] or args[0].startswith("/") or ".." in Path(args[0]).parts:
        return usage_error(PROG, "path needs one file under config/, like hypr/scripts/volume.sh", "path FILE")
    found = config_file(args[0])
    if not found:
        print(f"{PROG}: there is no {args[0]} in your settings or in Starchaser's", file=sys.stderr)
        return 1
    print(found)
    return 0


# Features that arrive in an update wait for a yes (decided 2026-11-16): no new service, timer or listener starts by
# itself. The user refresh records each new unit here; the person turns it on, or dismisses it, with these commands.
# What each one does, in plain words; a unit not listed gets a name made from the unit's own.
FEATURE_WORDS = {
    "starchaser-fleet-recovery.timer": "Fleet recovery check: looks for a fleet computer that needs help getting back in",
    "starchaser-fleet-watch.timer": "Fleet watch: checks on the other computers in your fleet",
    "starchaser-backup-offer.timer": "Backup reminder: offers to back up your files now and then",
    "starchaser-region.timer": "Night light place check: finds sunrise and sunset from your time zone",
    "starchaser-ai-usage.timer": "AI usage check: counts what your AI accounts have used",
    "starchaser-desktop-copy.timer": "Desktop copy check",
    "starchaser-permissions.service": "App permission notices",
    "starchaser-printer-usb.service": "USB printer setup: sets up a USB printer when you plug it in",
    "starchaser-input-method.service": "Typing in other languages (input method)",
    "starchaser-power-watch.service": "Battery watch: warns when the battery is low and acts when it is nearly empty",
    "starchaser-files-index.timer": "Search inside your files: reads the text of your documents so Files can find it",
    "starchaser-cloud-folders.service": "Cloud folders in Files",
    "starchaser-automount.service": "USB drives open by themselves when you plug them in",
    "starchaser-link.service": "Link to your other computers: listens for your other computers on this network",
    "starchaser-localsend.service": "Nearby sharing: receives files from phones and computers nearby",
}
FEATURES_FILE = "new-features.pending"
FEATURES_DECLINED = "new-features.declined"
UPDATE_MACHINERY = ("starchaser-refresh.path", "starchaser-refresh-login.service")


def feature_name(unit: str) -> str:
    return FEATURE_WORDS.get(unit) or unit.removeprefix("starchaser-").rsplit(".", 1)[0].replace("-", " ").capitalize()


def feature_read(name: str) -> list:
    try:
        return [u for u in (STATE / name).read_text().split() if re.fullmatch(r"starchaser-[A-Za-z0-9@_.-]+\.(?:service|timer|path|socket)", u)]
    except OSError:
        return []


def feature_write(name: str, units: list) -> None:
    STATE.mkdir(parents=True, exist_ok=True)
    write_atomic(STATE / name, ("\n".join(sorted(set(units))) + "\n" if units else "").encode(), 0o644)


def cmd_features(args) -> int:
    """features [list|add UNIT...|on NAME|all|dismiss NAME|all]. add is the user refresh's: it records units that
    arrived in an update and turns nothing on."""
    verb, rest = (args[0], args[1:]) if args else ("list", [])
    pending = feature_read(FEATURES_FILE)
    if verb == "list":
        if not pending:
            print("No new features are waiting.")
        for unit in pending:
            print(f"{unit}\t{feature_name(unit)}")
        return 0
    if verb == "add":
        declined = set(feature_read(FEATURES_DECLINED))
        fresh = [u for u in rest if u not in pending and u not in declined and re.fullmatch(r"starchaser-[A-Za-z0-9@_.-]+\.(?:service|timer|path|socket)", u)]
        if fresh:
            feature_write(FEATURES_FILE, pending + fresh)
        for unit in fresh:
            print(feature_name(unit))
        return 0
    if verb in ("on", "dismiss") and rest:
        chosen = pending if rest == ["all"] else [u for u in rest if u in pending]
        if not chosen:
            print("That isn't waiting for an answer. Run: starchaser defaults features", file=sys.stderr)
            return 1
        failed = 0
        for unit in chosen:
            if verb == "on":
                done = subprocess.run(["systemctl", "--user", "enable", "--now", unit], capture_output=True, text=True)
                if done.returncode:
                    print(f"Couldn't turn on {feature_name(unit)}: {done.stderr.strip()}", file=sys.stderr)
                    failed = 1
                    continue
                print(f"Turned on: {feature_name(unit)}")
            else:
                feature_write(FEATURES_DECLINED, feature_read(FEATURES_DECLINED) + [unit])
                print(f"Left off: {feature_name(unit)}")
            pending = [u for u in pending if u != unit]
        feature_write(FEATURES_FILE, pending)
        return failed
    return usage_error(PROG, "features needs list, add UNIT, on NAME or dismiss NAME", "features [list|add|on|dismiss] [UNIT ...]", COMMANDS)


def main(argv) -> int:
    safe_streams()
    if not argv:
        return usage_error(PROG, "missing command", "COMMAND [ARG ...]", COMMANDS)
    if argv[0] == "help" or "-h" in argv or "--help" in argv:
        print(__doc__.strip())
        return 0
    cmd, rest = argv[0], argv[1:]
    handlers = {"status": cmd_status, "apply": cmd_apply, "undo": cmd_undo, "last": cmd_last, "auto": cmd_auto,
                "notice": cmd_notice, "init": cmd_init, "path": cmd_path, "preset": cmd_preset,
                "features": cmd_features}
    if cmd not in handlers:
        return usage_error(PROG, f"unknown command {cmd!r}", "COMMAND [ARG ...]", COMMANDS)
    return handlers[cmd](rest)


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