#!/usr/bin/env python3
# summary: Open Mission Control to manage your fleet.
"""starchaser mission control: open Mission Control (manage the computers in your fleet) and the few steps around it.

    starchaser mission control open [route]   the Mission Control window, already signed in (route: e.g. "#/add" or
                                              "#/m/<fleet id>/updates"; an open window goes to that page)
    starchaser mission control close [token]  close that window (the page's x calls this)
    starchaser mission control status         JSON for Settings › Mission Control: web access, addresses, the
                                              certificate, the sign-in window, paused sign-ins
    starchaser mission control sync-overrides hide the upstream pages again (asks for the password)
    starchaser mission control cert-request   make a key and a certificate request for this computer's names and
                                              home-network addresses, to be signed by your own certificate
                                              authority; install the answer from Settings › Mission Control
    starchaser mission control cert-discard   delete that request and its key (one already in use stays in use)

The window: the Mission Control page and its browser run apart from the rest of the computer, with their own
little network where they can only talk to each other (nothing else can reach the page, and the browser can't
reach the internet), a fresh empty home (none of your files, no saved browser sign-ins) and only the screen.
Signing in uses your own session, so your keys and settings work. One window per person: a second "open" brings
the first one forward.
If that set-apart space or a Chromium-family browser isn't available, it opens the sign-in window instead: your
normal browser (any browser) on http://localhost:9091 (this computer only), which asks for your password.
"""
import fcntl
import importlib.machinery
import importlib.util
import ipaddress
import json
import os
import re
import secrets
import shutil
import signal
import socket
import subprocess
import sys
import time
from pathlib import Path

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

HOME = Path.home()
HERE = Path(os.path.realpath(__file__)).parent
WS = "/usr/lib/cockpit/cockpit-ws"
BRIDGE = "cockpit-bridge"
HELPER = "/usr/local/lib/starchaser/starchaser-mission-control-admin"
ADDR, PORT = "127.0.0.90", 8080           # inside the window's own network: nothing outside can reach it
SIGNIN_URL = "http://localhost:9091/"
PREFS = HOME / ".config/starchaser/mission-control.json"
CERT_DIR = HOME / ".local/state/starchaser/mission-control/cert"
WS_CERTS = Path("/etc/cockpit/ws-certs.d")
ROUTE = re.compile(r"#?/[A-Za-z0-9/_.-]{0,200}")
WINDOW_CONF = """[WebService]
Shell = /missioncontrol/index.html
LoginTitle = Mission Control
"""


def runtime() -> Path:
    base = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    d = Path(base) / "starchaser-mission-control"
    d.mkdir(mode=0o700, parents=True, exist_ok=True)
    return d


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


def prefs() -> dict:
    try:
        p = json.loads(PREFS.read_text())
        return p if isinstance(p, dict) else {}
    except (OSError, ValueError):
        return {}


