#!/usr/bin/env python3
"""starchaser-mission-control-admin: the root steps of Mission Control (Settings > Mission Control). Root-owned in
/usr/local/lib/starchaser/, run through pkexec (polkit action org.starchaser.mission-control, auth_admin_keep), or
directly by root (the desktop setup, the pacman hook). Every answer is one JSON object on stdout. Nothing is passed
to a shell; every input is checked here.

    web-on                  open Mission Control to other devices. With the firewall off, any device on a private
                            network this computer joins, including public Wi-Fi, can reach the sign-in page.
                            The socket turns away addresses outside private networks. Writes /etc/cockpit/cockpit.conf,
                            the 9090 listener (30-starchaser-web.conf),
                            when the firewall is on, adds a narrow allow (tcp 9090 on networks you trust, plus
                            Tailscale and your VPN as the fleet's switches say, never Public ones) appended
                            after the person's own rules, enables the socket, then checks for every zone, IPv4 and
                            IPv6, who can reach it ("reach"), naming any rule of the person's that opens it wider
    web-off                 close it again: the 9090 listener and only the firewall rule web-on added go away
    tailscale on|off        the fleet's Tailscale switch (starchaser-admin fleet-networks tailscale): devices on
                            Tailscale may reach Mission Control, and the rest of the fleet's switches, or not
    local-signin on|off     the sign-in window: a listener on 127.0.0.1:9091 only, for this computer's own browser
    cert-install <cert> [<key>]   use a certificate from your own certificate authority (PEM; the key may be in
                            the same file): checked (matches its key, not expired, made for a server), then put at
                            /etc/cockpit/ws-certs.d/2-starchaser.cert/.key
    cert-check <cert> [<key>]   the same checks as cert-install, changing nothing (no root needed): Settings asks
                            this first, so a mistyped path or the wrong file is said before the password box
    cert-remove             go back to the web server's own certificate
    refresh                 after an update: the conf and drop-ins written again for what is on (nothing new on)
    sync-overrides          hide the upstream pages: an override package (priority 100) for each one installed,
                            whose only page sends you to Mission Control. The shell's override carries the
                            "bridges" list admin rights need, copied from the upstream shell; if the effective
                            list (cockpit-bridge --bridges) differs afterward, the shell override is removed
                            again rather than break admin rights. Run by the setup and the pacman hook.
    status                  what is on (no root needed)

Two layers keep the internet out (DESIGN.md 4.2): the socket's own IPAddressAllow (10-starchaser.conf, systemd's
eBPF filter, with or without the firewall) and, when the firewall is on, its rule for networks you trust.
"""
import datetime
import importlib.machinery
import importlib.util
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

HERE = os.path.dirname(os.path.realpath(__file__))
STATE = Path("/etc/starchaser/mission-control.json")
SHARE = Path("/usr/local/share/starchaser/missioncontrol")
CONF_SRC = SHARE / "cockpit.conf"
OVERRIDE_PAGE = SHARE / "overrides" / "index.html"
CONF = Path("/etc/cockpit/cockpit.conf")
DROPIN = Path("/etc/systemd/system/cockpit.socket.d")
WEB_DROPIN = DROPIN / "30-starchaser-web.conf"
TS_DROPIN = DROPIN / "40-starchaser-tailscale.conf"
CERTS = Path("/etc/cockpit/ws-certs.d")
CERT = CERTS / "2-starchaser.cert"
KEY = CERTS / "2-starchaser.key"
UPSTREAM = Path("/usr/share/cockpit")
OURS = Path("/usr/local/share/cockpit")
MARK = ".starchaser-override"              # in each override folder we made (never touch one we didn't)
# never hidden: the JS API, the static files and branding, and our own package
KEEP = {"base1", "static", "branding", "issue", "missioncontrol"}
PORT = 9090
APP = "mission-control"
RULE_NAME = "Mission Control from other devices"
HOME_ZONES = ("trusted",)
TS_ZONE = "tailscale"
TS_RANGES = "100.64.0.0/10 fd7a:115c:a1e3::/48"

_fw = None
_admin = None


