#!/usr/bin/env python3
# summary: Connect to another desktop from a saved connection.
"""starchaser remote: Super+R. Remote desktop to your other computers, from one small picker.

    starchaser remote               Super+R: connect straight to the default connection when one is marked (pressing
                                    it again while that connects opens the picker); with no default, the picker
    starchaser remote pick          open the picker (Settings > Fleet links here)
    starchaser remote list          JSON: {remmina, rdp, connections, devices, default, keyring, connecting}: devices =
                                    the machines in the fleet that remote desktop can reach; remmina and rdp say whether
                                    Remmina and its Windows (RDP) part are installed; connecting is the one starting now
    starchaser remote connect <id> [--notify]
                                    connect; prints {"step"} lines, then {"result": "connected"|"failed", "error"}.
                                    --notify (Super+R's direct connect): a failure becomes a notification with a
                                    "Pick another" button instead of only this output, and this command then waits
                                    for that button (up to 10 minutes; the Super+R direct connect runs it detached)
    starchaser remote add --name N --address A [--user U] [--password-stdin]
                                    save a Windows (RDP) computer; the password (optional) is read from the input and
                                    goes to the keyring only, never into a file; prints {"id"}
    starchaser remote remove <id>   forget a saved computer (and its password in the keyring)
    starchaser remote default <id>|none
                                    mark the connection Super+R connects to right away
    starchaser remote watch <pid>   (started by connect) once the remote desktop app's windows are all closed, end it,
                                    so it doesn't stay behind in the taskbar's tray

Connection ids: "rdp:<file name>" for a computer saved as a Remmina connection file (~/.local/share/remmina/*.remmina;
Remmina is the remote desktop app that opens them: RDP for Windows, VNC for others. Connections made in Remmina
itself show up here too), "device:<link id>" for a Starchaser machine in the fleet (starchaser link remote sets
remote desktop up there and pairs Moonlight), and "fleet:<fleet id>" for any other machine in the fleet whose
remote desktop (Sunshine) answers (Moonlight connects to it; the first time, Moonlight shows a PIN to type there).
The fleet comes from the fleet registry (starchaser fleet list); paired devices it doesn't hold yet still show.
Passwords: Remmina's own keyring support (its "secret" plugin) keeps them. A password typed here is stored the same
way (libsecret, schema org.remmina.Password, attributes filename + key), and the file says only "." for it, which
is how Remmina marks "in the keyring".
Settings: ~/.config/starchaser/remote.json {"default": "<id>", "defaultFleet": "<fleet id>"}: the default is also kept
by the machine's fleet id, so it survives a reinstalled machine that was put back in its place (a new link id). While a connection starts,
a short note in the runtime folder says so (Super+R again then opens the picker): a device until its
connect ends, a saved computer for 25 seconds. Pressing Super+R again during those seconds also stops that attempt
when the remote desktop app Starchaser started for it hasn't shown a window yet (that app ends), so nothing keeps
connecting unseen behind the picker; once it shows a window (which may already be the connected computer) it stays.
When Super+R's direct connect to the default fails, Super+R opens the picker instead for the next minute (and the
failure notification has a "Pick another" button), so it doesn't retry the same dead connection.
Remmina stays running in the tray after its last window closes; a Remmina that Starchaser started is ended when its
windows are all closed (`watch`). One that was already running before is left alone.
"""
import configparser
import fcntl
import json
import os
os.environ["QS_DISABLE_CRASH_HANDLER"] = "1"
os.environ["STARCHASER_QML_APP"] = "remote"
import re
import secrets
import shutil
import subprocess
import sys
import time
from pathlib import Path

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

HOME = Path.home()
CONF = HOME / ".config/starchaser/remote.json"
REMMINA_DIR = Path(os.environ.get("XDG_DATA_HOME", str(HOME / ".local/share"))) / "remmina"
PEERS = HOME / ".local/share/starchaser/devices/peers.json"
FLEET_FILE = HOME / ".config/starchaser/fleet.json"
RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp"))
CONNECTING = RUNTIME / "starchaser-remote-connecting.json"
# Super+R's direct connect to the default failed: for a minute, Super+R opens the picker instead of retrying it
FAILED = RUNTIME / "starchaser-remote-failed.json"
FAILED_WINDOW = 60
QS_DIR = HOME / ".config/quickshell/settings/remote"
CONNECT_WINDOW = 25          # seconds after a start that Super+R opens the picker instead of connecting again
NAME_OK = re.compile(r"[^\x00-\x1f\x7f]{1,80}")
ADDR_OK = re.compile(r"[A-Za-z0-9.:\[\]_-]{1,253}")
USER_OK = re.compile(r"[^\x00-\x1f\x7f\s]{0,104}")
FILE_OK = re.compile(r"[\w.@+-]{1,200}\.remmina")
DEVICE_OK = re.compile(r"[0-9a-f]{8,64}")
FLEET_ID_OK = re.compile(r"(?:dev|m)-[0-9a-z]{6,64}")


