#!/usr/bin/env python3
# summary: Read or apply portable settings for fleet synchronization.
"""Synchronize this account's portable settings through their owning tools.

All six Follow switches start off. This command never connects to another computer.
Use export --publish to deliberately share this computer's settings after enabling Follow.
Use report to read status and recent local activity as one JSON object, without a network connection.
"""
import copy
import fcntl
import importlib.machinery
import importlib.util
import json
import os
import pwd
import re
import secrets
import stat
import subprocess
import sys
import tempfile
import time
from argparse import RawDescriptionHelpFormatter
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_settings_schema as schema
from starchaser_cli import CommandParser

CATEGORIES = schema.CATEGORIES
LABELS = {"off": "Off", "same": "Same", "different": "Different", "pending": "Waiting to apply",
          "waiting-sign-in": "Waiting for you to sign in", "needs-update": "This computer needs an update",
          "offline": "Can't reach it right now", "refused": "That computer turned this one away",
          "unavailable": "Not installed here (for example, a pointer style this computer doesn't have)",
          "error": "Couldn't apply",
          "repair-needed": "Couldn't finish or undo a change. Run `starchaser fleet settings status` for what to do",
          "revision-limit": "Too many changes to track. Turn Follow off and on again"}
# the area of the one command that owns each category; its tool is the file starchaser-AREA next to this one
TOOLS = {"look": "theme", "notifications": "notifications", "clock-bar": "theme",
         "input": "input", "power-profiles": "power", "shortcuts-profile": "shortcuts"}
EVENTS = ("received", "applied", "undone", "refused", "failed")


class Failure(Exception):
    def __init__(self, message="Settings could not be applied.", code=1, state="error"):
        super().__init__(message)
        self.code, self.state = code, state


def check_user():
    if os.geteuid() == 0 or os.getuid() != os.geteuid():
        raise Failure("Run this command as the account whose settings you want to use.", 4, "refused")
    return pwd.getpwuid(os.getuid()).pw_name


def membership():
    """The registry owner supplies a non-mutating, fail-closed view of existing membership."""
    path = Path(__file__).resolve().with_name("starchaser-fleet")
    loader = importlib.machinery.SourceFileLoader("starchaser_settings_registry", str(path))
    spec = importlib.util.spec_from_loader(loader.name, loader)
    owner = importlib.util.module_from_spec(spec)
    try:
        loader.exec_module(owner)
        return owner.settings_context()
    except (OSError, ValueError, TypeError, KeyError, AttributeError):
        raise Failure("The computer list or paired accounts couldn't be checked.", 4, "refused") from None


NOT_ALLOWED = ("This computer isn't letting your fleet manage it. To allow it, open Settings here, choose Fleet, "
               "and turn on Let your fleet manage this computer.")


def manage_allowed():
    """This computer's own current answer, read fresh each time; anything unreadable counts as no."""
    path = Path(__file__).resolve().with_name("starchaser-fleet")
    try:
        loader = importlib.machinery.SourceFileLoader("starchaser_settings_consent", str(path))
        spec = importlib.util.spec_from_loader(loader.name, loader)
        owner = importlib.util.module_from_spec(spec)
        loader.exec_module(owner)
        return owner.manage_consent_on() is True
    except (OSError, ValueError, TypeError, KeyError, AttributeError, ImportError, SyntaxError):
        return False


def session_ready():
    """Require logind's root-owned session record and this user's actual compositor sockets.

    Environment variables alone (including those inherited through SSH) are not proof of sign-in.
    No session discovery may choose a different user or a different compositor instance.
    """
    sid = os.environ.get("XDG_SESSION_ID", "")
    sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE", "")
    wayland = os.environ.get("WAYLAND_DISPLAY", "")
    if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", sid) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,160}", sig):
        return False
    if not re.fullmatch(r"wayland-[0-9]+", wayland):
        return False
    runtime = Path(f"/run/user/{os.getuid()}")
    if os.environ.get("XDG_RUNTIME_DIR") != str(runtime):
        return False
    if os.environ.get("DBUS_SESSION_BUS_ADDRESS") != f"unix:path={runtime}/bus":
        return False
    try:
        record = Path("/run/systemd/sessions") / sid
        info = record.lstat()
        if not stat.S_ISREG(info.st_mode) or info.st_uid != 0:
            return False
        data = dict(line.split("=", 1) for line in record.read_text().splitlines() if "=" in line)
        if data.get("UID") != str(os.getuid()) or data.get("ACTIVE") != "1" or data.get("TYPE") != "wayland":
            return False
        if data.get("STATE") != "active" or data.get("REMOTE") not in ("0", "no") or data.get("CLASS") != "user":
            return False
        for socket in (runtime / "bus", runtime / wayland, runtime / "hypr" / sig / ".socket.sock"):
            info = socket.lstat()
            if not stat.S_ISSOCK(info.st_mode) or info.st_uid != os.getuid():
                return False
        return runtime.stat().st_uid == os.getuid()
    except (OSError, ValueError):
        return False


def safe_directory(path):
    for ancestor in (path, *path.parents):
        if ancestor.is_symlink():
            raise Failure("A settings state folder is linked. Use a folder owned by this account.", 4, "refused")
    path.mkdir(parents=True, exist_ok=True, mode=0o700)
    info = path.lstat()
    if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid():
        raise Failure("A settings state folder belongs to another account.", 4, "refused")
    if stat.S_IMODE(info.st_mode) != 0o700:
        os.chmod(path, 0o700)