def fw():
    global _fw
    if _fw is None:
        sys.path.insert(0, HERE)
        import firewall as f  # the engine, root-owned beside this file
        _fw = f
    return _fw


def access():
    """The engine's one answer for how the firewall already treats an app (firewall_access.py, beside this file)."""
    fw()
    import firewall_access
    return firewall_access


def admin():
    """starchaser-admin beside this file: its lock (one firewall change at a time) and its record of a change
    waiting for Keep."""
    global _admin
    if _admin is None:
        path = os.path.join(HERE, "starchaser-admin")
        loader = importlib.machinery.SourceFileLoader("starchaser_admin", path)
        spec = importlib.util.spec_from_loader("starchaser_admin", loader)
        _admin = importlib.util.module_from_spec(spec)
        loader.exec_module(_admin)
    return _admin


def sh(*cmd, timeout=60, input=None) -> subprocess.CompletedProcess:
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, input=input)
    except (OSError, subprocess.TimeoutExpired) as e:
        return subprocess.CompletedProcess(cmd, 127, "", str(e))


def write_atomic(path: Path, text: str, mode: int = 0o644) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + ".", suffix=".tmp")
    try:
        with os.fdopen(fd, "w") as fh:
            fh.write(text)
            fh.flush()
            os.fsync(fh.fileno())
        os.chmod(tmp, mode)
        os.replace(tmp, path)
    except BaseException:
        Path(tmp).unlink(missing_ok=True)
        raise


def load_state() -> dict:
    try:
        st = json.loads(STATE.read_text())
        return st if isinstance(st, dict) else {}
    except (OSError, ValueError):
        return {}


def save_state(st: dict) -> None:
    write_atomic(STATE, json.dumps(st, indent=1) + "\n")


# ---------------------------------------------------------------------------------------------------------- socket

def write_conf() -> None:
    write_atomic(CONF, CONF_SRC.read_text())


def socket_files(st: dict) -> None:
    if st.get("web"):
        write_atomic(WEB_DROPIN, "# Mission Control: open to other devices (Settings > Mission Control).\n"
                                 f"[Socket]\nListenStream={PORT}\n")
    else:
        WEB_DROPIN.unlink(missing_ok=True)
    if st.get("web") and tailscale_on():
        write_atomic(TS_DROPIN, "# Mission Control: devices on Tailscale may reach it too (its own switch).\n"
                                f"[Socket]\nIPAddressAllow={TS_RANGES}\n")
    else:
        TS_DROPIN.unlink(missing_ok=True)


def apply_socket(st: dict) -> str:
    """Make the socket match the state: listening (9091 always while enabled, 9090 with web access) or off.
    Returns "" or what went wrong, in plain words."""
    socket_files(st)
    want = bool(st.get("web") or st.get("localSignin"))
    if want:
        write_conf()
    else:
        CONF.unlink(missing_ok=True)
    sh("systemctl", "daemon-reload")
    if want:
        r = sh("systemctl", "enable", "cockpit.socket")
        if r.returncode != 0:
            return "Couldn't turn on the Mission Control web service."
        # a running web server keeps the old listeners and settings: start over (open sessions end)
        sh("systemctl", "stop", "cockpit.service")
        r = sh("systemctl", "restart", "cockpit.socket")
        if r.returncode != 0:
            return "The Mission Control web service didn't start."
    else:
        sh("systemctl", "disable", "--now", "cockpit.socket")
        sh("systemctl", "stop", "cockpit.service")
    return ""


def listening() -> list:
    """The addresses the socket listens on now (systemctl show Listen). Listen names the configured addresses even
    while the socket is stopped, so a stopped socket listens on nothing (the sign-in window would open a dead page)."""
    if sh("systemctl", "is-active", "cockpit.socket").stdout.strip() != "active":
        return []
    out = sh("systemctl", "show", "-p", "Listen", "--value", "cockpit.socket").stdout
    return [x.split(" (")[0] for x in out.strip().split("\n") if x.strip()]


# -------------------------------------------------------------------------------------------------------- firewall