def say(**kw) -> None:
    print(json.dumps(kw), flush=True)


def conf() -> dict:
    try:
        c = json.loads(CONF.read_text())
        return c if isinstance(c, dict) else {}
    except (OSError, ValueError, RecursionError):
        return {}


def save_conf(c: dict) -> None:
    CONF.parent.mkdir(parents=True, exist_ok=True)
    tmp = CONF.with_name(f".{CONF.name}.{os.getpid()}.tmp")
    with open(tmp, "w") as f:
        f.write(json.dumps(c, indent=1) + "\n")
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, CONF)


def remmina_ready() -> dict:
    """Remmina, and its Windows (RDP) part: Arch's remmina package opens RDP only with freerdp installed."""
    have = bool(shutil.which("remmina"))
    rdp = have and any(Path("/usr/lib").glob("libfreerdp[23].so*"))
    return {"remmina": have, "rdp": rdp}


def read_remmina(f: Path) -> dict | None:
    cp = configparser.ConfigParser(interpolation=None, strict=False)
    try:
        cp.read(f, encoding="utf-8")
        r = cp["remmina"]
    except (configparser.Error, KeyError, OSError, UnicodeDecodeError):
        return None
    proto = (r.get("protocol") or "").upper()
    if proto not in ("RDP", "VNC", "SPICE", "SSH", "X2GO"):
        return None
    return {"id": "rdp:" + f.name, "kind": proto.lower(), "name": r.get("name") or r.get("server") or f.stem,
            "address": r.get("server") or "", "user": r.get("username") or "",
            "protocol": {"RDP": "Windows (RDP)", "VNC": "VNC", "SPICE": "SPICE", "SSH": "SSH", "X2GO": "X2Go"}[proto]}


def connections() -> list:
    out = []
    if REMMINA_DIR.is_dir():
        for f in sorted(REMMINA_DIR.glob("*.remmina")):
            if FILE_OK.fullmatch(f.name):
                r = read_remmina(f)
                if r:
                    out.append(r)
    return sorted(out, key=lambda r: r["name"].lower())


def registry() -> tuple:
    """The fleet registry's machines (starchaser fleet list), or fleet.json when it is a registry file
    (version 2) and starchaser fleet isn't installed; [] otherwise. With them, the ids the registry removed (its
    removal records with their old ids, and entries being removed): a paired device among them stays out."""
    data = None
    if shutil.which("starchaser"):
        try:
            r = subprocess.run(["starchaser", "fleet", "list"], capture_output=True, text=True, timeout=10)
            data = json.loads(r.stdout) if r.returncode == 0 else None
        except (OSError, ValueError, subprocess.TimeoutExpired):
            data = None
    if data is None:
        try:
            data = json.loads(FLEET_FILE.read_text())
        except (OSError, ValueError, RecursionError):
            return [], set()
        if not isinstance(data, dict) or data.get("version") != 2:
            return [], set()
    machines = data if isinstance(data, list) else data.get("machines") if isinstance(data, dict) else None
    machines = [m for m in machines or [] if isinstance(m, dict)]
    removed = data.get("removed") if isinstance(data, dict) and isinstance(data.get("removed"), list) else []
    gone = {str(m.get("id")) for m in machines if m.get("state") == "removing"}
    for t in removed:
        if isinstance(t, dict):
            gone.add(str(t.get("id", "")))
            gone.update(str(x) for x in t.get("aliases") or [] if isinstance(t.get("aliases"), list))
    return [m for m in machines if m.get("state") != "removing"], gone


def address_of(m: dict) -> str:
    """Where to reach a fleet machine: the order the registry documents (docs/fleet.md)."""
    a = m.get("addresses") if isinstance(m.get("addresses"), dict) else {}
    for v in ((a.get("lan") or [None])[0], a.get("mdns"), a.get("tailscale"), a.get("last"), m.get("hostname")):
        # never one that starts with "-": it goes to Moonlight's command line, where it would read as an option
        if isinstance(v, str) and ADDR_OK.fullmatch(v) and not v.startswith("-"):
            return v
    return ""