def secure_open(path, flags):
    try:
        fd = os.open(path, flags | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
    except OSError as ex:
        if path.is_symlink():
            raise Failure("A settings state file is linked.", 4, "refused") from ex
        raise
    info = os.fstat(fd)
    if info.st_uid != os.getuid() or not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
        os.close(fd)
        raise Failure("A settings state file isn't private to this account.", 4, "refused")
    if stat.S_IMODE(info.st_mode) != 0o600:
        os.fchmod(fd, 0o600)
    return fd


class Store:
    def __init__(self):
        home = Path.home()
        self.config = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config") / "starchaser/fleet-settings.json"
        self.root = Path(os.environ.get("XDG_STATE_HOME") or home / ".local/state") / "starchaser/fleet-settings"
        self.runtime = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser/fleet-settings"
        for path in (self.config.parent, self.root.parent, self.root):
            safe_directory(path)
        self.lock = os.fdopen(secure_open(self.root / "lock", os.O_RDWR | os.O_CREAT), "w")
        fcntl.flock(self.lock, fcntl.LOCK_EX)

    def close(self):
        self.lock.close()

    def path(self, name):
        return self.config if name == "follow" else self.root / (name + ".json")

    def read(self, name, default=None):
        try:
            fd = secure_open(self.path(name), os.O_RDONLY)
        except FileNotFoundError:
            return copy.deepcopy(default)
        with os.fdopen(fd, "rb") as handle:
            try:
                return schema.loads(handle.read(4 * 1024 * 1024 + 1), limit=4 * 1024 * 1024)
            except (ValueError, TypeError):
                raise Failure("Saved settings state couldn't be read. Keep it for repair.") from None

    def sync_directory(self, path):
        fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)

    def write(self, name, value):
        path = self.path(name)
        text = json.dumps(value, sort_keys=True, ensure_ascii=True, allow_nan=False) + "\n"
        # Check an existing destination before replacing it, including dangling links and hard links. The same
        # bytes already there are not written again: the link daemon's regular refresh would otherwise replace
        # state.json each time, and every replacement wakes the taskbar's status read (and the sync behind it).
        try:
            fd = secure_open(path, os.O_RDONLY)
        except FileNotFoundError:
            pass
        else:
            with os.fdopen(fd, "rb") as current:
                if current.read(len(text) + 1) == text.encode():
                    return
        fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + ".", suffix=".tmp")
        try:
            with os.fdopen(fd, "w") as out:
                out.write(text)
                out.flush()
                os.fsync(out.fileno())
            os.replace(tmp, path)
            self.sync_directory(path.parent)
        finally:
            if os.path.exists(tmp):
                os.unlink(tmp)

    def delete(self, name):
        try:
            fd = secure_open(self.path(name), os.O_RDONLY)
        except FileNotFoundError:
            return
        os.close(fd)
        self.path(name).unlink()
        self.sync_directory(self.path(name).parent)

    def log(self, event, source, categories, why=""):
        """Activity is best effort: a damaged log must never interrupt settings sync."""
        try:
            if event not in EVENTS:
                return
            selected = [c for c in categories if isinstance(c, str) and c in CATEGORIES]
            if categories and not selected:
                return
            source = source if isinstance(source, str) and schema.DEVICE.fullmatch(source) else ""
            why = re.sub(r"[\x00-\x1f\x7f-\x9f]", "", why)[:160] if event in ("refused", "failed") else ""
            entry = {"t": int(time.time()), "event": event, "from": source, "categories": selected, "why": why}
            path = self.root / "activity.jsonl"
            with os.fdopen(secure_open(path, os.O_APPEND | os.O_CREAT | os.O_WRONLY), "w", encoding="ascii") as out:
                out.write(json.dumps(entry, sort_keys=True, ensure_ascii=True) + "\n")
            with os.fdopen(secure_open(path, os.O_RDONLY), "rb") as handle:
                lines = handle.readlines()
            if sum(map(len, lines)) <= 96 * 1024 and len(lines) <= 400:
                return
            lines = lines[-300:]
            size = sum(map(len, lines))
            while lines and size > 96 * 1024:
                size -= len(lines.pop(0))
            fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + ".", suffix=".tmp")
            try:
                with os.fdopen(fd, "wb") as out:
                    out.writelines(lines)
                    out.flush()
                    os.fsync(out.fileno())
                os.replace(tmp, path)
                self.sync_directory(path.parent)
            finally:
                if os.path.exists(tmp):
                    os.unlink(tmp)
        except (Failure, OSError, ValueError, TypeError):
            pass

    def read_log(self, limit=40):
        """Return recent valid entries in file order, without repairing or rewriting the log."""
        try:
            if type(limit) is not int or limit <= 0:
                return []
            entries = []
            with os.fdopen(secure_open(self.root / "activity.jsonl", os.O_RDONLY), "rb") as handle:
                for line in handle:
                    try:
                        entry = json.loads(line)
                    except (ValueError, RecursionError):
                        continue
                    if not isinstance(entry, dict) or set(entry) != {"t", "event", "from", "categories", "why"}:
                        continue
                    if type(entry["t"]) is not int or entry["event"] not in EVENTS:
                        continue
                    source, categories, why = entry["from"], entry["categories"], entry["why"]
                    if not isinstance(source, str) or (source and not schema.DEVICE.fullmatch(source)):
                        continue
                    if not isinstance(categories, list) or any(not isinstance(c, str) or c not in CATEGORIES for c in categories):
                        continue
                    if not isinstance(why, str) or len(why) > 160 or re.search(r"[\x00-\x1f\x7f-\x9f]", why):
                        continue
                    if entry["event"] not in ("refused", "failed") and why:
                        continue
                    entries.append(entry)
            return entries[-limit:]
        except (Failure, OSError, ValueError, TypeError):
            return []

    def catch_up(self):
        for path in (self.runtime.parent, self.runtime):
            safe_directory(path)
        # Same secure writer, at a runtime path; this is a request, never a received payload.
        old = self.root
        try:
            self.root = self.runtime
            self.write("catch-up", {"schema": 1, "catch_up": True})
        finally:
            self.root = old


def wire_size(value):
    """Bytes on the wire: UTF-8 JSON exactly as main() prints it."""
    return len(json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False).encode("utf-8"))


# Room kept for the reply's result and availability fields next to the records.
RECORDS_BUDGET = schema.MAX_BYTES - 8 * 1024


def fresh_state():
    return {"schema": 1, "records": {}, "incompatible": {}, "observations": {}, "applied": {}, "highest": {},
            "pending": {}, "availability": {}, "peers": {}, "notes": {}}