def zones(st: dict) -> tuple:
    """The fleet's networks (decided 2026-10-09: Mission Control from a browser on your own network and trusted ones
    such as Tailscale or another VPN, never Public). st is kept for the callers' shape; the switches are the fleet's."""
    return tuple(fw().fleet_zones())


def tailscale_on() -> bool:
    return bool(fw().fleet_networks().get("tailscale"))


def ports():
    return [("tcp", PORT)]


def standing(policy: dict, zs: tuple, cat: dict, live: dict) -> str:
    """How the firewall treats tcp 9090 on these zones: "open" / "limited" / "off" (a rule of the person's
    decides), or "none" (add our allow at the end of the list). firewall_access.standing() owns the decision
    table; Mission Control's catalog entry and the older web-console entry both mean this app, and our own rule
    never counts as the person's."""
    return access().standing(fw(), policy, zs, (APP, "cockpit"), ports(), cat, live,
                             lambda p: add_allow(p, zs, "mc-trial"), skip=(load_state().get("ruleId"),))


def add_allow(policy: dict, zs: tuple, rid: str = "") -> dict:
    rules = list(policy.get("rules") or [])
    rule = access().basic_allow(rid or access().next_id(policy, APP), RULE_NAME, APP, zs)
    return dict(policy, rules=rules + [rule])


def ours(r: dict, rid: str) -> bool:
    """Our rule, still as we added it (the person didn't take it over by editing it)."""
    return r.get("id") == rid and r.get("app") == APP and r.get("managed") == "basic" and r.get("dir") == "in"


def _commit(adm, policy: dict, summary: str):
    """Validate, load, snapshot; keeps a change waiting for Keep consistent the way remote desktop does."""
    f = fw()
    try:
        clean = f.validate(policy)
    except f.PolicyError as e:
        return str(e)
    return access().load(f, adm, clean, summary, adm.waiting())


def firewall_policy():
    f = fw()
    try:
        return json.loads(f.POLICY.read_text())
    except (OSError, ValueError):
        return None


def firewall_on() -> bool:
    p = firewall_policy()
    return bool(p and p.get("enabled"))


def fw_allow(st: dict) -> dict:
    """Our allow on home networks (+ Tailscale): added after every rule of the person's when nothing of theirs
    concerns port 9090; an existing rule of ours is widened or narrowed to the zones wanted now."""
    adm = admin()
    f = fw()
    with adm.locked():
        policy = firewall_policy()
        if not policy or not policy.get("enabled"):
            return {"ok": True, "changed": False, "standing": "open-no-firewall", "ruleId": st.get("ruleId", "")}
        try:
            policy = f.validate(policy)
        except f.PolicyError as e:
            return {"ok": False, "why": "policy", "errors": str(e)}
        cat, live = f.catalog(), f.listening()
        zs = zones(st)
        rid = st.get("ruleId", "")
        rules = list(policy.get("rules") or [])
        mine = [r for r in rules if ours(r, rid)]
        if mine:
            if sorted(mine[0].get("zones") or []) == sorted(zs):
                return {"ok": True, "changed": False, "ruleId": rid}
            rules = [dict(r, zones=list(zs)) if ours(r, rid) else r for r in rules]
            err = _commit(adm, dict(policy, rules=rules), "Mission Control: which networks may reach it")
            return {"ok": not err, "changed": not err, "ruleId": rid, **({"errors": err} if err else {})}
        stand = standing(policy, zs, cat, live)
        if stand in ("open", "limited", "off"):
            return {"ok": True, "changed": False, "standing": stand, "ruleId": ""}
        new = add_allow(policy, zs)
        rid = new["rules"][-1]["id"]
        err = _commit(adm, new, "Mission Control allowed from other devices on home networks")
        if err:
            return {"ok": False, "errors": err}
        return {"ok": True, "changed": True, "ruleId": rid}