def notify(title: str, body: str) -> None:
    if shutil.which("notify-send"):
        sh(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Mission Control", "-i", "computer", title, body)
    print(f"{title} {body}", file=sys.stderr)


def webapp():
    """bin/starchaser-webapp, beside this file: which Chromium-family browser app windows use."""
    path = HERE / "starchaser-webapp"
    loader = importlib.machinery.SourceFileLoader("starchaser_webapp", str(path))
    spec = importlib.util.spec_from_loader("starchaser_webapp", loader)
    mod = importlib.util.module_from_spec(spec)
    loader.exec_module(mod)
    return mod


# ------------------------------------------------------------------------------------------------------ the window

def browser_cmd() -> list:
    """The browser to run inside the confinement: a real binary (never a Flatpak, which can't run in there)."""
    try:
        _, cmd = webapp().browser()
    except Exception:
        return []
    parts = cmd.split()
    if not parts or parts[0] == "flatpak":
        return []
    exe = shutil.which(parts[0])
    return [os.path.realpath(exe)] + parts[1:] if exe else []


def confinement_works() -> bool:
    if not shutil.which("bwrap"):
        return False
    r = sh("bwrap", "--unshare-user", "--unshare-net", "--unshare-pid", "--ro-bind", "/usr", "/usr",
           "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib", "/lib64",
           "--proc", "/proc", "--dev", "/dev",
           "--", "/usr/bin/true", timeout=10)
    return r.returncode == 0


def app_window_reason() -> str:
    """A stable reason for Settings to explain the fallback and offer the right next step."""
    if not browser_cmd():
        return "missing-browser"
    if not confinement_works():
        return "isolation-unavailable"
    return ""


def descendants(root: int) -> set:
    kids = {}
    for p in Path("/proc").iterdir():
        if not p.name.isdigit():
            continue
        try:
            ppid = int((p / "stat").read_text().rsplit(")", 1)[1].split()[1])
        except (OSError, IndexError, ValueError):
            continue
        kids.setdefault(ppid, []).append(int(p.name))
    out, todo = set(), [root]
    while todo:
        x = todo.pop()
        for k in kids.get(x, []):
            if k not in out:
                out.add(k)
                todo.append(k)
    return out


def raise_window(info: dict) -> bool:
    """Bring the open window forward: the Hyprland window whose process belongs to that window's confinement.
    Focus only; the pointer never moves."""
    pids = descendants(int(info.get("bwrap", 0) or 0))
    if not pids or not shutil.which("hyprctl"):
        return False
    try:
        clients = json.loads(sh("hyprctl", "clients", "-j").stdout or "[]")
    except ValueError:
        return False
    for c in clients:
        if c.get("pid") in pids and c.get("address"):
            # Use the same action as the taskbar: restore its desktop and uncover it when Settings floats above it.
            # Raw compositor focus alone leaves tiled apps underneath floating Settings.
            command = (f'if StarchaserWin and StarchaserWin.show then StarchaserWin.show("{c["address"]}") '
                       f'else hl.dispatch(hl.dsp.focus({{ window = "address:{c["address"]}", no_mouse = true }})); '
                       'hl.dispatch(hl.dsp.window.bring_to_top()) end')
            return sh("hyprctl", "eval", command).returncode == 0
    return False


def window_info() -> dict:
    try:
        info = json.loads((runtime() / "window.json").read_text())
    except (OSError, ValueError):
        return {}
    pid = info.get("pid")
    try:
        if not isinstance(pid, int) or "starchaser-mission-control" not in Path(f"/proc/{pid}/cmdline").read_text(errors="replace"):
            return {}
    except OSError:
        return {}
    return info


def go_to(info: dict, route: str) -> None:
    """Send the open window to a page: it watches goto.json and follows a route naming its own token, newer than
    when it opened (web/app.js followGoto). Written whole (temp file, then rename), so the page never reads half."""
    path = runtime() / "goto.json"
    tmp = path.with_name(f".goto.json.{os.getpid()}.tmp")
    with open(tmp, "w") as f:
        json.dump({"route": route if route.startswith("#") else "#" + route, "token": info.get("token", ""), "at": time.time()}, f)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)