# Sunshine's pairing port (the tests point it at a port nothing listens on, since a computer running them may run
# Sunshine itself)
SUNSHINE_PORT = int(os.environ.get("STARCHASER_SUNSHINE_PORT") or 47989)


def sunshine_answers(addrs: list) -> set:
    """The addresses whose remote desktop (Sunshine) answers on its pairing port, asked in parallel, about a second
    and a half at most."""
    import urllib.request
    from concurrent.futures import ThreadPoolExecutor

    def one(a):
        host = f"[{a}]" if ":" in a else a
        try:
            with urllib.request.urlopen(f"http://{host}:{SUNSHINE_PORT}/serverinfo", timeout=1.5) as r:
                return a if b"SUNSHINE_SERVER" in r.read(65536) else ""
        except (OSError, ValueError):
            return ""
    with ThreadPoolExecutor(max_workers=8) as ex:
        return {a for a in ex.map(one, list(dict.fromkeys(addrs))) if a}


def moonlight_paired() -> set:
    """The addresses Moonlight has paired with: its hosts that hold the computer's certificate (srvcert)."""
    conf = HOME / ".config/Moonlight Game Streaming Project/Moonlight.conf"
    hosts: dict = {}
    try:
        lines = conf.read_text(errors="replace").splitlines()
    except OSError:
        return set()
    section = ""
    keys = r"(localaddress|manualaddress|remoteaddress|ipv6address|srvcert)"
    for line in lines:
        line = line.strip()
        if line.startswith("[") and line.endswith("]"):
            section = line[1:-1]
            continue
        # Qt writes its host list as "[hosts]" then "1\localaddress=...", or "hosts\1\..." outside that section
        m = re.match(r"(\d+)\\" + keys + "=(.*)$", line) if section == "hosts" else \
            re.match(r"hosts\\(\d+)\\" + keys + "=(.*)$", line)
        if m:
            hosts.setdefault(m.group(1), {})[m.group(2)] = m.group(3).strip()
    return {v.split(":")[0] if v.count(":") == 1 else v for h in hosts.values() if h.get("srvcert")
            for k, v in h.items() if k != "srvcert" and v}


def devices(reg=None) -> list:
    """The fleet machines remote desktop can reach: every Starchaser machine (through its link), and any other whose
    remote desktop (Sunshine) answered; plus paired devices the registry doesn't hold yet. reg: registry(), when it
    was read already."""
    out, seen, others = [], set(), []
    machines, gone = reg if reg is not None else registry()
    for m in machines:
        fid = str(m.get("id", ""))
        if not FLEET_ID_OK.fullmatch(fid):
            continue
        name = str(m.get("label") or m.get("hostname") or "Computer")[:80]
        # the ids it had before (a reinstalled machine merged into its old place keeps the old id here)
        aliases = [str(x) for x in m.get("aliases") or [] if FLEET_ID_OK.fullmatch(str(x))] if isinstance(m.get("aliases"), list) else []
        link = m.get("link") if isinstance(m.get("link"), dict) else {}
        did = str(link.get("device", ""))
        if DEVICE_OK.fullmatch(did):
            seen.add(did)
            out.append({"id": "device:" + did, "fleetId": fid, "aliases": aliases, "name": name, "kind": str(m.get("kind") or ""),
                        "address": address_of(m), "via": "starchaser"})
        elif address_of(m) and (m.get("desktop") or {}).get("sunshine") != "absent":
            others.append((m, fid, aliases, name))
    # any other machine: shown when its remote desktop (Sunshine) answers, asked now and all at once (a registry
    # that already says "ready" is taken as it is)
    asked = [m for m, *_ in others if (m.get("desktop") or {}).get("sunshine") != "ready"]
    answering = sunshine_answers([address_of(m) for m in asked]) if asked else set()
    paired_at = moonlight_paired()
    for m, fid, aliases, name in others:
        addr = address_of(m)
        if (m.get("desktop") or {}).get("sunshine") == "ready" or addr in answering:
            known = (m.get("desktop") or {}).get("moonlightPaired")
            out.append({"id": "fleet:" + fid, "fleetId": fid, "aliases": aliases, "name": name, "kind": str(m.get("kind") or ""),
                        "address": addr, "via": "moonlight", "paired": bool(known) if known is not None else addr in paired_at})
    try:
        peers = json.loads(PEERS.read_text())
    except (OSError, ValueError, RecursionError):
        peers = []
    for p in peers if isinstance(peers, list) else []:
        if isinstance(p, dict) and DEVICE_OK.fullmatch(str(p.get("id", ""))) and str(p["id"]) not in seen \
                and "dev-" + str(p["id"]) not in gone:
            out.append({"id": "device:" + p["id"], "fleetId": "dev-" + p["id"], "name": str(p.get("name") or "Device")[:80],
                        "kind": str(p.get("kind") or ""), "address": str(p.get("address") or ""), "via": "starchaser"})
    return sorted(out, key=lambda d: d["name"].lower())