def fw_remove(st: dict) -> dict:
    rid = st.get("ruleId", "")
    if not rid:
        return {"ok": True, "changed": False}
    adm = admin()
    with adm.locked():
        policy = firewall_policy()
        if not policy:
            return {"ok": True, "changed": False}
        rules = list(policy.get("rules") or [])
        keep = [r for r in rules if not ours(r, rid)]
        if len(keep) == len(rules):
            # gone already, or edited by the person (then it's theirs now and stays)
            edited = any(r.get("id") == rid for r in rules)
            return {"ok": True, "changed": False, **({"kept": "edited"} if edited else {})}
        if not policy.get("enabled"):
            # firewall off: change the saved policy only, it's used the next time the firewall turns on
            try:
                fw().write_atomic(fw().POLICY, json.dumps(dict(policy, rules=keep), indent=1) + "\n")
            except OSError as e:
                return {"ok": False, "errors": str(e)}
            return {"ok": True, "changed": True}
        err = _commit(adm, dict(policy, rules=keep), "Mission Control closed to other devices")
        return {"ok": not err, "changed": not err, **({"errors": err} if err else {})}


def reach() -> dict:
    """Who can reach tcp 9090, per zone and address family, by the firewall's own first-match walk; and the
    person's rules that open it outside our zones (named, so Settings can say which)."""
    f = fw()
    policy = firewall_policy()
    if not policy:
        return {"firewall": "none"}
    if not policy.get("enabled"):
        return {"firewall": "off"}
    try:
        policy = f.validate(policy)
    except f.PolicyError:
        return {"firewall": "unreadable"}
    cat, live = f.catalog(), f.listening()
    st = load_state()
    names = {r.get("id"): r.get("name") or r.get("id") for r in policy.get("rules") or []}
    out, wider = {}, set()
    for z in f.ZONES:
        out[z], deciders = access().port_reach(f, policy, z, "tcp", PORT, cat, live)
        if z not in zones(st):
            wider |= deciders - {st.get("ruleId")}
    return {"firewall": "on", "zones": out, "wider": sorted(names.get(i, i) for i in wider)}


# ---------------------------------------------------------------------------------------------------- commands

def web_on() -> dict:
    st = load_state()
    sync = sync_overrides()
    r = fw_allow(dict(st, web=True))
    if not r.get("ok"):
        return {"ok": False, "why": r.get("why", "firewall"),
                "errors": r.get("errors") or "Couldn't add the firewall rule for Mission Control."}
    st.update(web=True, ruleId=r.get("ruleId") or st.get("ruleId", ""))
    if r.get("standing") and r["standing"] != "open-no-firewall":
        st["ruleId"] = ""                      # a rule of the person's decides: nothing of ours to remove later
    save_state(st)
    err = apply_socket(st)
    res = {"ok": not err, "web": True, "standing": r.get("standing", "added" if r.get("changed") else "kept"),
           "listen": listening(), "reach": reach(), "overrides": sync}
    if err:
        res["errors"] = err
    return res


def web_off() -> dict:
    st = load_state()
    r = fw_remove(st)
    st.update(web=False)
    if r.get("ok"):
        st.pop("ruleId", None)
    save_state(st)
    err = apply_socket(st)
    res = {"ok": not err and r.get("ok", False), "web": False, "listen": listening(), "firewall": r}
    if err or not r.get("ok"):
        res["errors"] = err or r.get("errors") or "Couldn't remove the firewall rule."
    return res


def tailscale(on: bool) -> dict:
    """The fleet's Tailscale switch, from Settings > Mission Control: one switch for the whole fleet, so starchaser-admin
    moves every fleet rule (this one's too) and writes the socket's filter again (refresh)."""
    st = load_state()
    if on and st.get("web") and not firewall_on():
        return {"ok": False, "why": "firewall-off",
                "errors": "Turn on the firewall first, so only your own devices can reach Mission Control."}
    r = sh(sys.executable, os.path.join(HERE, "starchaser-admin"), "fleet-networks", "tailscale", "on" if on else "off",
           timeout=120)
    try:
        out = json.loads(r.stdout.strip().splitlines()[-1])
    except (ValueError, IndexError):
        out = {"ok": False, "errors": (r.stderr or "").strip()[-300:] or "Couldn't change the Tailscale switch."}
    if not out.get("ok"):
        return {"ok": False, "errors": out.get("errors") or "Couldn't change the firewall rule."}
    if st.get("web") and firewall_on():
        r2 = fw_allow(st)                     # our rule follows already; this adds it if the person's rule went away
        if r2.get("ruleId") and r2["ruleId"] != st.get("ruleId"):
            st["ruleId"] = r2["ruleId"]
            save_state(st)
    res = {"ok": True, "tailscale": on}
    if st.get("web"):
        res.update(listen=listening(), reach=reach())
    return res