def open_window(route: str) -> int:
    rt = runtime()
    lock = open(rt / "lock", "w")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        info = window_info()
        if info and route:
            go_to(info, route)
        if info and raise_window(info):
            return 0
        # held, but no window yet: an earlier press is still starting it (or offering a browser), not an open window
        notify("Mission Control is already open." if info else "Mission Control is still opening.", "")
        return 0
    if prefs().get("window") == "signin":
        return open_signin(route)
    browser = browser_cmd()
    if not Path(WS).is_file() or not shutil.which(BRIDGE):
        notify("Mission Control isn't installed completely.", "Run the Starchaser desktop setup again.")
        return 1
    if not browser or not confinement_works():
        return open_signin(route)
    drop_browser_offer()

    token = secrets.token_hex(12)
    win = Path(f"/tmp/starchaser-mission-control-{os.getuid()}-{token}")
    (win / "home").mkdir(parents=True, mode=0o700)
    (win / "profile/Default").mkdir(parents=True, mode=0o700)
    # the throwaway profile: no "Save password?" offers (admin passwords are typed into the page) and no sign-in nags
    (win / "profile/Default/Preferences").write_text(json.dumps({
        "credentials_enable_service": False, "profile": {"password_manager_enabled": False},
        "browser": {"check_default_browser": False}, "signin": {"allowed": False}}))
    (win / "config/cockpit").mkdir(parents=True)
    (win / "config/cockpit/cockpit.conf").write_text(WINDOW_CONF)

    # bridge <-> web server: two pipes. The bridge runs out here, in the person's session.
    ws_to_bridge_r, ws_to_bridge_w = os.pipe()
    bridge_to_ws_r, bridge_to_ws_w = os.pipe()
    env = dict(os.environ, STARCHASER_MC_WINDOW=token)
    bridge = subprocess.Popen([BRIDGE], stdin=ws_to_bridge_r, stdout=bridge_to_ws_w, env=env, start_new_session=True)

    xdg = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    wl = os.environ.get("WAYLAND_DISPLAY", "wayland-1")
    wl_path = wl if wl.startswith("/") else f"{xdg}/{wl}"
    # ?app=<token>: the page shows its own x, which runs `starchaser mission control close <token>` (web/app.js)
    url = f"http://{ADDR}:{PORT}/?app={token}" + (route if route.startswith("#") else ("#" + route if route else ""))
    args = ["bwrap", "--unshare-net", "--unshare-user", "--unshare-ipc", "--unshare-pid", "--unshare-uts",
            "--die-with-parent", "--new-session",
            "--ro-bind", "/usr", "/usr", "--ro-bind", "/etc", "/etc", "--ro-bind-try", "/opt", "/opt",
            "--symlink", "usr/bin", "/bin", "--symlink", "usr/bin", "/sbin",
            "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib", "/lib64",
            "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--tmpfs", "/var/tmp",
            "--ro-bind-try", "/var/cache/fontconfig", "/var/cache/fontconfig",
            "--tmpfs", "/home", "--tmpfs", "/run", "--dir", xdg,
            "--ro-bind", wl_path, wl_path,
            "--bind", str(win), str(win)]
    args += ["--setenv", "HOME", str(win / "home"), "--setenv", "XDG_CONFIG_DIRS", str(win / "config"),
             "--setenv", "XDG_RUNTIME_DIR", xdg, "--setenv", "WAYLAND_DISPLAY", wl_path,
             "--unsetenv", "DISPLAY", "--unsetenv", "DBUS_SESSION_BUS_ADDRESS", "--unsetenv", "SSH_AUTH_SOCK",
             "--unsetenv", "XDG_CONFIG_HOME", "--unsetenv", "XDG_DATA_HOME", "--unsetenv", "XDG_CACHE_HOME",
             "--", "/bin/sh", "-c", SCRIPT, "sh", WS, ADDR, str(PORT)]
    args += browser + [f"--app={url}", f"--user-data-dir={win / 'profile'}", "--no-first-run",
                       "--no-default-browser-check", "--no-sandbox", "--test-type", "--disable-gpu",
                       "--ozone-platform=wayland", "--class=starchaser-mission-control", "--password-store=basic",
                       "--disable-background-networking", "--disable-features=Translate,MediaRouter"]
    jail = subprocess.Popen(args, stdin=bridge_to_ws_r, stdout=ws_to_bridge_w, start_new_session=True)
    for fd in (ws_to_bridge_r, ws_to_bridge_w, bridge_to_ws_r, bridge_to_ws_w):
        os.close(fd)
    (rt / "window.json").write_text(json.dumps({"pid": os.getpid(), "token": token, "bwrap": jail.pid,
                                                "bridge": bridge.pid, "dir": str(win)}))

    def stop(*_):
        for p in (jail, bridge):
            try:
                p.terminate()
            except ProcessLookupError:
                pass
    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    signal.signal(signal.SIGHUP, stop)
    try:
        jail.wait()
    finally:
        try:
            bridge.terminate()
            bridge.wait(timeout=5)
        except (ProcessLookupError, subprocess.TimeoutExpired):
            bridge.kill()
        (rt / "window.json").unlink(missing_ok=True)
        shutil.rmtree(win, ignore_errors=True)
    return 0