def default_id(cons: list, devs: list) -> str:
    """The marked default: by its connection id, or else by the fleet id it was marked with (a reinstalled machine
    put back in its place has a new link id); "" when it was removed."""
    c = conf()
    d = c.get("default", "")
    if any(x["id"] == d for x in cons + devs):
        return d
    fid = c.get("defaultFleet", "")
    return next((x["id"] for x in devs if fid and (x.get("fleetId") == fid or fid in x.get("aliases", []))), "")


def listing() -> dict:
    reg = registry()
    cons, devs = connections(), devices(reg)
    # every computer in the fleet, reachable or not: with none of them in devices, the picker says why instead of
    # sending the person to Settings > Fleet to add the computers already there
    count = sum(1 for m in reg[0] if FLEET_ID_OK.fullmatch(str(m.get("id", ""))) and str(m.get("id")) not in reg[1])
    return {**remmina_ready(), "connections": cons, "devices": devs, "fleetCount": count, "default": default_id(cons, devs),
            "keyring": bool(shutil.which("secret-tool")), "connecting": connecting()}


# ---------------------------------------------------------------------------------------------- connecting
def pid_alive(pid: int) -> bool:
    try:
        os.kill(pid, 0)
        return True
    except (OSError, ValueError):
        return False


def connecting() -> str:
    """The id of a connection that is starting right now, or "".
    A device: for as long as its connect runs (the pid is that connect itself, which ends when it's done; getting a
    device ready can take minutes). A saved computer: for CONNECT_WINDOW seconds after the start, whatever its pid
    does, because a Remmina that's already open takes the request and the one started for it exits at once."""
    try:
        s = json.loads(CONNECTING.read_text())
        if str(s.get("id", "")).startswith("device:"):
            if pid_alive(int(s["pid"])):
                return str(s["id"])
        elif time.time() - float(s["since"]) < CONNECT_WINDOW:
            return str(s.get("id", ""))
    except (OSError, ValueError, KeyError, TypeError):
        pass
    return ""


def mark_connecting(cid: str, pid: int, fresh: bool = False) -> None:
    try:
        CONNECTING.write_text(json.dumps({"id": cid, "pid": pid, "since": time.time(), "fresh": fresh}))
    except OSError:
        pass


def remmina_running() -> bool:
    try:
        return subprocess.run(["pgrep", "-u", str(os.getuid()), "-x", "remmina"], capture_output=True, timeout=5).returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


def remmina_windows() -> int | None:
    """How many Remmina windows are open (its class is org.remmina.Remmina), or None when Hyprland didn't answer."""
    try:
        cs = json.loads(subprocess.run(["hyprctl", "clients", "-j"], capture_output=True, text=True, timeout=5).stdout)
    except (OSError, ValueError, subprocess.TimeoutExpired):
        return None
    return sum(1 for c in cs if isinstance(c, dict) and str(c.get("class", "")).lower() in ("org.remmina.remmina", "remmina"))


def quit_remmina(pid: int) -> None:
    """End the Remmina Starchaser started: asked politely first (remmina --quit), then its process."""
    try:
        subprocess.run(["remmina", "--quit"], capture_output=True, timeout=10)
    except (OSError, subprocess.TimeoutExpired):
        pass
    for _ in range(15):
        if not pid_alive(pid):
            return
        time.sleep(0.2)
    try:
        os.kill(pid, 15)
    except OSError:
        pass