def local_signin(on: bool) -> dict:
    st = load_state()
    st["localSignin"] = on
    save_state(st)
    if on:
        sync_overrides()
    err = apply_socket(st)
    return {"ok": not err, "localSignin": on, "listen": listening(), **({"errors": err} if err else {})}


PEM_CERT = re.compile(r"-----BEGIN CERTIFICATE-----[A-Za-z0-9+/=\s]+?-----END CERTIFICATE-----")
PEM_KEY = re.compile(r"-----BEGIN (?:RSA |EC )?PRIVATE KEY-----[A-Za-z0-9+/=\s]+?-----END (?:RSA |EC )?PRIVATE KEY-----")


def _read_small(path: str) -> str:
    p = Path(path)
    if not p.is_file() or p.stat().st_size > 256 * 1024:
        raise ValueError("not a certificate file")
    return p.read_text(errors="replace")


def _started(pem: Path) -> bool:
    """notBefore is in the past (openssl -checkend only looks at the end date)."""
    out = sh("openssl", "x509", "-in", str(pem), "-noout", "-startdate").stdout.strip().split("=", 1)[-1]
    try:
        start = datetime.datetime.strptime(" ".join(out.split()), "%b %d %H:%M:%S %Y GMT").replace(tzinfo=datetime.timezone.utc)
    except ValueError:
        return False
    return start <= datetime.datetime.now(datetime.timezone.utc)


def cert_pair(cert_path: str, key_path: str = "") -> dict:
    """The checks cert-install makes, changing nothing: an "errors" answer, or the certificates, key, end date and names."""
    if not Path(cert_path).exists():
        return {"ok": False, "errors": f"There is no file at {cert_path}. Check the name and the folder."}
    if key_path and not Path(key_path).exists():
        return {"ok": False, "errors": "The private key is missing. Choose the key file that was made with the request."}
    try:
        text = _read_small(cert_path)
        ktext = _read_small(key_path) if key_path else text
    except (OSError, ValueError):
        return {"ok": False, "errors": "That file can't be used: it isn't a certificate."}
    certs = PEM_CERT.findall(text)
    keys = PEM_KEY.findall(ktext)
    if not certs:
        return {"ok": False, "errors": "That file has no certificate in it."}
    if len(keys) != 1:
        return {"ok": False, "errors": "The private key is missing. Choose the key file that was made with the request."}
    leaf = certs[0]
    with tempfile.TemporaryDirectory() as d:
        lf, kf = Path(d) / "leaf.pem", Path(d) / "key.pem"
        lf.write_text(leaf + "\n")
        os.chmod(d, 0o700)
        kf.write_text(keys[0] + "\n")
        if sh("openssl", "x509", "-in", str(lf), "-noout", "-checkend", "0").returncode != 0 or not _started(lf):
            return {"ok": False, "errors": "That certificate has expired (or isn't valid yet)."}
        a = sh("openssl", "x509", "-in", str(lf), "-noout", "-pubkey").stdout
        b = sh("openssl", "pkey", "-in", str(kf), "-pubout").stdout
        if not a or a != b:
            return {"ok": False, "errors": "The certificate and the key don't belong together."}
        eku = sh("openssl", "x509", "-in", str(lf), "-noout", "-ext", "extendedKeyUsage").stdout
        if eku.strip() and "TLS Web Server Authentication" not in eku:
            return {"ok": False, "errors": "That certificate isn't made for a web server."}
        end = sh("openssl", "x509", "-in", str(lf), "-noout", "-enddate").stdout.strip().split("=", 1)[-1]
        names = sh("openssl", "x509", "-in", str(lf), "-noout", "-ext", "subjectAltName").stdout
    return {"ok": True, "certs": certs, "key": keys[0], "until": end,
            "names": ", ".join(s.strip() for s in names.split("\n")[1:] if s.strip())}