def validate_local(state, follow):
    schema.fields(follow, ("schema", "follow"))
    schema.require(type(follow["schema"]) is int and follow["schema"] == 1)
    schema.fields(follow["follow"], CATEGORIES)
    for value in follow["follow"].values():
        schema.boolean(value)
    schema.fields(state, fresh_state())
    schema.require(type(state["schema"]) is int and state["schema"] == 1)
    for name in fresh_state().keys() - {"schema", "peers"}:
        schema.fields(state[name], (), CATEGORIES)
    schema.require(isinstance(state["peers"], dict))
    for name in ("records", "incompatible"):
        for category, record in state[name].items():
            schema.record(record)
            schema.require(record["category"] == category)
    for category, value in state["observations"].items():
        schema.payload(category, value)
    for value in state["highest"].values():
        schema.number(value, 0, schema.MAX_COUNTER - 1, integer=True)
    for value in state["pending"].values():
        schema.choice(value, LABELS)
    for value in state["availability"].values():
        schema.fields(value, ("available", "state"))
        schema.boolean(value["available"])
        schema.choice(value["state"], LABELS)
    for value in state["notes"].values():
        schema.require(isinstance(value, str))
    for value in state["applied"].values():
        schema.require(isinstance(value, list) and len(value) == 3)
        schema.number(value[0], 0, schema.MAX_COUNTER - 1, integer=True)
        schema.require(isinstance(value[1], str) and schema.DEVICE.fullmatch(value[1]))
        schema.require(isinstance(value[2], str) and re.fullmatch(r"[0-9a-f]{64}", value[2]))


def validate_extra(extra):
    schema.fields(extra, (), ("power_mode",))
    if "power_mode" in extra:
        schema.choice(extra["power_mode"], schema.MODES[1:])


def validate_snapshot(snapshot):
    if snapshot is None:
        return
    schema.fields(snapshot, ("schema", "token", "before", "extra"))
    schema.require(type(snapshot["schema"]) is int and snapshot["schema"] == 1)
    schema.require(isinstance(snapshot["token"], str) and re.fullmatch(r"[A-Za-z0-9_-]{32}", snapshot["token"]))
    schema.fields(snapshot["before"], (), CATEGORIES)
    schema.require(bool(snapshot["before"]))
    for category, data in snapshot["before"].items():
        schema.payload(category, data)
    validate_extra(snapshot["extra"])


def validate_transaction(transaction):
    if transaction is None:
        return
    schema.fields(transaction, ("schema", "phase", "kind", "before", "targets", "extra", "attempted",
                                "state_before", "follow_before"), ("state_after", "follow_after", "undo_after"))
    schema.require(type(transaction["schema"]) is int and transaction["schema"] == 1)
    schema.choice(transaction["phase"], ("applying", "rollback", "committing"))
    schema.choice(transaction["kind"], ("apply", "undo"))
    for name in ("before", "targets"):
        schema.fields(transaction[name], (), CATEGORIES)
        for category, data in transaction[name].items():
            schema.payload(category, data)
    schema.require(transaction["before"].keys() == transaction["targets"].keys())
    attempted = transaction["attempted"]
    schema.require(isinstance(attempted, list) and len(attempted) <= 6)
    schema.require(all(isinstance(c, str) and c in transaction["before"] for c in attempted))
    schema.require(len(set(attempted)) == len(attempted))
    validate_extra(transaction["extra"])
    validate_local(transaction["state_before"], transaction["follow_before"])
    if transaction["phase"] == "committing":
        validate_local(transaction["state_after"], transaction["follow_after"])
        validate_snapshot(transaction["undo_after"])


class Owners:
    def __init__(self):
        self.bin = Path(__file__).resolve().parent
        self.input_info = None
        self.power_info = None
        self.notes = {}
        self.fleet_apply = False

    def call(self, tool, *args, data=None, applying=False, plain=False):
        if tool == "starchaser":   # starchaser AREA ...: run the area's tool file next to this one
            tool, args = f"starchaser-{args[0]}", args[1:]
        path = self.bin / tool
        env = dict(os.environ)
        if applying or self.fleet_apply:
            env["STARCHASER_FLEET_APPLY"] = "1"
        try:
            result = subprocess.run([str(path), *args], input=None if data is None else json.dumps(data, allow_nan=False),
                                    capture_output=True, text=True, timeout=90, env=env, cwd=self.bin)
        except FileNotFoundError:
            raise Failure("A settings tool isn't installed here.", state="unavailable") from None
        except (OSError, subprocess.SubprocessError):
            raise Failure("A settings tool couldn't finish.") from None
        if result.returncode == 3:
            raise Failure("A required settings choice isn't installed here.", state="unavailable")
        if result.returncode:
            raise Failure("The settings tool couldn't read or apply this category.")
        if plain:
            return result.stdout.strip()
        try:
            return schema.loads(result.stdout, limit=1024 * 1024)
        except (ValueError, TypeError):
            raise Failure("A settings tool returned unreadable data.") from None

    def export(self, category):
        if category in ("look", "clock-bar"):
            data = self.call("starchaser", "theme", "data", "export", category)
        elif category == "notifications":
            data = self.call("starchaser", "notifications", "export")
        elif category == "power-profiles":
            data = self.call("starchaser", "power", "export-profiles")
        elif category == "shortcuts-profile":
            data = {"profile": self.call("starchaser", "shortcuts", "profile", "get", plain=True)}
        else:
            info = self.call("starchaser", "input", "get")
            if not isinstance(info, dict) or info.get("broken") is not False or info.get("supported") is not True:
                raise Failure("Input settings need attention before they can follow.")
            self.input_info = info
            if info.get("trial"):
                raise Failure("Finish trying the mouse buttons before sharing Input.", state="pending")
            data = {}
            try:
                for key in schema.INPUT_KEYS:
                    value = info["settings"]
                    for part in key.split("."):
                        value = value[part]
                    data[key] = value
            except (TypeError, KeyError):
                raise Failure("Input settings couldn't be read.") from None
        try:
            return schema.payload(category, data)
        except (ValueError, TypeError):
            raise Failure("The current settings are outside the portable choices.") from None

    def preflight(self, category, data):
        if category == "look":
            # Validation lives beside the bundled themes and the owning validators.
            self.call("starchaser", "theme", "data", "check", "look", "--stdin", data=data)
        elif category == "input":
            info = self.input_info
            if info.get("trial"):
                raise Failure("Finish trying the mouse buttons before changing Input.", state="pending")
            themes = info.get("cursorThemes", [])
            if data["cursor.theme"] and data["cursor.theme"] not in {x.get("id") for x in themes if isinstance(x, dict)}:
                raise Failure("The pointer style isn't installed here.", state="unavailable")
            layouts = self.call("starchaser", "input", "layouts")
            known = {(x.get("layout"), x.get("variant")) for x in layouts if isinstance(x, dict)} if isinstance(layouts, list) else set()
            if any((x["layout"], x["variant"]) not in known for x in data["layouts"]):
                raise Failure("A keyboard layout isn't installed here.", state="unavailable")
        elif category == "power-profiles":
            self.power_info = self.call("starchaser", "power", "profile-state")
            if not isinstance(self.power_info, dict) or not isinstance(self.power_info.get("profiles"), list):
                raise Failure("The available power modes couldn't be read.")
            if any(value and value not in self.power_info["profiles"] for value in data.values()):
                raise Failure("A power mode isn't available here.", state="unavailable")
        elif category == "shortcuts-profile":
            available = self.call("starchaser", "shortcuts", "profile", "list", "--json")
            if not isinstance(available, list) or data["profile"] not in {x.get("id") for x in available if isinstance(x, dict)}:
                raise Failure("The shortcut profile isn't installed here.", state="unavailable")
            self.call("starchaser", "shortcuts", "profile", "check", data["profile"])

    def apply(self, category, data):
        schema.payload(category, data)
        if category in ("look", "clock-bar"):
            self.call("starchaser", "theme", "data", "apply", category, "--stdin", data=data, applying=True)
        elif category == "notifications":
            self.call("starchaser", "notifications", "apply", "--stdin", data=data, applying=True)
        elif category == "power-profiles":
            result = self.call("starchaser", "power", "apply-profiles", "--stdin", data=data, applying=True)
            if isinstance(result, dict) and result.get("note"):
                self.notes[category] = "Saved, but the power mode cannot change right now."
        elif category == "shortcuts-profile":
            self.call("starchaser", "shortcuts", "profile", "set", data["profile"], applying=True, plain=True)
        else:
            args = []
            for key in schema.INPUT_KEYS:
                value = data[key]
                if key == "layouts":
                    value = ",".join(x["layout"] + (":" + x["variant"] if x["variant"] else "") for x in value)
                elif isinstance(value, bool):
                    value = "true" if value else "false"
                else:
                    value = str(value)
                args.extend((key, value))
            self.call("starchaser", "input", "set", *args, applying=True, plain=True)

    def restore(self, category, data, extra):
        self.apply(category, data)
        if category == "power-profiles" and extra.get("power_mode"):
            self.call("starchaser", "power", "set", "profile", extra["power_mode"], applying=True, plain=True)