# Inside the confinement: the web server on the loopback of the window's own network, then the browser. When the
# browser closes, bubblewrap ends and takes the web server with it (its own process namespace).
SCRIPT = r"""
ws=$1; addr=$2; port=$3; shift 3
"$ws" --local-session=- -a "$addr" -p "$port" <&0 >&1 &
exec 0</dev/null 1>&2
hex=$(printf '%02X%02X%02X%02X:%04X' $(echo "$addr" | awk -F. '{print $4, $3, $2, $1}') "$port")
i=0
while [ $i -lt 50 ] && ! grep -q " $hex 00000000:0000 0A" /proc/net/tcp 2>/dev/null; do sleep 0.1; i=$((i+1)); done
"$@"
"""


# Read by starchaser software: when a browser finishes installing within half an hour, it opens Mission Control
# itself, so the person isn't left on the Software page to find their way back (QA 2026-11-04)
AFTER_BROWSER = "starchaser-after-browser.json"


def open_after_browser(route: str = "") -> None:
    base = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    try:
        Path(base, AFTER_BROWSER).write_text(json.dumps({
            "argv": ["starchaser", "mission", "control", "open"] + ([route] if route else []), "until": time.time() + 1800}))
    except OSError:
        pass


# exit status for "did not open, and the person was already told why": the Super menu shows its own "did not start"
# notice for any other failure, which would be wrong advice here (QA 20261108-0209 001)
EXIT_EXPLAINED = 75


def no_browser(route: str = "") -> int:
    """No browser to open it in: the recommended one's install offer, whose button opens it in Settings › Software.
    Mission Control then opens by itself once a browser is installed."""
    open_after_browser(route)
    r = sh("starchaser", "software", "offer", "--remind", "brave-origin", "Mission Control opens in a web browser window.")
    if r.returncode != 0:
        notify("Mission Control didn't open.", "Install a web browser from Settings › Software, then try again. You can open Software with starchaser settings software.")
    else:
        # the offer is a desktop notification only: from a Terminal, say why it exited too (QA 20261106-1333 001)
        print("Mission Control opens in a web browser window, and no browser is installed. "
              "Install one in Settings › Software (starchaser settings software).", file=sys.stderr)
    return EXIT_EXPLAINED


def drop_browser_offer() -> None:
    """Mission Control is opening, so a "web browser is needed" card still on screen (or in the bell) from an earlier
    press is out of date: a browser got installed some other way. Nothing on screen: nothing happens."""
    sh("starchaser", "software", "withdraw", "brave-origin")


def has_any_browser() -> bool:
    """Any web browser for the sign-in window: a Chromium-family one, or the default browser (any other),
    which opens the page like any link."""
    try:
        w = webapp()
        return bool(w.browser()[1] or w.default_browser())
    except Exception:
        return True


def open_signin(route: str = "") -> int:
    """The sign-in window: the person's normal browser on the loopback-only listener (asks for the password)."""
    # before the password is asked for: a password typed only to hear that there's no browser is wasted
    if not has_any_browser():
        return no_browser(route)
    drop_browser_offer()
    st = helper_status()
    if not any("127.0.0.1:9091" in x for x in st.get("listen", [])):
        r = sh("pkexec", HELPER, "local-signin", "on", timeout=120)
        if r.returncode != 0:
            notify("Mission Control didn't open.", "Turning on its sign-in window needs your password.")
            return 1
    try:
        ok = webapp().open_webapp(SIGNIN_URL)
    except Exception:
        ok = False
    if not ok:
        notify("Mission Control didn't open.", "Install a web browser from Settings › Software, then try again. You can open Software with starchaser settings software.")
        return 1
    return 0


def close_window(token: str) -> int:
    token = token or os.environ.get("STARCHASER_MC_WINDOW", "")
    info = window_info()
    if not info:
        return 0
    if token and token != info.get("token"):
        print("starchaser mission control: that isn't the open window", file=sys.stderr)
        return 1
    os.kill(info["pid"], signal.SIGTERM)
    return 0


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