def cert_check(cert_path: str, key_path: str = "") -> dict:
    pair = cert_pair(cert_path, key_path)
    return {k: v for k, v in pair.items() if k not in ("certs", "key")}


def cert_install(cert_path: str, key_path: str = "") -> dict:
    pair = cert_pair(cert_path, key_path)
    if not pair["ok"]:
        return pair
    certs, key = pair["certs"], pair["key"]
    CERTS.mkdir(parents=True, exist_ok=True)
    # keep the pair in use now, so a certificate the web service refuses puts it back ("nothing changed" is true)
    old = {p: p.read_bytes() for p in (CERT, KEY) if p.is_file()}
    write_atomic(CERT, "\n".join(certs) + "\n", 0o644)
    write_atomic(KEY, key + "\n", 0o640)
    chk = sh("/usr/lib/cockpit/cockpit-certificate-ensure", "--check")
    if chk.returncode != 0 or "2-starchaser.cert" not in (chk.stdout + chk.stderr):
        for p, mode in ((CERT, 0o644), (KEY, 0o640)):
            if p in old:
                write_atomic(p, old[p].decode(errors="replace"), mode)
            else:
                p.unlink(missing_ok=True)
        return {"ok": False, "errors": "The web service wouldn't use that certificate, so nothing changed."}
    sh("systemctl", "try-restart", "cockpit.service")
    return {"ok": True, "until": pair["until"], "names": pair["names"]}


def cert_remove() -> dict:
    CERT.unlink(missing_ok=True)
    KEY.unlink(missing_ok=True)
    sh("systemctl", "try-restart", "cockpit.service")
    return {"ok": True}


def _bridges() -> str:
    r = sh("cockpit-bridge", "--bridges", timeout=30)
    if r.returncode != 0:
        return ""
    try:
        return json.dumps(json.loads(r.stdout), sort_keys=True)
    except ValueError:
        return ""


def _override_manifest(name: str, extra: dict = None) -> str:
    m = {"name": name, "priority": 100,
         "content-security-policy": "default-src 'self'; frame-ancestors 'none'; base-uri 'none'"}
    m.update(extra or {})
    return json.dumps(m, indent=2) + "\n"


def _place_override(folder: str, manifest: str) -> None:
    d = OURS / folder
    d.mkdir(parents=True, exist_ok=True)
    (d / MARK).write_text("made by starchaser-mission-control-admin sync-overrides\n")
    write_atomic(d / "manifest.json", manifest)
    shutil.copyfile(OVERRIDE_PAGE, d / "index.html")
    os.chmod(d / "index.html", 0o644)


def _remove_override(folder: str) -> None:
    d = OURS / folder
    if (d / MARK).is_file():
        shutil.rmtree(d, ignore_errors=True)