def validate_envelope(value, user, context):
    try:
        schema.fields(value, ("verb", "protocol", "reader", "user", "from", "records"), ("result", "availability"))
        schema.require(value["verb"] == "settings-sync")
        schema.number(value["protocol"], 1, schema.MAX_COUNTER - 1, integer=True)
        schema.number(value["reader"], 1, schema.MAX_COUNTER - 1, integer=True)
        schema.require(isinstance(value["from"], str) and schema.DEVICE.fullmatch(value["from"]))
        schema.require(isinstance(value["user"], str))
        schema.require(isinstance(value["records"], list) and len(value["records"]) <= 6)
        seen = set()
        for record in value["records"]:
            schema.record(record)
            schema.require(record["category"] not in seen)
            seen.add(record["category"])
        if "result" in value:
            schema.fields(value["result"], ("state",), ("categories", "older"))
            schema.choice(value["result"]["state"], LABELS)
            if "categories" in value["result"]:
                schema.fields(value["result"]["categories"], (), CATEGORIES)
                for state in value["result"]["categories"].values():
                    schema.choice(state, LABELS)
            if "older" in value["result"]:
                schema.choice(value["result"]["older"], ("this", "peer"))
        if "availability" in value:
            schema.fields(value["availability"], (), CATEGORIES)
            for available in value["availability"].values():
                schema.fields(available, ("available", "state"))
                schema.boolean(available["available"])
                schema.choice(available["state"], LABELS)
    except (ValueError, TypeError, KeyError):
        raise Failure("The received settings aren't valid.", 2) from None
    if value["user"] != user or value["from"] not in context["paired"]:
        raise Failure("These settings are for a different account or an unpaired computer.", 4, "refused")
    if value["protocol"] != 1 or value["reader"] < 1:
        raise Failure("This computer needs an update to exchange these settings.", 3, "needs-update")
    return value