def watch(pid: int) -> int:
    """Wait while the Remmina we started runs; once it has shown a window and then has none for a few seconds (the
    person closed it), end it. Gives up after 12 hours."""
    seen, empty = False, 0
    for _ in range(12 * 3600 // 2):
        if not pid_alive(pid):
            return 0
        n = remmina_windows()
        if n is None:
            pass
        elif n > 0:
            seen, empty = True, 0
        elif seen:
            empty += 1
            if empty >= 2:
                quit_remmina(pid)
                return 0
        time.sleep(2)
    return 0


def stop_connecting() -> None:
    """Super+R pressed again while a saved computer is still connecting: that attempt stops (the Remmina started
    for it ends) if it hasn't shown a window yet, so it doesn't go on unseen behind the picker. A Remmina that was
    already open, or that shows a window, is left alone."""
    try:
        s = json.loads(CONNECTING.read_text())
    except (OSError, ValueError, RecursionError):
        return
    if not str(s.get("id", "")).startswith("rdp:"):
        return
    try:
        pid = int(s.get("pid"))
    except (TypeError, ValueError):
        return
    # only while it hasn't shown a window yet: a Remmina window may already hold the connected session (this flag
    # outlasts a quick connect), and "remmina --quit" would close it; a window that is showing can be closed by hand
    if s.get("fresh") and pid_alive(pid) and remmina_windows() == 0:
        quit_remmina(pid)
    done_connecting(str(s["id"]))


def done_connecting(cid: str) -> None:
    """The start is over (connected or not): Super+R connects again instead of opening the picker."""
    try:
        if json.loads(CONNECTING.read_text()).get("id") == cid:
            CONNECTING.unlink()
    except (OSError, ValueError, AttributeError):
        pass


def shortcut_key(desc: str) -> str:
    """The key in use for a shortcut, as people read it ("Super+R"), or "" (never written in here: a profile or the
    person's own change can move it)."""
    try:
        return subprocess.run(["starchaser", "shortcuts", "key", desc], capture_output=True, text=True, timeout=5).stdout.strip()
    except (OSError, subprocess.TimeoutExpired):
        return ""


def notify(title: str, body: str, replace: str = "", low: bool = False) -> str:
    """A notification; returns its id, so a later one can replace it (one card that updates, not a pile)."""
    cmd = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-p", "-a", "Starchaser", "-i", "preferences-desktop-remote-desktop"]
    if low:
        cmd += ["-u", "low"]
    if replace:
        cmd += ["-r", replace]
    try:
        return subprocess.run(cmd + [title, body], capture_output=True, text=True, timeout=5).stdout.strip().splitlines()[0]
    except (OSError, subprocess.TimeoutExpired, IndexError):
        return ""


def notify_pick(title: str, body: str, replace: str = "") -> None:
    """A failure notification with a "Pick another" button that opens the picker (waits for the answer: run only
    from the detached Super+R connect)."""
    if sys.stderr.isatty():     # say so in a terminal: the wait below can last minutes, and silence reads as a hang
        print("Waiting for your answer in the notification: press Pick another to choose another connection.",
              file=sys.stderr)
    cmd = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "preferences-desktop-remote-desktop", "-A", "pick=Pick another"]
    if replace:
        cmd += ["-r", replace]
    try:
        out = subprocess.run(cmd + [title, body], capture_output=True, text=True, timeout=600).stdout.split()
    except (OSError, subprocess.TimeoutExpired):
        return
    if out and out[-1] == "pick":
        open_picker()


def mark_failed(cid: str) -> None:
    try:
        FAILED.write_text(json.dumps({"id": cid, "at": time.time()}))
    except OSError:
        pass


def clear_failed() -> None:
    try:
        FAILED.unlink()
    except OSError:
        pass


def failed_recently(cid: str) -> bool:
    try:
        f = json.loads(FAILED.read_text())
        return f.get("id") == cid and time.time() - float(f.get("at", 0)) < FAILED_WINDOW
    except (OSError, ValueError, TypeError, AttributeError):
        return False