def sync_overrides() -> dict:
    """Hide every upstream page package installed here behind an override of the same name that only leads to
    Mission Control. The shell's carries the upstream "bridges" (and only that key), checked with
    cockpit-bridge --bridges before and after."""
    if not OVERRIDE_PAGE.is_file():
        return {"ok": False, "errors": "Mission Control isn't installed completely (its override page is missing)."}
    made, skipped, removed = [], [], []
    seen = set()
    upstream = {}
    for mf in sorted(UPSTREAM.glob("*/manifest.json")):
        folder = mf.parent.name
        if folder in KEEP:
            continue
        try:
            m = json.loads(mf.read_text())
        except (OSError, ValueError):
            continue
        if isinstance(m, dict):
            upstream[folder] = m
    for folder, m in upstream.items():
        if folder == "shell":
            continue
        name = m.get("name") or folder
        if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", name):
            continue
        seen.add(folder)
        if "bridges" in m:
            skipped.append(folder)                 # carries admin methods: never hidden
            _remove_override(folder)
            continue
        if (OURS / folder).exists() and not (OURS / folder / MARK).is_file():
            skipped.append(folder)                 # someone else's package there: leave it
            continue
        _place_override(folder, _override_manifest(name))
        made.append(folder)
    shell = {"done": False}
    if "shell" in upstream:
        seen.add("shell")
        _remove_override("shell")
        before = _bridges()
        bridges = upstream["shell"].get("bridges")
        if before and isinstance(bridges, list):
            _place_override("shell", _override_manifest("shell", {"bridges": bridges}))
            after = _bridges()
            if after == before:
                shell = {"done": True}
                made.append("shell")
            else:
                _remove_override("shell")
                shell = {"done": False, "why": "admin methods would change"}
        else:
            shell = {"done": False, "why": "no admin methods to copy" if before else "cockpit-bridge didn't answer"}
    for d in OURS.glob("*/" + MARK):
        if d.parent.name not in seen:
            _remove_override(d.parent.name)
            removed.append(d.parent.name)
    return {"ok": True, "made": made, "skipped": skipped, "removed": removed, "shell": shell}


def refresh() -> dict:
    """After an update or a setup run: the conf and drop-ins written again from the state (new template), the socket
    restarted only if something is on. Turns nothing on and changes no firewall rule."""
    st = load_state()
    if not (st.get("web") or st.get("localSignin")):
        # both off: make sure nothing listens, including a socket that was turned on before Mission Control was
        # installed (it would keep its old 9090 listener until stopped)
        socket_files(st)
        CONF.unlink(missing_ok=True)
        active = sh("systemctl", "is-active", "cockpit.socket").stdout.strip() == "active" \
            or sh("systemctl", "is-enabled", "cockpit.socket").stdout.strip() == "enabled" \
            or sh("systemctl", "is-active", "cockpit.service").stdout.strip() == "active"
        if active:
            err = apply_socket(st)
            return {"ok": not err, "changed": True, **({"errors": err} if err else {})}
        return {"ok": True, "changed": False}
    err = apply_socket(st)
    return {"ok": not err, "changed": True, **({"errors": err} if err else {})}


def status() -> dict:
    st = load_state()
    enabled = sh("systemctl", "is-enabled", "cockpit.socket").stdout.strip()
    return {"web": bool(st.get("web")), "tailscale": tailscale_on(), "localSignin": bool(st.get("localSignin")),
            "socket": enabled, "listen": listening(), "cert": CERT.is_file()}


USAGE = __doc__.strip()


PHONE_BRANDING = Path("/usr/share/cockpit/branding/starchaser")


def phone_share(certificate: str, url: str, token: str) -> dict:
    import phone_trust
    if not re.fullmatch(r"[0-9a-f]{64}", token):
        return {"ok": False, "errors": "The phone invitation isn't valid."}
    try:
        content = phone_trust.profile(certificate, url)
        directory = PHONE_BRANDING.resolve(strict=True)
        if directory.stat().st_uid != 0 or directory.stat().st_mode & 0o022:
            raise ValueError("The public certificate folder isn't protected. Update Starchaser first.")
        path = directory / ("phone-" + token + ".mobileconfig")
        with path.open("xb") as stream:
            stream.write(content)
        path.chmod(0o644)
        public_ca = directory / ("phone-" + token + ".crt")
        der = sh("openssl", "x509", "-in", certificate, "-outform", "PEM")
        if der.returncode:
            path.unlink(missing_ok=True)
            raise ValueError("The public certificate couldn't be shared.")
        public_ca.write_text(der.stdout)
        public_ca.chmod(0o644)
        result = sh("systemd-run", "--quiet", "--collect", "--unit=starchaser-phone-" + token[:16], "--on-active=10m",
                    sys.executable, os.path.realpath(__file__), "phone-stop", token)
        if result.returncode:
            path.unlink(missing_ok=True)
            public_ca.unlink(missing_ok=True)
            raise ValueError("The phone invitation couldn't be given an end time. Nothing was shared.")
        return {"ok": True, "url": url.rstrip("/") + "/static/phone-" + token + ".mobileconfig", "token": token, "certificateUrl": url.rstrip("/") + "/static/phone-" + token + ".crt"}
    except (ValueError, OSError) as error:
        return {"ok": False, "errors": str(error)}