class Engine:
    def __init__(self, store, owners, user, context, read_only=False):
        self.store, self.owners, self.user, self.context = store, owners, user, context
        self.follow = store.read("follow", {"schema": 1, "follow": dict.fromkeys(CATEGORIES, False)})
        self.state = store.read("state", fresh_state())
        try:
            validate_local(self.state, self.follow)
        except (ValueError, TypeError, KeyError):
            raise Failure("Saved settings state needs repair before it can be used.", state="repair-needed") from None
        if self.prune() and not read_only:
            self.save()

    def save(self):
        self.store.write("state", self.state)

    def prune(self):
        changed = False
        for name in ("records", "incompatible"):
            for category, record in list(self.state[name].items()):
                if record["writer"] not in self.context["writers"]:
                    del self.state[name][category]
                    self.state["pending"].pop(category, None)
                    changed = True
        return changed

    def recheck_context(self):
        current = membership()
        if current["user"] != self.user or current["self"] != self.context["self"]:
            raise Failure("The account or computer list changed. Try again after checking it.", 4, "refused")
        self.context = current
        self.prune()

    def fits(self, category, record):
        """Whether every followed winner, with this one in place, still fits in one message."""
        winners = {}
        for name in CATEGORIES:
            choices = [self.state[kind].get(name) for kind in ("records", "incompatible")]
            winner = max((r for r in choices if r), key=schema.order, default=None)
            if winner and self.follow["follow"][name]:
                winners[name] = winner
        winners[category] = record
        return wire_size(list(winners.values())) <= RECORDS_BUDGET

    def selected(self, categories):
        return [c for c in (categories or CATEGORIES) if self.follow["follow"][c]]

    def refresh(self, categories, publish=False):
        for category in self.selected(categories):
            if category in self.state["incompatible"]:
                continue  # An older reader must not overwrite a newer schema with local defaults.
            try:
                data = self.owners.export(category)
            except Failure as ex:
                self.state["availability"][category] = {"available": False, "state": ex.state}
                continue
            self.state["availability"][category] = {"available": True, "state": "same"}
            previous = self.state["observations"].get(category)
            accepted = self.state["records"].get(category)
            changed = previous is not None and previous != data
            if publish:
                changed = accepted is None or accepted["payload"] != data
            if changed:
                high = max(self.state["highest"].get(category, 0), accepted["rev"] if accepted else 0)
                if high + 1 >= schema.MAX_COUNTER:
                    self.state["pending"][category] = "revision-limit"
                    continue
                # Older computers keep new choices as needs-update instead of rejecting the whole sync.
                version = 2 if ((category == "clock-bar" and "frame" in data)
                                or (category == "look" and data["look"] == "glass-light")) else 1
                record = {"category": category, "rev": high + 1, "writer": self.context["self"], "schema": version,
                          "min_reader": version, "payload": data}
                record["digest"] = schema.digest(record)
                if not self.fits(category, record):
                    self.state["pending"][category] = "error"
                    print("These settings are too large to share. Nothing was published.", file=sys.stderr)
                    continue
                self.state["records"][category] = record
                self.state["highest"][category] = record["rev"]
                self.state["applied"][category] = list(schema.order(record))
                self.state["pending"].pop(category, None)
            self.state["observations"][category] = data
        self.save()

    def merge(self, records):
        received = {}
        for record in records:
            category = record["category"]
            if record["writer"] not in self.context["writers"]:
                continue
            following = self.follow["follow"][category]
            high = self.state["highest"].get(category)
            if high is not None and record["rev"] > high + 65536:
                if following:
                    self.state["pending"][category] = "error"
                    print("A received revision is too far ahead. No record was saved.", file=sys.stderr)
                    self.store.log("refused", record["writer"], [category],
                                   "That change was too far ahead of this computer's copy.")
                continue
            # The highest rev seen is kept even for an unfollowed category (an integer, never the record), so
            # "Turn on and apply" publishes above what the fleet already has instead of losing to it.
            self.state["highest"][category] = max(high if high is not None else 0, record["rev"])
            if not following:
                continue
            candidates = [self.state[name].get(category) for name in ("records", "incompatible")]
            current = max((r for r in candidates if r), key=schema.order, default=None)
            if current and schema.order(record) <= schema.order(current):
                continue
            if not self.fits(category, record):
                self.state["pending"][category] = "error"
                print("Received settings are too large to keep. No record was saved.", file=sys.stderr)
                self.store.log("refused", record["writer"], [category], "That change was too large to keep.")
                continue
            name = "records" if schema.supported(record) else "incompatible"
            self.state[name][category] = record
            if name == "records":
                self.state["incompatible"].pop(category, None)
            self.state["pending"][category] = "pending" if name == "records" else "needs-update"
            received.setdefault(record["writer"], [])
            if category not in received[record["writer"]]:
                received[record["writer"]].append(category)
        self.save()
        for writer, categories in received.items():
            self.store.log("received", writer, categories)

    def envelope(self, categories=None):
        records = []
        availability = {}
        for category in (categories or CATEGORIES):
            active = self.follow["follow"][category]
            if active:
                choices = [self.state[name].get(category) for name in ("records", "incompatible")]
                winner = max((r for r in choices if r), key=schema.order, default=None)
                if winner:
                    records.append(winner)
            availability[category] = self.state["availability"].get(category, {
                "available": os.access(self.owners.bin / f"starchaser-{TOOLS[category]}", os.X_OK), "state": "same" if active else "off"})
        result = {"verb": "settings-sync", "protocol": 1, "reader": 2, "user": self.user, "from": self.context["self"],
                  "records": records, "availability": availability}
        if wire_size(result) > schema.MAX_BYTES:
            raise Failure("The portable settings are too large to exchange.")
        return result

    def begin(self, kind, before, targets, extra):
        transaction = {"schema": 1, "phase": "applying", "kind": kind, "before": before, "targets": targets,
                       "extra": extra, "attempted": [], "state_before": copy.deepcopy(self.state),
                       "follow_before": copy.deepcopy(self.follow)}
        self.store.write("transaction", transaction)
        return transaction

    def finish(self, transaction, snapshot):
        # Commit intent is durable before changing any metadata file. Recovery can finish these replacements.
        transaction.update(phase="committing", state_after=self.state, follow_after=self.follow, undo_after=snapshot)
        self.store.write("transaction", transaction)
        self.store.write("state", self.state)
        self.store.write("follow", self.follow)
        if snapshot is not None:
            self.store.write("undo", snapshot)
        else:
            self.store.delete("undo")
        self.store.delete("transaction")

    def rollback(self, transaction):
        transaction["phase"] = "rollback"
        self.store.write("transaction", transaction)
        failures = []
        for category in reversed(transaction["attempted"]):
            try:
                self.owners.restore(category, transaction["before"][category], transaction["extra"])
                if self.owners.export(category) != transaction["before"][category]:
                    raise Failure()
            except Failure:
                failures.append(category)
        if failures:
            for category in transaction["attempted"]:
                self.state["pending"][category] = "repair-needed"
            self.save()
            raise Failure(LABELS["repair-needed"], state="repair-needed")
        received = self.state
        self.state = copy.deepcopy(transaction["state_before"])
        self.preserve_received(received)
        self.follow = transaction["follow_before"]
        self.save()
        self.store.write("follow", self.follow)
        self.store.delete("transaction")

    def preserve_received(self, received):
        """Receives may queue during a crashed apply. Recovery must keep those newer records."""
        for category in CATEGORIES:
            high = received["highest"].get(category)
            if high is not None:
                self.state["highest"][category] = max(high, self.state["highest"].get(category, 0))
            for name in ("records", "incompatible"):
                newer = received[name].get(category)
                old = self.state[name].get(category)
                if newer and (old is None or schema.order(newer) > schema.order(old)):
                    self.state[name][category] = newer
            candidates = [self.state[name].get(category) for name in ("records", "incompatible")]
            winner = max((r for r in candidates if r), key=schema.order, default=None)
            if winner and self.follow["follow"][category] and self.state["applied"].get(category) != list(schema.order(winner)):
                self.state["pending"][category] = "pending" if schema.supported(winner) else "needs-update"

    def recover(self):
        transaction = self.store.read("transaction")
        if transaction is None:
            return
        try:
            validate_transaction(transaction)
        except (ValueError, TypeError, KeyError):
            raise Failure(LABELS["repair-needed"], state="repair-needed") from None
        self.owners.fleet_apply = True
        if transaction["phase"] == "committing":
            received = self.state
            self.state, self.follow = transaction["state_after"], transaction["follow_after"]
            self.preserve_received(received)
            self.finish(transaction, transaction["undo_after"])
        else:
            if transaction["attempted"] and not session_ready():
                raise Failure(LABELS["repair-needed"], state="repair-needed")
            self.rollback(transaction)
        self.prune()

    def apply_pending(self, defer=False):
        result = {"ok": True, "changed": [], "applied": [], "pending": {}, "unchanged": [], "undo_token": None,
                  "notify": False}
        if defer or not session_ready():
            if not defer:
                for category in self.selected(None):
                    if self.state["pending"].get(category) == "pending":
                        self.state["pending"][category] = "waiting-sign-in"
            self.save()
            result["pending"] = dict(self.state["pending"])
            return result
        self.owners.fleet_apply = True
        self.recover()
        self.prune()
        self.refresh(None)  # Give a genuine unseen local edit a revision before selecting the received winner.
        before, targets, changed, unchanged, eligible, extra = {}, {}, [], [], [], {}
        for category in CATEGORIES:
            record = self.state["records"].get(category)
            if not self.follow["follow"][category] or not record or category in self.state["incompatible"]:
                continue
            if self.state["applied"].get(category) == list(schema.order(record)):
                continue
            try:
                local = self.owners.export(category)
                if local != record["payload"]:
                    self.owners.preflight(category, record["payload"])
                    changed.append(category)
                    before[category], targets[category] = local, record["payload"]
                    if category == "power-profiles":
                        mode = (self.owners.power_info or {}).get("profile")
                        if mode in schema.MODES and mode:
                            extra["power_mode"] = mode
                else:
                    unchanged.append(category)
                eligible.append(category)
                self.state["availability"][category] = {"available": True, "state": "same"}
            except Failure as ex:
                self.state["pending"][category] = ex.state
                self.state["availability"][category] = {"available": False, "state": ex.state}
        self.recheck_context()
        eligible = [c for c in eligible if c in self.state["records"]]
        changed = [c for c in changed if c in eligible]
        before = {c: before[c] for c in changed}
        targets = {c: targets[c] for c in changed}
        unchanged = [c for c in unchanged if c in eligible]
        transaction = self.begin("apply", before, targets, extra) if changed else None
        if transaction:
            try:
                for category in changed:
                    transaction["attempted"].append(category)
                    self.store.write("transaction", transaction)
                    self.owners.apply(category, targets[category])
                    if self.owners.export(category) != targets[category]:
                        raise Failure("The settings didn't match after application.")
            except Failure:
                try:
                    self.rollback(transaction)
                except Failure:
                    self.store.log("failed", "", changed,
                                   "The settings did not match after application, and putting them back did not finish.")
                    raise
                for category in changed:
                    self.state["pending"][category] = "error"
                self.save()
                self.store.log("failed", "", changed,
                               "The settings did not match after application, so they were put back.")
                result.update(ok=False, pending=dict(self.state["pending"]))
                return result
        for category in eligible:
            record = self.state["records"][category]
            self.state["applied"][category] = list(schema.order(record))
            self.state["observations"][category] = record["payload"]
            self.state["pending"].pop(category, None)
        if transaction:
            token = secrets.token_urlsafe(24)
            snapshot = {"schema": 1, "token": token, "before": before, "extra": extra}
            self.state["notes"] = dict(self.owners.notes)
            self.finish(transaction, snapshot)
            writers = {}
            for category in changed:
                writers.setdefault(self.state["records"][category]["writer"], []).append(category)
            for writer, categories in writers.items():
                self.store.log("applied", writer, categories)
            result.update(undo_token=token, notify=True)
        else:
            self.save()
        result.update(changed=changed, applied=eligible, unchanged=unchanged, pending=dict(self.state["pending"]))
        if self.owners.notes:
            result["notes"] = dict(self.owners.notes)
        return result

    def undo(self, token):
        snapshot = self.store.read("undo")
        transaction = self.store.read("transaction")
        try:
            validate_snapshot(snapshot)
            validate_transaction(transaction)
        except (ValueError, TypeError, KeyError):
            raise Failure(LABELS["repair-needed"], state="repair-needed") from None
        if transaction and transaction.get("phase") == "committing":
            snapshot = transaction.get("undo_after")
        if token is not None and (not snapshot or token != snapshot.get("token")):
            raise Failure("That Undo is no longer available. Only the latest change can be undone.", 2)
        self.owners.fleet_apply = True
        self.recover()
        snapshot = self.store.read("undo")
        if not isinstance(snapshot, dict) or (token is not None and token != snapshot.get("token")):
            raise Failure("That Undo is no longer available. Only the latest change can be undone.", 2)
        try:
            validate_snapshot(snapshot)
        except (ValueError, TypeError, KeyError):
            raise Failure(LABELS["repair-needed"], state="repair-needed") from None
        if not session_ready():
            raise Failure("Sign in to this account's desktop before using Undo.", state="waiting-sign-in")
        before, current_extra = {}, {}
        categories = [c for c in CATEGORIES if c in snapshot["before"]]
        for category in categories:
            before[category] = self.owners.export(category)
            self.owners.preflight(category, snapshot["before"][category])
            if category == "power-profiles":
                mode = (self.owners.power_info or {}).get("profile")
                if mode in schema.MODES and mode:
                    current_extra["power_mode"] = mode
        transaction = self.begin("undo", before, snapshot["before"], current_extra)
        try:
            for category in reversed(categories):
                transaction["attempted"].append(category)
                self.store.write("transaction", transaction)
                self.owners.restore(category, snapshot["before"][category], snapshot["extra"])
                if self.owners.export(category) != snapshot["before"][category]:
                    raise Failure()
        except Failure:
            self.rollback(transaction)
            raise Failure("The change couldn't be undone. Your current settings were restored.") from None
        for category in categories:
            self.follow["follow"][category] = False
            self.state["observations"][category] = snapshot["before"][category]
            self.state["pending"].pop(category, None)
            self.state["incompatible"].pop(category, None)
            self.state["applied"].pop(category, None)
        self.finish(transaction, None)
        self.store.log("undone", "", categories)
        names = [schema.NAMES[c] for c in categories]
        joined = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
        # one singular name reads "is ... it"; a plural name (Notifications) or several read "are ... they"
        one = len(names) == 1 and categories[0] not in schema.PLURAL
        verb = "is" if one else "are"
        commands = " and ".join(f"`starchaser fleet settings follow {c} on`" for c in categories)
        follow_verb = "follows" if one else "follow"
        return (f"{joined} {verb} back the way {'it was' if one else 'they were'} and no longer {follow_verb} your other "
                f"computers. Turn {'it' if one else 'them'} back on with {commands}.")

    def set_follow(self, categories, enabled):
        self.recover()
        for category in categories:
            was = self.follow["follow"][category]
            if enabled and not was:
                # A fresh catch-up, never a cached record, decides what to apply after opting back in.
                for name in ("records", "incompatible", "pending", "applied"):
                    self.state[name].pop(category, None)
            if enabled and (not was or category not in self.state["observations"]):
                try:
                    self.state["observations"][category] = self.owners.export(category)
                    self.state["availability"][category] = {"available": True, "state": "same"}
                except Failure as ex:
                    self.state["observations"].pop(category, None)
                    self.state["availability"][category] = {"available": False, "state": ex.state}
            if not enabled:
                for name in ("records", "incompatible", "pending"):
                    self.state[name].pop(category, None)
            self.follow["follow"][category] = enabled
        self.save()
        self.store.write("follow", self.follow)  # All six switches change in one atomic replacement for match.
        if enabled:
            self.store.catch_up()
        return {"ok": True, "follow": self.follow["follow"], "catch_up": enabled}

    def status(self):
        categories = {}
        for category in CATEGORIES:
            active = self.follow["follow"][category]
            records = [self.state[name].get(category) for name in ("records", "incompatible")]
            accepted = max((r for r in records if r), key=schema.order, default=None)
            pending = self.state["pending"].get(category)
            availability = self.state["availability"].get(category, {"available": os.access(self.owners.bin / f"starchaser-{TOOLS[category]}", os.X_OK), "state": "same"})
            state = "off" if not active else pending or ("same" if accepted is None or self.state["applied"].get(category) == list(schema.order(accepted)) else "different")
            if active and not availability["available"] and not pending:
                state = availability["state"]
            categories[category] = {"follow": active, "accepted": list(schema.order(accepted)) if accepted else None,
                                    "applied": self.state["applied"].get(category), "pending": pending,
                                    "availability": availability, "state": state}
        undo = self.store.read("undo")
        transaction = self.store.read("transaction")
        try:
            validate_snapshot(undo)
            validate_transaction(transaction)
        except (ValueError, TypeError, KeyError):
            raise Failure(LABELS["repair-needed"], state="repair-needed") from None
        if transaction:
            for category in transaction.get("attempted", []):
                if category in categories:
                    categories[category]["state"] = "repair-needed"
        peers = {peer: self.state["peers"].get(peer, {"last_attempt": None, "last_successful_contact": None,
                                                      "result": None}) for peer in sorted(self.context["paired"])}
        return {"schema": 1, "user": self.user, "follow": self.follow["follow"], "categories": categories,
                "peers": peers, "undo": {"available": bool(undo), "token": undo.get("token") if undo else None,
                "categories": list(undo.get("before", {})) if undo else []},
                "transaction": {"state": "repair-needed", "phase": transaction.get("phase")} if transaction else None}