def helper_status() -> dict:
    r = sh(HELPER, "status") if os.path.exists(HELPER) else None
    try:
        return json.loads(r.stdout) if r and r.returncode == 0 else {}
    except ValueError:
        return {}


def addresses() -> list:
    """This computer's home-network addresses (IPv4 and IPv6 unique-local), the way other devices would use them."""
    out = []
    try:
        data = json.loads(sh("ip", "-j", "addr", "show", "up").stdout or "[]")
    except ValueError:
        data = []
    for link in data:
        if link.get("ifname") == "lo":
            continue
        for a in link.get("addr_info") or []:
            try:
                ip = ipaddress.ip_address(a.get("local", ""))
            except ValueError:
                continue
            if a.get("scope") != "global":
                continue
            ts = ip in ipaddress.ip_network("100.64.0.0/10") or (ip.version == 6 and ip in ipaddress.ip_network("fd7a:115c:a1e3::/48"))
            if ip.is_private or ts:
                out.append({"ip": str(ip), "iface": link.get("ifname"), "v": ip.version, "tailscale": ts})
    return out


def cert_state() -> dict:
    """The certificate the web server uses: the highest-sorting *.cert in ws-certs.d (as the web server picks)."""
    try:
        certs = sorted(p for p in WS_CERTS.glob("*.cert"))
    except OSError:
        certs = []
    if not certs:
        return {"kind": "none"}
    f = certs[-1]
    r = sh("openssl", "x509", "-in", str(f), "-noout", "-subject", "-issuer", "-enddate", "-ext", "subjectAltName")
    if r.returncode != 0:
        return {"kind": "unreadable", "file": f.name}
    lines = r.stdout.splitlines()
    subj = next((x.split("=", 1)[1].strip() for x in lines if x.startswith("subject=")), "")
    iss = next((x.split("=", 1)[1].strip() for x in lines if x.startswith("issuer=")), "")
    end = next((x.split("=", 1)[1].strip() for x in lines if x.startswith("notAfter=")), "")
    names = [s.strip() for x in lines if "DNS:" in x or "IP Address:" in x for s in x.split(",")]
    exp = sh("openssl", "x509", "-in", str(f), "-noout", "-checkend", "0").returncode != 0
    soon = sh("openssl", "x509", "-in", str(f), "-noout", "-checkend", str(30 * 86400)).returncode != 0
    kind = "own" if f.name == "2-starchaser.cert" else "self-signed" if subj == iss else "other"
    return {"kind": kind, "file": f.name, "until": end, "expired": exp, "soon": soon and not exp,
            "names": [n.replace("IP Address:", "").replace("DNS:", "") for n in names if n]}


def faillock() -> dict:
    """Is this account's sign-in paused after wrong passwords (pam_faillock)? "unknown" when it can't be read."""
    user = os.environ.get("USER") or ""
    if not shutil.which("faillock") or not user:
        return {"state": "unknown"}
    r = sh("faillock", "--dir", "/run/faillock-network", "--user", user)
    if r.returncode != 0:
        return {"state": "unknown"}
    fails = [ln for ln in r.stdout.splitlines()[2:] if ln.strip() and " V" in ln]
    return {"state": "paused" if len(fails) >= 3 else "ok", "fails": len(fails)}


