#!/usr/bin/env python3
"""starchaser-fleet-root: the fleet service, the one writer of this computer's fleet state (rule 33.7).

Started by systemd from starchaser-fleet-state.socket, only where /etc/starchaser/fleet-v2-preview exists until the
fleet is finished (build plan section 1). `starchaser fleet` talks to it over two sockets in /run/starchaser/fleet/:
  root.sock    mode 0600, root only: the root-here steps (start, recover) and the wake-up poke (rule 2.4)
  people.sock  mode 0666: reads, filtered by who is asking (rules 32.3, 33.4), Check now, fleet changes that carry
               a fleet admin's password, which this service checks (rules 4.2, 4.7), a person's own password change
               (the old password is the proof, rule 11.1) and the sign-in screen's questions (rules 12.2, 13.2, 11.7)
The caller is known from the socket (SO_PEERCRED), never from what it sends. Each request is one line of JSON and
each answer one line back; Turn on and the recovery code are one conversation on one connection, so a dropped
session forgets everything made for it (rule 5.1).

Build phase 3 adds, on people.sock: `hello` (a join hello from the network, handed over by `starchaser link daemon`,
which owns port 47744, rule 16.12) and `net` (a request over the fleet link, only from the link account's forced
command, rules 22.7 and 35.6); on root.sock the joining computer's steps (join, leave, renumber, keep-local).
Build phase 5 adds `new-key` on people.sock (a fleet admin at the flagship, confirmed like a recovery code) and, on
root.sock, `rekey` and `reset` (rules 25.1, 25.2, 26.2 to 26.4).
Build phase 6 adds, on people.sock: `export` (the fleet file, or with "accounts" the names and numbers for a computer
that can't join, such as a NAS), `inventory` and `apply-check`, all reads; `apply` itself is a fleet change (family 31).
Build phase 8 adds, on people.sock: `backup-check` (the Make backup sheet, a read; `flagship backup` itself is a fleet
change); on root.sock: `take-over-check` and `take-over` (family 30). `recover` also works on a member (rule 5.3).

On a Mac member (rules 35.10 to 35.12) launchd keeps this service running, and it makes its own two sockets in
/var/run/starchaser/fleet, since a Mac has no systemd and no /run.

Usage: starchaser-fleet-root serve       (systemd; or, for the unit tests only, bound to STARCHASER_FLEET_RUN)
       starchaser-fleet-root poke        ask for news now (the network and wake-up hooks, rule 2.4)
       starchaser-fleet-root relay CID   the fleet link's forced command (one request from computer CID)
       starchaser-fleet-root firstboot   the first-boot join with the installer's token (rule 16.9)
       starchaser-fleet-root renumber-resume   finish an unfinished renumber before sign-in (rule 9.5)
       starchaser-fleet-root listen      one join hello from the network, on a Linux computer that isn't Starchaser
                                         (rule 35.7: systemd holds port 47744 there and starts this per connection)
"""
import contextlib
import json
import os
import pwd
import socket
import struct
import sys
import threading
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import fleet_apply as fa
import fleet_backup as fb
import fleet_join as fj
import fleet_people as fp
import fleet_renumber as fr
import fleet_reset as fz
import fleet_state as fs
import fleet_wire as fw

LIMIT = 17 * 1024 * 1024                   # a news bundle the link relays (fleet_wire.BUNDLE_LIMIT, 16 MiB) and its wrapping
IDLE_EXIT = 120


MAC = sys.platform == "darwin"             # a Mac member (rules 35.10 to 35.12): launchd, not systemd; no /run


def run_dir() -> Path:
    if fs.testing() and os.environ.get("STARCHASER_FLEET_RUN"):
        return Path(os.environ["STARCHASER_FLEET_RUN"])
    return Path("/var/run/starchaser/fleet" if MAC else "/run/starchaser/fleet")


def fleet_dir() -> Path:
    if fs.testing():
        return Path(os.environ["STARCHASER_FLEET_DIR"])
    return Path("/var/lib/starchaser/fleet")