def parser():
    ap = CommandParser(prog="starchaser fleet settings", description=__doc__, allow_abbrev=False)
    sub = ap.add_subparsers(dest="command", required=True)
    export = sub.add_parser("export", allow_abbrev=False, help="Read portable published records",
                            formatter_class=RawDescriptionHelpFormatter,
                            description="Read saved records as JSON without reading current settings or contacting other computers. "
                                        "Only categories with Follow turned on include settings records.",
                            epilog="Local read:\n  starchaser fleet settings export --category look\n\n"
                                   "Deliberate sharing:\n  starchaser fleet settings follow look on\n"
                                   "  starchaser fleet settings export --publish --category look")
    mode = export.add_mutually_exclusive_group()
    mode.add_argument("--refresh", action="store_true",
                      help="Read current settings for followed categories; changes since the last reading become records available to paired fleet computers")
    mode.add_argument("--publish", action="store_true",
                      help="Make current settings available to paired fleet computers, even on the first reading; requires Follow on for every selected category")
    export.add_argument("--category", choices=CATEGORIES, action="append",
                        help="Select a category; repeat for several. If omitted, select all categories")
    apply = sub.add_parser("apply", allow_abbrev=False, help="Accept settings or apply pending settings")
    source = apply.add_mutually_exclusive_group(required=True)
    source.add_argument("--stdin", action="store_true", help="the settings to accept, as JSON on the standard input")
    source.add_argument("--pending", action="store_true", help="the settings saved earlier, waiting to be applied")
    apply.add_argument("--defer", action="store_true", help="save the settings now and put them on later (--stdin only)")
    undo = sub.add_parser("undo", allow_abbrev=False, help="Restore the latest apply and turn its Follow switches off")
    undo.add_argument("--token", help="the token from status naming which apply to restore")
    status = sub.add_parser("status", allow_abbrev=False, help="Show Follow and application state")
    status.add_argument("--json", action="store_true", help="print JSON instead of text")
    sub.add_parser("report", allow_abbrev=False, help="Read status and recent local activity as JSON")
    follow = sub.add_parser("follow", allow_abbrev=False, help="Change one local Follow switch")
    follow.add_argument("category", choices=CATEGORIES, help="which settings to follow")
    follow.add_argument("value", choices=("on", "off"), help="on to follow them, off to stop")
    match = sub.add_parser("match", allow_abbrev=False, help="Turn all Follow switches on and request catch-up",
                           description="Turn all six Follow switches on and ask for a catch-up, so this computer starts "
                                       "taking on the settings of the computers it follows. Use follow <category> off to turn one back off.")
    match.add_argument("--managed", action="store_true", help="Run for Mission Control: refused unless this computer lets the fleet manage it")
    return ap