def status() -> dict:
    st = helper_status()
    window_reason = app_window_reason()
    host = socket.gethostname()
    fqdn = sh("hostname", "-f").stdout.strip() or host
    try:
        policy = json.loads(Path("/etc/starchaser/policy.json").read_text())
        firewall = "on" if policy.get("enabled") else "off"
    except (OSError, ValueError):
        firewall = "unknown"
    reach = {}
    if st.get("web"):
        r = sh(HELPER, "reach")
        try:
            reach = json.loads(r.stdout)
        except ValueError:
            reach = {}
    addrs = addresses()
    names = [fqdn if "." in fqdn else host]
    urls = [f"https://{n}:9090" for n in names] + [
        f"https://{a['ip']}:9090" if a["v"] == 4 else f"https://[{a['ip']}]:9090"
        for a in addrs if a["v"] == 4 and (not a["tailscale"] or st.get("tailscale"))]
    return {"installed": Path(WS).is_file() and os.path.exists(HELPER), "web": bool(st.get("web")),
            "tailscale": bool(st.get("tailscale")), "localSignin": bool(st.get("localSignin")),
            "socket": st.get("socket", "unknown"), "listen": st.get("listen", []), "firewall": firewall,
            "reach": reach, "host": host, "fqdn": fqdn, "addresses": addrs, "urls": urls, "cert": cert_state(),
            "faillock": faillock(), "window": "signin" if prefs().get("window") == "signin" else "app",
            "appWindowPossible": not window_reason, "appWindowReason": window_reason,
            "hasBrowser": window_reason != "missing-browser" or has_any_browser(),
            "tailscaleUp": any(a["tailscale"] for a in addrs), "certRequest": cert_requests()}


# ------------------------------------------------------------------------------------------------ certificate

def cert_request() -> int:
    """A new key and a request (CSR) with every name and home-network address of this computer."""
    if not shutil.which("openssl"):
        print(json.dumps({"ok": False, "errors": "openssl is missing"}))
        return 1
    host = socket.gethostname()
    fqdn = sh("hostname", "-f").stdout.strip() or host
    dns = list(dict.fromkeys([host, fqdn, "localhost"]))
    ips = [a["ip"] for a in addresses() if a["v"] == 4 and not a["tailscale"]]
    san = ",".join([f"DNS:{d}" for d in dns if re.fullmatch(r"[A-Za-z0-9.-]{1,253}", d)] + [f"IP:{i}" for i in ips])
    CERT_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
    key, csr = CERT_DIR / f"{host}.key", CERT_DIR / f"{host}.csr"
    old = os.umask(0o077)
    try:
        r = sh("openssl", "req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes",
               "-keyout", str(key), "-out", str(csr), "-subj", f"/CN={fqdn}",
               "-addext", f"subjectAltName={san}", "-addext", "extendedKeyUsage=serverAuth",
               "-addext", "keyUsage=critical,digitalSignature")
    finally:
        os.umask(old)
    if r.returncode != 0:
        print(json.dumps({"ok": False, "errors": "Couldn't make the request."}))
        return 1
    print(json.dumps({"ok": True, "csr": str(csr), "key": str(key), "names": dns, "ips": ips,
                      "next": "Have your certificate authority sign the request (a server certificate, valid at "
                              "most 398 days). Then choose the signed file in Settings › Mission Control › "
                              "Certificate; the key stays on this computer."}))
    return 0


def cert_requests() -> list:
    """The certificate requests made here and not discarded yet (their .csr files)."""
    try:
        return sorted(str(p) for p in CERT_DIR.glob("*.csr"))
    except OSError:
        return []


def cert_discard() -> int:
    """Delete every request made here and its key. A certificate already chosen with Use it keeps working: the web
    service has its own copy of the key."""
    gone = []
    for csr in map(Path, cert_requests()):
        for f in (csr, csr.with_suffix(".key")):
            try:
                f.unlink()
                gone.append(str(f))
            except FileNotFoundError:
                pass
            except OSError:
                print(json.dumps({"ok": False, "errors": f"Couldn't delete {f}."}))
                return 1
    print(json.dumps({"ok": True, "discarded": gone}))
    return 0