def peer_uid(conn) -> int:
    if MAC:                                # LOCAL_PEERCRED (level 0, option 1): struct xucred starts version, uid
        return struct.unpack("2I", conn.getsockopt(0, 1, 76)[:8])[1]
    return struct.unpack("3i", conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")))[1]


def login_of(uid: int) -> str:
    try:
        return pwd.getpwuid(uid).pw_name
    except KeyError:
        return ""


class Conversation:
    """One connection: its caller, and what a Turn on or a new code made for it so far (never written until the
    code comes back)."""

    def __init__(self, service, conn, root_socket: bool):
        self.svc, self.conn, self.root_socket = service, conn, root_socket
        self.uid = peer_uid(conn)
        # root here: uid 0 on the root socket. The unit tests' service runs unprivileged and counts its own uid.
        me = os.geteuid()
        self.is_root = root_socket and (self.uid == 0 or (fs.testing() and self.uid == me))
        self.login = login_of(self.uid)
        self.pending = None
        self.buf = b""

    def read(self):
        while b"\n" not in self.buf:
            chunk = self.conn.recv(4096)
            if not chunk:
                return None
            self.buf += chunk
            if len(self.buf) > LIMIT:
                raise ValueError("too large")
        line, self.buf = self.buf.split(b"\n", 1)
        return json.loads(line)

    def send(self, obj) -> None:
        self.conn.sendall(json.dumps(obj).encode() + b"\n")

    def serve(self) -> None:
        try:
            self._serve()
        finally:
            if self.pending and self.pending[0] == "join":                               # rules 15.6, 16.13
                with contextlib.suppress(Exception):
                    self.svc.fleet.join_cancel(self.pending[1])

    def _serve(self) -> None:
        with self.conn:
            while True:
                try:
                    req = self.read()
                except (ValueError, OSError):
                    return
                if req is None:
                    return                         # the session dropped: self.pending dies with it (rule 5.1)
                if isinstance(req, dict) and req.get("op") == "hello":
                    self.hello(req)                # the connection is the join's from here on (rule 15.1)
                    return
                try:
                    answer = self.handle(req if isinstance(req, dict) else {})
                except fs.Refused as r:
                    answer = r.answer()
                except (KeyError, TypeError, ValueError) as e:
                    answer = {"ok": False, "error": "bad-request", "message": f"That request wasn't understood ({e}).",
                              "exit": 2}
                except OSError as e:
                    # a file or a system tool failed under the request: said to the person and written to the
                    # journal, never a silent end (found on a server whose /etc and /var are separate file systems)
                    print(f"starchaser-fleet-root: {req.get('op') if isinstance(req, dict) else '?'} stopped: {e!r}",
                          file=sys.stderr, flush=True)
                    answer = {"ok": False, "error": "failed", "exit": 1,
                              "message": f"This computer couldn't finish that ({e.strerror or e}). Check the system "
                                         "log: " + ("/var/log/starchaser-fleet.log" if MAC else
                                                    "journalctl -u starchaser-fleet-state")}
                try:
                    self.send(answer)
                except OSError:
                    return

    def need_root(self) -> None:
        if not self.is_root:
            raise fs.Refused("refused", "root", "Run this with sudo.")

    def admin(self, req) -> str:
        """The fleet admin a change is asked for: the caller's own login (root may name one)."""
        name = req.get("admin") or ""
        if not self.is_root and name != self.login:
            raise fs.Refused("need-fleet-admin")
        return name

    def signin_caller(self, person: str) -> None:
        """The sign-in screen's questions are for the sign-in screen (the greeter account), root, or the person."""
        if not (self.is_root or self.login in ("greeter",) or self.login == person):
            raise fs.Refused("refused", "signin", "Only the sign-in screen asks this.")

    def own_person(self, req: dict) -> str:
        """A person's own password change: the caller's own account. The sign-in screen and root name the person
        whose old password they carry; the old password is checked either way (rule 13.6)."""
        person = req.get("person") or self.login
        if person != self.login and not (self.is_root or self.login == "greeter"):
            raise fs.Refused("not-yours")
        return person

    def hello(self, req: dict) -> None:
        """A join hello from the network: `starchaser link daemon` passes the connection through, byte for byte."""
        lines = fw.Lines(self.conn, fw.PAYLOAD_LIMIT)
        lines.buf = self.buf
        address = str(req.get("address") or "")[:64]
        with contextlib.suppress(OSError, TimeoutError, ValueError, fs.Refused):
            self.svc.fleet.hello(lines, address, req.get("first") or {})

    def link_caller(self) -> None:
        """Rule 22.7: `net` comes only from the fleet link's account (its forced command), never from a person."""
        if self.login != fw.LINK_ACCOUNT and not (fs.testing() and self.uid == os.geteuid()):
            raise fs.Refused("refused", "link", "Only the fleet link asks this.")

    def handle(self, req: dict) -> dict:
        f, op = self.svc.fleet, req.get("op")
        if (MAC or f.host.plain_passwords) and op in MAC_NEVER:                          # rule 35.10
            raise fs.Refused("refused", "mac", MAC_NEVER[op])
        if op == "net":
            self.link_caller()
            return f.net(str(req.get("computer") or ""), str(req.get("address") or ""), req.get("msg") or {})
        if op == "list-computers":
            return f.computers_list(self.login, self.is_root)
        if op == "list-tokens":
            return f.tokens_list(self.login, self.is_root)
        if op == "invite-received":                                                      # rule 36.2
            return f.invite_received(req.get("token", ""), req.get("from", ""), req.get("address", ""))
        if op == "list-people":
            return f.people_list(self.login, self.is_root)
        if op == "list-rules":                                                           # build phase 4
            return f.rules_list(self.login, self.is_root)
        if op == "list-keys":
            return f.keys_list(self.login, self.is_root, str(req.get("person") or ""))
        if op == "installer":                                                            # rules 35.8, 35.12
            import fleet_member
            # with this computer's address, so the screen and the command can spell out the commands to run on
            # the new computer (a server finds no fleet by name: it has no local-network lookup)
            address = next(iter(f.host.addresses()), "")
            if req.get("mac"):
                import fleet_mac
                return {"ok": True, "script": fleet_mac.installer(), "address": address, "mac": True,
                        "version": fleet_member.version(fleet_member._tar(mac=True))}
            return {"ok": True, "script": fleet_member.installer(), "version": fleet_member.version(),
                    "address": address}
        if op == "known-hosts":                                                          # rule 22.6
            return f.known_hosts()
        if op == "others-keys":                                                          # rule 35.5
            return f.others_keys(self.login)
        if op == "export":                                                               # rules 31.1, 31.7
            if req.get("accounts"):
                return f.export_accounts(self.login, self.is_root)
            return f.export_file(self.login, self.is_root)
        if op == "inventory":                                                            # rule 31.7
            return f.inventory(self.login, self.is_root)
        if op == "apply-check":                                                          # rules 31.2, 31.6
            return f.apply_check(self.login, self.is_root, str(req.get("text") or ""))
        if op == "list-groups":
            return f.groups_list(self.login, self.is_root)
        if op == "backup-check":                                                         # rules 29.2, 29.3, 29.7
            return f.backup_check(self.login, self.is_root, str(req.get("computer") or ""))
        if op == "list-services":
            return f.services_list(self.login, self.is_root)
        if op == "password-change":                                                      # rules 11.1, 11.2
            return f.password_change(self.own_person(req), req["old"], req["new"])
        if op == "password-finish":                                                      # rule 14.3
            return f.password_change(self.own_person(req), req["old"], req["new"], finishing=True)
        if op == "finish":                                                               # rule 3.4
            return f.finish(self.admin(req), req["password"], req.get("nonce"))
        if op == "signin-check":
            self.signin_caller(req.get("person", ""))
            return f.signin_check(req.get("person", ""))
        if op == "signin-hint":
            self.signin_caller(req.get("person", ""))
            return f.signin_hint(req.get("person", ""), bool(req.get("physical")), req.get("typed") or "")
        if op == "keyring-keep":                                                         # rule 11.7
            self.signin_caller(req.get("person", ""))
            return f.keyring_keep(req.get("person", ""), req.get("old") or "", req.get("current") or "")
        if op == "keyring-fresh":
            self.signin_caller(req.get("person", ""))
            return f.keyring_fresh(req.get("person", ""))
        if op == "status":
            return f.status(self.login, self.is_root)
        if op == "log":
            return f.activity(self.login, self.is_root, req.get("person") or "", req.get("computer") or "")
        if op in ("sync", "poke"):
            self.svc.wake.set()
            return dict(f.catch_up(), asked=True)
        if op == "change":
            return f.change(self.admin(req), req["password"], req["change"], req.get("seen"), req.get("nonce"))
        if op == "recovery-code-prepare":                                                # rule 5.6
            self.pending = ("recovery", f.recovery_prepare(self.admin(req), req["password"], req.get("nonce")))
            return {"ok": True, "code": self.pending[1]["code"]}
        if op == "new-key-prepare":                                                      # rule 26.1
            p = f.new_key_prepare(self.admin(req), req["password"], req.get("nonce"))
            self.pending = ("new-key", p)
            return {"ok": True, "code": p["code"], "ended": len(p["ended"])}
        if op in ("recovery-code-confirm", "recover-confirm", "start-confirm", "new-key-confirm", "show"):
            return self.confirm(op, req)
        # the root-here steps
        self.need_root()
        if op == "start-check":
            return f.start_check(req.get("founder", ""), req.get("name", ""), rng(req))
        if op == "start-prepare":
            answer, pending = f.start_prepare(req.get("founder", ""), req["password"], req.get("newPassword", ""),
                                              req.get("name", ""), rng(req), req.get("trust", ""))
            self.pending = ("start", pending)
            return answer
        if op == "recover-check":
            return f.recover_check(req["code"])
        if op == "recover-prepare":
            self.pending = ("recover", f.recover_prepare(req["code"], req["admin"], req["password"]))
            return {"ok": True, "code": self.pending[1]["code"]}
        out = self.joining(f, op, req)
        if out is not None:
            return out
        raise fs.Refused("bad-request", op or "", "That request wasn't understood.")

    def joining(self, f, op: str, req: dict):
        """The root-here steps of build phase 3 (commands.md): join, leave, renumber, keep-local."""
        j = self.pending[1] if self.pending and self.pending[0] == "join" else None
        if op == "join-check":
            return f.join_check(req.get("name", ""))
        if op == "join-start":                                                           # rule 15.1
            chk = f.join_check(req.get("name", ""))
            j = fj.Joining(chk["name"], req.get("trust", ""))
            out = f.join_code_start(j, req.get("via", ""))
            self.pending = ("join", j)
            return out
        if op in ("join-wait", "join-more", "join-cancel", "join-finish"):
            if j is None:
                raise fs.Refused("stale-start", "", "That join ended. Start again.")
            if op == "join-wait":
                return f.join_wait(j, min(60, max(1, int(req.get("seconds") or 5))))
            if op == "join-more":
                return f.join_more(j)
            self.pending = None
            if op == "join-cancel":
                return f.join_cancel(j)
            out = f.join_finish(j, bool(req.get("yes")))
            self.svc.wake.set()
            return out
        if op in ("join-token", "join-paired"):                                          # rules 16.4, 36.2
            chk = f.join_check(req.get("name", ""))
            j = fj.Joining(chk["name"], req.get("trust", ""))
            self.pending = ("join", j)
            try:
                if op == "join-paired":
                    out = f.join_paired(j, req.get("flagship", ""))
                else:
                    out = f.join_token(j, req.get("token", ""), req.get("via", ""))
            finally:
                self.pending = None
            self.svc.wake.set()
            return out
        if op == "join-arm":                                                             # rule 16.9
            return f.arm(req.get("token", ""), req.get("name", ""))
        if op == "firstboot":
            out = f.firstboot(req.get("trust", ""))
            self.svc.wake.set()
            return out
        if op == "renumber-preview":                                                     # rules 9.4, 9.9
            return fr.Renumber(f).preview(req.get("name", ""), req.get("to"))
        if op == "renumber":                                                             # rules 9.2, 9.5
            to = req.get("to")
            target = fr.Renumber(f)._target(req.get("name", ""), to)
            if target["fleet"]:                                                          # a fleet admin's password
                r = f.change(req.get("admin", ""), req.get("password", ""), {"op": "check-admin"}, None,
                             req.get("nonce"))
                if not r.get("ok"):
                    return r
            return fr.Renumber(f).start(req.get("name", ""), to, bool(req.get("endSessions")))
        if op == "keep-local":                                                           # rule 9.7
            return fr.keep_local(f, req.get("name", ""))
        if op == "rekey":                                                                # rules 26.2 to 26.4
            out = f.rekey(str(req.get("code") or ""))
            self.svc.wake.set()
            return out
        if op == "take-over-check":                                                      # rules 29.2, 29.7, 30.4
            return f.take_over_check()
        if op == "take-over":                                                            # rules 30.3, 30.3a, 30.4
            out = f.take_over(req.get("admin", ""), req.get("password", ""), req.get("nonce", ""),
                              bool(req.get("gone")))
            self.svc.wake.set()
            return out
        if op == "reset-check":                                                          # rule 25.1
            return f.reset_check()
        if op == "reset":                                                                # rules 25.1, 25.2
            return f.reset_here()
        if op == "test-deliver" and fs.hooks_allowed():                                  # QA VMs only (P3 step 3)
            return dict(f.accept(req.get("state") or {}, req.get("entries") or []), ok=True)
        if op in ("leave", "sell"):                                                      # rules 28.1 to 28.4
            out = f.leave(req.get("admin", ""), req.get("password", ""), bool(req.get("anyway")))
            if op == "sell" and out.get("ok"):
                out["erase"] = ("This computer has left your fleet and forgotten its fleet keys. To erase it, start "
                                "it from a Starchaser install stick and install over everything."
                                if f.host.starchaser() else
                                "This computer has left your fleet and forgotten its fleet keys. To erase it, "
                                "reinstall it with its own installer and install over everything.")
            return out
        return None

    def confirm(self, op: str, req: dict) -> dict:
        if not self.pending:
            raise fs.Refused("stale-start")
        kind, p = self.pending
        if op == "show":                                                                 # "Show the code again"
            return {"ok": True, "code": p["code"]}
        want = {"start-confirm": "start", "recovery-code-confirm": "recovery", "recover-confirm": "recover",
                "new-key-confirm": "new-key"}[op]
        if kind != want:
            raise fs.Refused("stale-start")
        if kind == "start":
            out = self.svc.fleet.start_confirm(p, req["code"])
        elif kind == "recovery":
            out = self.svc.fleet.recovery_confirm(p, req["code"])
        elif kind == "new-key":
            out = self.svc.fleet.new_key_confirm(p, req["code"])
        else:
            out = self.svc.fleet.recover_confirm(p, req["code"])
        self.pending = None
        self.svc.wake.set()
        return out


def test_wire():
    """The unit tests' fleet link: requests to other test computers' services over their people.sock, keyed by
    computer id in STARCHASER_FLEET_TEST_LINK (a JSON map of computer id to run folder). Never for a root service."""
    if not fs.testing() or not os.environ.get("STARCHASER_FLEET_TEST_LINK"):
        return None

    class Wire:
        def ask(self, computer, addresses, msg, seconds=30):
            me = json.loads(Path(os.environ["STARCHASER_FLEET_TEST_LINK"]).read_text())
            run = me.get(computer["id"])
            if not run:
                raise OSError("unreachable")
            mine = next((k for k, v in me.items() if v == str(run_dir())), "")
            with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
                s.settimeout(seconds)
                s.connect(str(Path(run) / "people.sock"))
                s.sendall(json.dumps({"op": "net", "computer": mine, "address": "192.0.2.1", "msg": msg}).encode()
                          + b"\n")
                buf = b""
                while not buf.endswith(b"\n"):
                    chunk = s.recv(65536)
                    if not chunk:
                        raise OSError("closed")
                    buf += chunk
            return json.loads(buf)
    return Wire()


# Rule 35.10: what a Mac member never does, each with the one sentence that says what to do instead
_MAC_FLAGSHIP = ("A Mac can't be the flagship or the backup. Use a Linux computer in your fleet for that; this Mac "
                 "follows it.")
_MAC_NUMBER = ("Account numbers aren't changed on a Mac. An account that was already on this Mac keeps its Mac "
               "number and still gets its person's fleet SSH keys.")
MAC_NEVER = {"start-check": _MAC_FLAGSHIP, "start-prepare": _MAC_FLAGSHIP, "recover-check": _MAC_FLAGSHIP,
             "recover-prepare": _MAC_FLAGSHIP, "take-over-check": _MAC_FLAGSHIP, "take-over": _MAC_FLAGSHIP,
             "new-key-prepare": _MAC_FLAGSHIP, "renumber": _MAC_NUMBER, "renumber-preview": _MAC_NUMBER,
             "installer": "Print the installer on a Linux computer in your fleet: starchaser fleet installer --mac",
             "join-arm": "A Mac doesn't join at its next start. Join it now: sudo starchaser fleet join --token"}


def rng(req):
    r = req.get("range")
    return (int(r[0]), int(r[1])) if r else None


class Service:
    def __init__(self):
        self.fleet = fb.BackupFleet(fleet_dir(), wire=test_wire())
        self.wake = threading.Event()
        self.wake.set()                                                                  # rule 2.4: at start
        self.last_used = time.monotonic()
        self.busy = 0
        self.lock = threading.Lock()

    def sockets(self) -> list:
        """systemd's two sockets (LISTEN_FDNAMES root:people), or, for the unit tests, two bound here."""
        if os.environ.get("LISTEN_PID") == str(os.getpid()) and os.environ.get("LISTEN_FDS") == "2":
            names = (os.environ.get("LISTEN_FDNAMES") or "root:people").split(":")
            return [(socket.socket(fileno=3 + i), names[i] == "root") for i in range(2)]
        if not fs.testing() and not MAC:           # on a Mac launchd keeps this service running; it binds its own
            raise SystemExit("starchaser-fleet-root: start it through starchaser-fleet-state.socket")
        d = run_dir()
        d.mkdir(parents=True, exist_ok=True)
        if MAC:                                    # /var/run is emptied at every start: the folders are made here,
            os.chmod(d.parent, 0o755)              # open enough for people.sock to be reached (the umask is 0077)
            os.chmod(d, 0o755)
        out = []
        for name, mode in (("root.sock", 0o600), ("people.sock", 0o666)):
            path = d / name
            with contextlib.suppress(FileNotFoundError):
                path.unlink()
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            old = os.umask(0o077)
            try:
                s.bind(str(path))
            finally:
                os.umask(old)
            os.chmod(path, mode)
            s.listen(16)
            out.append((s, name == "root.sock"))
        return out

    def accept_loop(self, listener, root_socket: bool) -> None:
        while True:
            conn, _ = listener.accept()
            threading.Thread(target=self.converse, args=(conn, root_socket), daemon=True).start()

    def converse(self, conn, root_socket: bool) -> None:
        with self.lock:
            self.busy += 1
        try:
            Conversation(self, conn, root_socket).serve()
        except OSError:
            pass
        finally:
            with self.lock:
                self.busy -= 1
                self.last_used = time.monotonic()

    def tick(self) -> None:
        """Rule 2.4: ask for news at start, on a wake-up or network poke, on Check now, every 60 seconds while
        something waits to be sent, and every 15 minutes otherwise."""
        last = 0
        seen = time.time()
        while True:
            woke = self.wake.wait(timeout=5)
            self.wake.clear()
            if MAC and time.time() - seen > 60:    # the clock ran on while this loop stood still: the Mac slept and
                woke = True                        # woke (rule 2.4; Linux has a hook for this, a Mac has none)
            seen = time.time()
            now = int(time.time())
            pending = any((self.fleet.root / "outbox").glob("*.json"))                    # rule 2.4: every 60 s
            if now >= fs.next_ask(now, last, pending=pending, woke=woke):
                with contextlib.suppress(fs.Refused, OSError, ValueError, KeyError):
                    self.fleet.catch_up()
                with contextlib.suppress(fs.Refused, OSError, ValueError, KeyError):
                    self.fleet.send_outbox()                                             # rule 11.2
                last = now
            socket_activated = os.environ.get("LISTEN_PID") == str(os.getpid())
            with self.lock:
                idle = not self.busy and time.monotonic() - self.last_used > IDLE_EXIT
            if socket_activated and idle and not self.fleet.state_path.exists():
                os._exit(0)                        # no fleet here: systemd starts it again at the next request

    def serve(self) -> None:
        os.umask(0o077)
        for listener, root_socket in self.sockets():
            threading.Thread(target=self.accept_loop, args=(listener, root_socket), daemon=True).start()
        self.tick()


def poke() -> int:
    """For the NetworkManager and wake-up hooks: ask the service for news now; quiet when there is no fleet."""
    path = run_dir() / "root.sock"
    if not path.exists():
        return 0
    with contextlib.suppress(OSError):
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
            s.settimeout(10)
            s.connect(str(path))
            s.sendall(b'{"op": "poke"}\n')
            s.recv(4096)
    return 0


def firstboot() -> int:
    """Rule 16.9: the join service at a start where /etc/starchaser/firstboot.json exists. The fleet service does the
    join (it is the one writer); this only asks it and waits, retrying for up to 10 minutes."""
    path = run_dir() / "root.sock"
    deadline = time.monotonic() + 60
    while not path.exists() and time.monotonic() < deadline:
        time.sleep(1)
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
            s.settimeout(fj.FIRSTBOOT_TRIES + 120)
            s.connect(str(path))
            s.sendall(b'{"op": "firstboot", "trust": "yes"}\n')
            buf = b""
            while not buf.endswith(b"\n"):
                chunk = s.recv(65536)
                if not chunk:
                    break
                buf += chunk
        out = json.loads(buf or b"{}")
    except (OSError, ValueError):
        return 1
    if out.get("lines"):
        print("\n".join(out["lines"]))
    elif out.get("message"):
        print(out["message"], file=sys.stderr)
    return 0 if out.get("ok") else 1


LISTEN_FIRST, LISTEN_LONGEST = 3, 25 * 60   # as `starchaser link daemon` hands a hello over: 3 seconds for the first
                                            # line; a code join waits 10 minutes, More time once, plus the answers


def listen() -> int:
    """Rule 35.7: on a Linux computer that isn't Starchaser there is no `starchaser link daemon` to hold TCP 47744,
    so systemd holds it (starchaser-fleet-listen.socket) and starts this once per connection, as nobody, with the
    connection as standard input. Like the link daemon, it only hands a join hello to this computer's fleet service
    and passes the conversation through unchanged; the service decides everything. With no fleet service socket, or
    a first line that is not a join hello, the caller gets no answer at all."""
    import select
    try:
        conn = socket.socket(fileno=os.dup(0))
        src = conn.getpeername()[0].removeprefix("::ffff:")
    except OSError:
        return 1
    sock = run_dir() / "people.sock"
    try:
        conn.settimeout(LISTEN_FIRST)
        buf, end = b"", time.monotonic() + LISTEN_FIRST
        while b"\n" not in buf:
            if time.monotonic() > end or len(buf) > fw.PAYLOAD_LIMIT:
                return 1
            chunk = conn.recv(4096)
            if not chunk:
                return 1
            buf += chunk
        line, rest = buf.split(b"\n", 1)
        first = json.loads(line)
        if not isinstance(first, dict) or first.get("fleetJoin") != 1 or not sock.exists():
            return 1
        svc = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        svc.connect(str(sock))
        svc.sendall(json.dumps({"op": "hello", "address": src, "first": first}).encode() + b"\n" + rest)
        conn.setblocking(True)
        end = time.monotonic() + LISTEN_LONGEST
        while time.monotonic() < end:
            ready, _, _ = select.select([conn, svc], [], [], 30)
            for s in ready:
                data = s.recv(65536)
                if not data:
                    return 0
                (svc if s is conn else conn).sendall(data)
    except (OSError, ValueError):
        return 1
    return 0


def main(argv: list) -> int:
    if argv in (["--help"], ["-h"]):
        print(__doc__.strip())
        return 0
    if argv == ["serve"]:
        if os.geteuid() != 0 and not fs.testing():
            print("starchaser-fleet-root: the fleet service runs as root", file=sys.stderr)
            return 1
        Service().serve()
        return 0
    if argv == ["poke"]:
        return poke()
    if len(argv) == 2 and argv[0] == "relay":
        return fw.relay(argv[1], run_dir())
    if argv == ["firstboot"]:
        return firstboot()
    if argv == ["listen"]:
        return listen()
    if argv == ["renumber-resume"]:
        if os.geteuid() != 0 and not fs.testing():
            return 1
        f = fz.ResetFleet(fleet_dir())
        if not f.state_path.exists() or not (f.root / "renumber.json").exists():
            return 0
        try:
            out = fr.Renumber(f).finish()
        except fs.Refused as r:
            print(r.text, file=sys.stderr)
            return 1
        print(out.get("text", ""))
        return 0
    print(__doc__.strip(), file=sys.stderr)
    return 2


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