def report():
    store = None
    try:
        user = check_user()
        store = Store()
        context = membership()
        if context["user"] != user:
            raise Failure("The computer list belongs to a different account.", 4, "refused")
        engine = Engine(store, Owners(), user, context, read_only=True)
        status = engine.status()
        # Other computers read this report; the undo token stays on this computer.
        if isinstance(status.get("undo"), dict):
            status["undo"] = {k: v for k, v in status["undo"].items() if k != "token"}
        return {"schema": 1, "ok": True, "self": context["self"], "status": status, "activity": store.read_log(40),
                "manageConsent": manage_allowed()}
    except (Failure, OSError, ValueError, TypeError, KeyError) as ex:
        return {"schema": 1, "ok": False, "state": ex.state if isinstance(ex, Failure) else "refused",
                "activity": store.read_log(40) if store is not None else [], "manageConsent": manage_allowed()}
    finally:
        if store is not None:
            try:
                store.close()
            except (OSError, ValueError):
                pass


def log_refused_envelope(envelope, failure, store=None):
    if failure.state not in ("refused", "needs-update"):
        return
    own_store = store is None
    try:
        if own_store:
            store = Store()
        source = envelope.get("from") if isinstance(envelope, dict) else ""
        store.log("refused", source, [], str(failure))
    except (Failure, OSError, ValueError, TypeError):
        pass
    finally:
        if own_store and store is not None:
            try:
                store.close()
            except (OSError, ValueError):
                pass