def phone_stop(token: str) -> dict:
    if not re.fullmatch(r"[0-9a-f]{64}", token):
        return {"ok": False, "errors": "The phone invitation isn't valid."}
    (PHONE_BRANDING / ("phone-" + token + ".mobileconfig")).unlink(missing_ok=True)
    (PHONE_BRANDING / ("phone-" + token + ".crt")).unlink(missing_ok=True)
    return {"ok": True}


def main(argv: list) -> int:
    if argv[:1] in (["-h"], ["--help"], ["help"]) or any(a in ("-h", "--help") for a in argv[1:]):
        print(USAGE)
        return 0
    if argv == ["status"]:
        print(json.dumps(status()))
        return 0
    if argv == ["reach"] and os.geteuid() != 0:
        print(json.dumps({"ok": True, **reach()}))       # read-only; Settings asks without a password
        return 0
    if argv[:1] == ["cert-check"] and len(argv) in (2, 3):
        res = cert_check(*argv[1:])                      # read-only, as the person: their own files
        print(json.dumps(res))
        return 0 if res.get("ok") else 1
    # the request is checked before the pkexec refusal: a known command with the wrong words, or an unknown one,
    # is answered as that ("unknown" for a newer Settings asking an older helper), not as a missing permission
    cmd = argv[0] if argv else ""
    takes = {"phone-share": "a public certificate, private HTTPS URL and invitation token", "phone-stop": "an invitation token", "status": "no arguments", "reach": "no arguments", "web-on": "no arguments",
             "web-off": "no arguments", "tailscale": "'tailscale on' or 'tailscale off'",
             "local-signin": "'local-signin on' or 'local-signin off'",
             "cert-install": "a certificate file and an optional key file: 'cert-install <cert> [<key>]'",
             "cert-check": "a certificate file and an optional key file: 'cert-check <cert> [<key>]'",
             "cert-remove": "no arguments", "refresh": "no arguments", "sync-overrides": "no arguments"}
    shaped = ((cmd == "phone-share" and len(argv) == 4) or (cmd == "phone-stop" and len(argv) == 2) or cmd in ("web-on", "web-off", "cert-remove", "refresh", "sync-overrides", "reach") and len(argv) == 1
              or cmd in ("tailscale", "local-signin") and argv[1:] in (["on"], ["off"])
              or cmd == "cert-install" and len(argv) in (2, 3))
    if cmd not in takes:
        print(json.dumps({"ok": False, "errors": "unknown request", "unknown": True}))
        return 2
    if not shaped:
        print(json.dumps({"ok": False, "errors": f"{cmd} takes {takes[cmd]}."}))
        return 2
    if os.geteuid() != 0:
        print(json.dumps({"ok": False, "errors": "run through pkexec"}))
        return 1
    os.umask(0o022)
    if cmd == "phone-share":
        res = phone_share(*argv[1:])
    elif cmd == "phone-stop":
        res = phone_stop(argv[1])
    elif argv == ["web-on"]:
        res = web_on()
    elif argv == ["web-off"]:
        res = web_off()
    elif cmd == "tailscale" and argv[1:] in (["on"], ["off"]):
        res = tailscale(argv[1] == "on")
    elif cmd == "local-signin" and argv[1:] in (["on"], ["off"]):
        res = local_signin(argv[1] == "on")
    elif cmd == "cert-install" and len(argv) in (2, 3):
        res = cert_install(*argv[1:])
    elif argv == ["cert-remove"]:
        res = cert_remove()
    elif argv == ["refresh"]:
        res = refresh()
    elif argv == ["sync-overrides"]:
        res = sync_overrides()
    elif argv == ["reach"]:
        res = {"ok": True, **reach()}
    else:
        print(json.dumps({"ok": False, "errors": "unknown request", "unknown": True}))
        return 2
    print(json.dumps(res))
    return 0 if res.get("ok") else 1


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