def phone_trust_module():
    import importlib.util
    path = Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser/phone_trust.py"
    if not path.is_file():
        path = Path("/usr/local/lib/starchaser/phone_trust.py")
    spec = importlib.util.spec_from_file_location("starchaser_phone_trust", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def phone_trust() -> int:
    import secrets
    import qrcode
    import qrcode.image.svg
    module = phone_trust_module()
    directory = HOME / ".local/share/starchaser/devices/fleet-web-ca"
    hostname = socket.gethostname().split(".")[0] + ".local"
    path = Path(__file__).resolve().with_name("starchaser-fleet-ca")
    loader = importlib.machinery.SourceFileLoader("mission_control_fleet_ca", str(path))
    spec = importlib.util.spec_from_loader(loader.name, loader)
    authority = importlib.util.module_from_spec(spec); loader.exec_module(authority)
    try:
        cert, key, ca = authority.obtain(directory, hostname, [a["ip"] for a in addresses() if a["v"] == 4])
    except (ValueError, OSError) as error:
        print(json.dumps({"ok": False, "error": str(error)})); return 1
    chain = directory / "server-chain.crt"
    chain.write_text(cert.read_text() + ca.read_text())
    installed = sh("pkexec", HELPER, "cert-install", str(chain), str(key), timeout=120)
    result = json.loads(installed.stdout or "{}")
    if installed.returncode or not result.get("ok"):
        print(json.dumps({"ok": False, "error": result.get("errors") or "The certificate wasn't installed."})); return 1
    token = secrets.token_hex(32)
    shared = sh("pkexec", HELPER, "phone-share", str(ca), f"https://{hostname}:9090/", token, timeout=120)
    result = json.loads(shared.stdout or "{}")
    if shared.returncode or not result.get("ok"):
        print(json.dumps({"ok": False, "error": result.get("errors") or "The phone invitation wasn't shared."})); return 1
    image = directory / "phone-code.svg"
    qrcode.make(result["url"], image_factory=qrcode.image.svg.SvgPathImage).save(image)
    ca_image = directory / "phone-authority-code.svg"
    qrcode.make(result["certificateUrl"], image_factory=qrcode.image.svg.SvgPathImage).save(ca_image)
    print(json.dumps({**result, "qr": str(image), "certificateQr": str(ca_image), "authorityFingerprint": module.fingerprint(ca), "serverFingerprint": module.fingerprint(cert),
                      "note": "Scan this code on your phone. During this one-time setup, check the server and authority fingerprints shown here before installing trust. On iPhone or iPad, install the downloaded profile, then turn on full trust in Settings > General > About > Certificate Trust Settings. Mission Control still asks for your account password."}))
    return 0


def main(argv: list) -> int:
    safe_streams()
    if not argv or argv[0] in ("-h", "--help", "help") or any(x in ("-h", "--help") for x in argv[1:]):
        print(__doc__.strip())
        return 0 if argv else 2
    cmd, rest = argv[0], argv[1:]
    if cmd in ("status", "sync-overrides", "cert-request", "cert-discard") and rest:
        return takes_nothing_after("starchaser mission control", cmd, argv)
    if cmd == "open":
        route = rest[0] if rest else ""
        if route and not ROUTE.fullmatch(route) and not re.fullmatch(r"#?/software\?destination=dev-[0-9a-f]{16}", route) \
                and not re.fullmatch(r"#?/add\?address=(?:[A-Za-z0-9_.~-]|%[0-9A-Fa-f]{2}){1,768}", route):
            print("starchaser mission control: that isn't a Mission Control page (like #/add)", file=sys.stderr)
            return 2
        return open_window(route)
    if cmd == "close":
        if len(rest) > 1:
            print("Usage: starchaser mission control close [token]", file=sys.stderr)
            return 2
        return close_window(rest[0] if rest else "")
    if cmd == "status":
        print(json.dumps(status()))
        return 0
    if cmd == "sync-overrides":
        r = subprocess.run(([HELPER] if os.geteuid() == 0 else ["pkexec", HELPER]) + ["sync-overrides"])
        return r.returncode
    if cmd == "phone-trust" and not rest:
        return phone_trust()
    if cmd == "phone-stop" and len(rest) == 1:
        result = sh("pkexec", HELPER, "phone-stop", rest[0], timeout=120)
        print(result.stdout); return result.returncode
    if cmd == "cert-request":
        return cert_request()
    if cmd == "cert-discard":
        return cert_discard()
    print(f"starchaser mission control: unknown command '{cmd}'. "
          "Run 'starchaser mission control --help' for more help.", file=sys.stderr)
    return 2


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