def run(argv, raw=None):
    ap = parser()
    # A URL-safe random token may start with a dash; it is a value, not another option.
    if len(argv) == 3 and argv[:2] == ["undo", "--token"]:
        argv = ["undo", "--token=" + argv[2]]
    args = ap.parse_args(argv)
    if args.command == "export" and args.category and len(set(args.category)) != len(args.category):
        ap.error("Each category can be selected only once.")
    if args.command == "apply" and args.pending and args.defer:
        ap.error("--defer can only be used with --stdin.")
    if args.command == "report":
        return report()
    if getattr(args, "managed", False) and not manage_allowed():
        raise Failure(NOT_ALLOWED, 4, "refused")
    user = check_user()
    envelope = None
    if args.command == "apply" and args.stdin:
        try:
            envelope = schema.loads(raw if raw is not None else sys.stdin.buffer.read(schema.MAX_BYTES + 1))
        except (ValueError, TypeError):
            raise Failure("The received settings aren't valid JSON.", 2) from None
    context = membership()
    if context["user"] != user:
        raise Failure("The computer list belongs to a different account.", 4, "refused")
    if envelope is not None:
        try:
            validate_envelope(envelope, user, context)
        except Failure as ex:
            log_refused_envelope(envelope, ex)
            raise
    store = Store()
    try:
        # Consent may have gone off while this waited for the lock.
        if getattr(args, "managed", False) and not manage_allowed():
            raise Failure(NOT_ALLOWED, 4, "refused")
        if envelope is not None:
            # A removal may have landed while this receive waited for the lock.
            context = membership()
            if context["user"] != user:
                raise Failure("The computer list belongs to a different account.", 4, "refused")
            try:
                validate_envelope(envelope, user, context)
            except Failure as ex:
                log_refused_envelope(envelope, ex, store)
                raise
        engine = Engine(store, Owners(), user, context, read_only=args.command == "status")
        if args.command == "status":
            result = engine.status()
            return result if args.json else "\n".join(f"{schema.NAMES[c]}: {LABELS[result['categories'][c]['state']]}" for c in CATEGORIES)
        if args.command == "follow":
            return engine.set_follow([args.category], args.value == "on")
        if args.command == "match":
            return engine.set_follow(CATEGORIES, True)
        if args.command == "undo":
            return engine.undo(args.token)
        if args.command == "export":
            if args.publish and any(not engine.follow["follow"][c] for c in (args.category or CATEGORIES)):
                raise Failure("Turn Follow on for each selected category before publishing it.", 2)
            if args.refresh or args.publish:
                engine.recover()
                engine.refresh(args.category, publish=args.publish)
            return engine.envelope(args.category)
        # A forced receive must not run category exporters, preflight, recovery, or setters.
        if envelope is not None:
            if not args.defer and session_ready():
                engine.recover()
            engine.merge(envelope["records"])
        result = engine.apply_pending(defer=args.defer)
        result.update(engine.envelope())
        pending = result["pending"]
        state = "off" if not any(engine.follow["follow"].values()) else "same"
        if pending:
            state = next((s for s in ("repair-needed", "needs-update", "error", "unavailable", "waiting-sign-in", "pending", "revision-limit") if s in pending.values()), "pending")
        result["result"] = {"state": state, "categories": pending}
        if state == "needs-update":
            result["result"]["older"] = "this"
        return result
    finally:
        store.close()


def main(argv):
    try:
        result = run(argv)
        if isinstance(result, str):
            print(result)
        else:
            sys.stdout.flush()
            sys.stdout.buffer.write((json.dumps(result, sort_keys=True, ensure_ascii=argv[:1] == ["report"]) + "\n").encode("utf-8"))
            sys.stdout.buffer.flush()
        return 0 if argv[:1] == ["report"] or not isinstance(result, dict) or result.get("ok", True) else 1
    except Failure as ex:
        print(str(ex), file=sys.stderr)
        result = {"ok": False, "error": str(ex), "result": {"state": ex.state}}
        if ex.state == "needs-update":
            result["result"]["older"] = "this"
        print(json.dumps(result))
        return ex.code
    except (OSError, ValueError, TypeError):
        print("Settings state could not be read or saved.", file=sys.stderr)
        print(json.dumps({"ok": False, "result": {"state": "error"}}))
        return 1


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