def connect(cid: str, notify_mode: bool = False) -> int:
    progress = {"nid": ""}         # Super+R's direct connect: the one notification its steps update

    def fail(msg: str, **extra) -> int:
        say(result="failed", error=msg, **extra)
        if notify_mode:
            # Super+R again within the minute opens the picker instead of retrying the same dead connection
            mark_failed(cid)
            k = shortcut_key("Apps: Remote desktop")
            notify_pick("Remote desktop didn't connect", msg + (f" Press {k} or Pick another to choose another connection." if k
                                                                else " Press Pick another to choose another connection."),
                        replace=progress["nid"])
        return 1

    def done() -> int:
        clear_failed()
        say(result="connected")
        return 0

    if cid.startswith("rdp:"):
        name = cid[4:]
        f = REMMINA_DIR / name
        if not FILE_OK.fullmatch(name) or not f.is_file():
            return fail("That connection isn't saved anymore.")
        r = read_remmina(f) or {}
        ready = remmina_ready()
        if not ready["remmina"] or (r.get("kind") == "rdp" and not ready["rdp"]):
            if notify_mode:
                open_picker()
            return fail("The remote desktop app isn't installed yet. The picker can install it.")
        say(step=f"Opening the remote desktop app for {r.get('name', 'the computer')}…")
        fresh = not remmina_running()            # a Remmina already open takes the request; ours then exits at once
        try:
            p = subprocess.Popen(["remmina", "-c", str(f)], start_new_session=True,
                                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except OSError as e:
            return fail(f"The remote desktop app didn't start ({e.strerror}).")
        mark_connecting(cid, p.pid, fresh)
        if fresh:                                # ends it once its windows are all closed
            try:
                subprocess.Popen([sys.executable, os.path.abspath(__file__), "watch", str(p.pid)], start_new_session=True,
                                 stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            except OSError:
                pass
        time.sleep(1.5)
        if p.poll() not in (None, 0):
            done_connecting(cid)
            return fail("The remote desktop app stopped right away.")
        done()
        if notify_mode and fresh:
            # nobody watches a picker here: a remote desktop app that gives up in the next seconds (a wrong address,
            # a refused login it can't ask about) says so in a notification
            for _ in range(17):
                time.sleep(0.5)
                code = p.poll()
                if code is not None:
                    # (not when Super+R stopped it on purpose: stop_connecting has already cleared the marker)
                    if code != 0 and connecting() == cid:
                        done_connecting(cid)
                        fail("The remote desktop app stopped before it connected.")
                    break
        return 0
    if cid.startswith("device:"):
        did = cid[7:]
        dev = next((d for d in devices() if d["id"] == cid), None)
        if not DEVICE_OK.fullmatch(did) or not dev:
            return fail("That machine isn't in your fleet anymore.")
        if connecting() == cid:
            # a second start while the first still runs (a second picker, or Super+R and the picker): it would only
            # be refused by the device link, and must not take over the first one's marker
            say(result="failed", error=f"Already connecting to {dev['name']}…", busy=True)
            return 1
        try:
            before = CONNECTING.read_text()
        except OSError:
            before = None
        mark_connecting(cid, os.getpid())
        try:
            p = subprocess.Popen(["starchaser", "link", "remote", did], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                 stderr=subprocess.DEVNULL, text=True)
        except OSError:
            done_connecting(cid)
            return fail("Starchaser's fleet link isn't available here.")
        result, busy = None, False
        for line in p.stdout:
            try:
                r = json.loads(line)
            except ValueError:
                continue
            if r.get("need") == "login":
                # remote desktop to this machine was never set up: that needs its login, asked in Settings > Fleet
                try:
                    p.stdin.write(json.dumps({"cancel": True}) + "\n")
                    p.stdin.flush()
                except OSError:
                    pass
                result = {"result": "failed", "need": "setup",
                          "error": f"Remote desktop to {dev['name']} needs its Sunshine login once. In Settings > Fleet, "
                                   f"press Remote desktop on {dev['name']} and enter it there."}
                continue
            if r.get("busy"):
                busy = True
            if r.get("step"):
                say(step=r["step"])
                if notify_mode:
                    # one card that follows the steps: the first already says when someone there has to click Allow
                    progress["nid"] = notify("Connecting to " + dev["name"], r["step"], replace=progress["nid"], low=True) or progress["nid"]
            if r.get("result"):
                result = result or r
        p.wait()
        if busy:
            # another start got there first: its marker stays (or comes back), and no "pick another" advice
            if before is not None:
                try:
                    CONNECTING.write_text(before)
                except OSError:
                    pass
            say(result="failed", error=(result or {}).get("error") or f"Already connecting to {dev['name']}…", busy=True)
            return 1
        done_connecting(cid)
        result = result or {"result": "failed", "error": f"{dev['name']} didn't answer."}
        if result.get("result") == "connected":
            if notify_mode and progress["nid"]:
                notify("Connected to " + dev["name"], "The other computer's screen is opening.", replace=progress["nid"], low=True)
            return done()
        if result.get("need") == "setup":
            say(**result)
            if notify_mode:
                notify("Remote desktop needs setting up", result["error"], replace=progress["nid"])
                subprocess.Popen(["starchaser", "settings", "devices"], start_new_session=True,
                                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            return 1
        return fail(result.get("error") or "Couldn't connect.")
    if cid.startswith("fleet:"):
        dev = next((d for d in devices() if d["id"] == cid), None)
        if not FLEET_ID_OK.fullmatch(cid[6:]) or not dev:
            return fail("That machine isn't in your fleet anymore, or its remote desktop isn't on.")
        if not shutil.which("moonlight"):
            return fail("Moonlight, the app that shows another computer's screen, isn't installed. Install it in Settings > Software.")
        # paired before: straight to its desktop. The first time, Moonlight pairs: it shows a PIN that is typed into
        # that computer's Sunshine page (on that computer itself), so nobody else's screen can be opened
        args = ["moonlight", "stream", dev["address"], "Desktop"] if dev.get("paired") else ["moonlight", "pair", dev["address"]]
        say(step=f"Opening {dev['name']}'s screen…" if dev.get("paired")
            else f"Moonlight shows a PIN: type it on {dev['name']}, in its remote desktop (Sunshine) page at https://localhost:47990.")
        try:
            subprocess.Popen(args, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        except OSError as e:
            return fail(f"Moonlight didn't start ({e.strerror}).")
        return done()
    return fail("Unknown connection.")


# ---------------------------------------------------------------------------------------------- saving
def slug(s: str) -> str:
    return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")[:40] or "computer"


def store_password(path: Path, name: str, password: str) -> bool:
    """Into the keyring, the way Remmina's secret plugin looks it up."""
    if not shutil.which("secret-tool"):
        return False
    try:
        r = subprocess.run(["secret-tool", "store", "--label", f"Remmina: {name} - password",
                            "xdg:schema", "org.remmina.Password", "filename", str(path), "key", "password"],
                           input=password, text=True, capture_output=True, timeout=30)
        return r.returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


def clear_password(path: Path) -> None:
    if shutil.which("secret-tool"):
        try:
            # by file only: a gateway or ssh-tunnel password Remmina kept for this computer goes too
            subprocess.run(["secret-tool", "clear", "xdg:schema", "org.remmina.Password", "filename", str(path)],
                           capture_output=True, timeout=15)
        except (OSError, subprocess.TimeoutExpired):
            pass                                 # a locked keyring that never answers: the file still goes


def add(name: str, address: str, user: str, password: str | None) -> int:
    name, address, user = name.strip() or address.strip(), address.strip(), user.strip()
    if not ADDR_OK.fullmatch(address):
        say(ok=False, error="Type the computer's name or address, like 192.168.1.20 or work-pc.")
        return 2
    if not NAME_OK.fullmatch(name) or not USER_OK.fullmatch(user):
        say(ok=False, error="The name or user name has characters that can't be used.")
        return 2
    REMMINA_DIR.mkdir(parents=True, exist_ok=True)
    f = REMMINA_DIR / f"starchaser-{slug(name)}-{secrets.token_hex(3)}.remmina"
    if password and shutil.which("secret-tool"):
        # a locked keyring (automatic sign-in leaves it locked) makes secret-tool wait its whole timeout: say the
        # work is happening, so the pause never reads as a hang (stderr only: stdout stays the JSON answer)
        print("Saving the password in the keyring. If it is locked, this can take up to 30 seconds; "
              "the computer is saved either way.", file=sys.stderr)
    stored = bool(password) and store_password(f, name, password)
    cp = configparser.ConfigParser(interpolation=None)
    cp.optionxform = str
    cp["remmina"] = {
        "name": name, "protocol": "RDP", "server": address, "username": user, "group": "",
        # "." = "in the keyring" to Remmina; empty = Remmina asks when connecting (and can save it itself)
        "password": "." if stored else "",
        "resolution_mode": "2",          # use this computer's screen size
        "colordepth": "99",              # automatic
        "sound": "local", "window_maximize": "1", "viewmode": "1",
    }
    with open(f, "w", encoding="utf-8") as fh:
        cp.write(fh, space_around_delimiters=False)
    f.chmod(0o600)
    say(ok=True, id="rdp:" + f.name, passwordSaved=stored,
        note="" if stored or not password
        else "The password wasn't saved (no keyring here): you'll be asked for it when you connect." if not shutil.which("secret-tool")
        else "The keyring didn't take the password (it may be locked). Remmina will ask for it when you connect.")
    return 0


def remove(cid: str) -> int:
    if not cid.startswith("rdp:") or not FILE_OK.fullmatch(cid[4:]):
        say(ok=False, error="Only saved computers can be removed here. Remove a computer from your fleet in Settings > Fleet.")
        return 2
    f = REMMINA_DIR / cid[4:]
    found = f.exists()
    clear_password(f)
    f.unlink(missing_ok=True)
    c = conf()
    if c.get("default") == cid:                      # a default left pointing at a file that is gone goes too
        c.pop("default")
        save_conf(c)
    if not found:
        say(ok=False, error="no such connection (see: starchaser remote list)")
        return 2
    say(ok=True)
    return 0


# ---------------------------------------------------------------------------------------------- the picker
def open_picker() -> None:
    """One picker: if it's open, bring it forward; else start it (a lock keeps two quick presses to one window)."""
    clear_failed()
    def ipc() -> bool:
        try:
            return subprocess.run(["qs", "-p", str(QS_DIR), "ipc", "call", "remote", "show"], capture_output=True,
                                  timeout=5).returncode == 0
        except (OSError, subprocess.TimeoutExpired):
            return False
    if ipc():
        return
    with open(RUNTIME / "starchaser-remote.lock", "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        if ipc():
            return
        subprocess.Popen(["qs", "-p", str(QS_DIR)], start_new_session=True, stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL)
        for _ in range(20):                       # hold the lock until it answers, so a second press asks it
            time.sleep(0.2)
            if ipc():
                break


def super_r() -> int:
    d = listing()
    if d["connecting"].startswith("rdp:"):
        stop_connecting()
        open_picker()
        return 0
    if d["default"] and not d["connecting"] and not failed_recently(d["default"]):
        subprocess.Popen([sys.executable, os.path.abspath(__file__), "connect", d["default"], "--notify"], start_new_session=True,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return 0
    open_picker()
    return 0


if __name__ == "__main__":
    a = sys.argv[1:]
    cmd = a[0] if a else "super-r"

    def refuse_unwritable(kind, error, trace):      # a settings folder it may not write: say so, not a traceback
        if issubclass(kind, PermissionError):
            print(f"starchaser remote: couldn't save your settings ({error.strerror}). Check that you can write to ~/.config.",
                  file=sys.stderr)
        else:
            sys.__excepthook__(kind, error, trace)
    sys.excepthook = refuse_unwritable

    if a[1:2] in (["-h"], ["--help"]):      # help after a command word is help, never a connection to open or change
        print(__doc__.strip())
        sys.exit(0)
    if cmd in ("list", "super-r", "pick") and len(a) > 1:
        sys.exit(takes_nothing_after("starchaser remote", cmd, a))

    def opt(n: str) -> str:
        return a[a.index(n) + 1] if n in a and a.index(n) + 1 < len(a) else ""

    if cmd == "super-r":
        sys.exit(super_r())
    elif cmd == "pick":
        open_picker()
    elif cmd == "watch" and len(a) == 2 and a[1].isdigit():
        sys.exit(watch(int(a[1])))
    elif cmd == "list":
        print(json.dumps(listing()))
    elif cmd == "connect" and len(a) >= 2:
        sys.exit(connect(a[1], "--notify" in a))
    elif cmd == "add" and "--address" in a:
        pw = sys.stdin.readline().rstrip("\n") if "--password-stdin" in a else None
        sys.exit(add(opt("--name"), opt("--address"), opt("--user"), pw))
    elif cmd == "remove" and len(a) == 2:
        sys.exit(remove(a[1]))
    elif cmd == "default" and len(a) == 2:
        c = conf()
        devs = devices()
        if a[1] == "none":
            c.pop("default", None)
            c.pop("defaultFleet", None)
        elif any(x["id"] == a[1] for x in connections() + devs):
            c["default"] = a[1]
            fid = next((x.get("fleetId", "") for x in devs if x["id"] == a[1]), "")
            if fid:
                c["defaultFleet"] = fid
            else:
                c.pop("defaultFleet", None)
        else:
            print("starchaser remote: no such connection (see: starchaser remote list)", file=sys.stderr)
            sys.exit(2)
        save_conf(c)
        print(json.dumps({"default": c.get("default", "")}))
    elif cmd in ("-h", "--help", "help"):
        print(__doc__.strip())
    else:
        if cmd in ("watch", "connect", "add", "remove", "default"):
            print(f"starchaser remote: wrong arguments for {cmd!r}. Run 'starchaser remote --help' for more help.", file=sys.stderr)
        else:
            print(f"starchaser remote: unknown command {cmd!r}. Run 'starchaser remote --help' for more help.", file=sys.stderr)
        sys.exit(2)
