#!/usr/bin/env python3
# summary: Create and check a recovery USB stick.
"""starchaser recovery usb: make a recovery USB stick (what Settings > Recovery runs).

    starchaser recovery usb status      JSON: the installer downloaded here (if any), and when you last made a stick
    starchaser recovery usb download [full|online]
                                        download the newest Starchaser installer and check its signature and
                                        checksum (keeps a copy that is already the newest); progress as "@@{json}"
                                        lines, then the JSON answer. full (the default) works with no internet and
                                        is bigger; online is smaller and needs internet to install
    starchaser recovery usb download-start [full|online]
                                        download in the background; keeps going after Settings closes; cancel pauses it
    starchaser recovery usb drives      JSON: the USB drives you can unplug (never the computer's own disks), with
                                        their size, name and what is on them
    starchaser recovery usb write DEVICE SERIAL SIZE
                                        erase that USB drive and write the downloaded installer to it, then check it
                                        (asks for your password). DEVICE, SERIAL and SIZE come from drives, so a
                                        different stick plugged into the same place is never erased. It keeps
                                        going if this command is stopped; progress as "@@{json}" lines, then the
                                        JSON answer
    starchaser recovery usb cancel      pause the download, or stop making the stick (left only partly written)
    starchaser recovery usb job         JSON: the current or last download or write job ({} when none)
    starchaser recovery usb job-seen ID mark that answer as shown
    starchaser recovery usb delete-download   remove the downloaded installer to free the space
    starchaser recovery usb remind      JSON: whether the welcome should suggest making one ({"show": true} until
                                        the person answers it, and only to someone who never made one)
    starchaser recovery usb remind-seen the person answered the suggestion with Not now: never again
"""
# The download lives in ~/.cache/starchaser/recovery-usb/ (it can be downloaded again), each ISO beside the signed
# checksum list it was checked with, so a stick can still be made offline from the copy already here and the root
# helper can check that copy itself. What was made and whether the welcome reminded is kept in
# ~/.local/state/starchaser/recovery-usb.json. The checks that matter for safety live in the root-owned
# recovery_usb.py, shared with the helper that writes (starchaser-recovery-usb-admin). One installer is kept: a
# download of the other edition (full or online) replaces it once it is checked.
import fcntl
import json
import os
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

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

safe_streams()
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "recovery_usb.py").is_file():
        sys.path.insert(0, str(_lib))
        break
from recovery_usb import (EDITIONS, ISO_NAME, Canceled, KeysMissing, Refused, iso_edition, iso_version, parse_sums,
                          removable_drives, sha256_file, size_text, sums_digest, verify_sums)

BASE = os.environ.get("STARCHASER_RECOVERY_USB_URL", "https://downloads.starchaserlinux.org/iso/")
HELPER = os.environ.get("STARCHASER_RECOVERY_USB_HELPER", "/usr/local/lib/starchaser/starchaser-recovery-usb-admin")
CACHE = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "starchaser" / "recovery-usb"
STATE = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state") / "starchaser" / "recovery-usb.json"
JOB = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-recovery-usb-job.json"
MARGIN = 200 << 20                  # left free after the download, so it never fills the disk to the last byte
SMALL = 64 * 1024


def version() -> str:
    for p in (Path("/usr/share/starchaser/VERSION"), Path(__file__).resolve().parent.parent / "VERSION"):
        try:
            return p.read_text().strip() or "dev"
        except OSError:
            pass
    return "dev"


def event(**kw) -> None:
    print("@@" + json.dumps(kw), flush=True)


def answer(code: int, **kw) -> None:
    print(json.dumps(kw), flush=True)
    sys.exit(code)


# ------------------------------------------------------------------ the record

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


def state_update(**changes) -> None:
    """Read-modify-write under a lock (two Settings windows, or Settings and the welcome, may both write)."""
    STATE.parent.mkdir(parents=True, exist_ok=True)
    with open(STATE.with_name(STATE.name + ".lock"), "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        d = state_read()
        for k, v in changes.items():
            if v is None:
                d.pop(k, None)
            elif isinstance(v, dict) and isinstance(d.get(k), dict) and k == "verified":
                d[k] = {**d[k], **v}
            else:
                d[k] = v
        tmp = STATE.with_name(f".{STATE.name}.{os.getpid()}.tmp")
        with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
            json.dump(d, f)
            f.flush()
            os.fsync(f.fileno())
        tmp.replace(STATE)


# ------------------------------------------------------------------ the copy downloaded here

def local_installers() -> list:
    """Checked copies here, newest version first: [{name, path, sha256, size, time}]. A copy counts only while its
    size and time match what was recorded when it was checked, and its signed list sits beside it."""
    verified = state_read().get("verified") or {}
    out = []
    for name, rec in verified.items():
        p = CACHE / name
        try:
            st = p.stat()
        except OSError:
            continue
        if (ISO_NAME.fullmatch(name) and isinstance(rec, dict) and rec.get("size") == st.st_size
                and rec.get("mtime") == int(st.st_mtime) and (CACHE / f"{name}.SHA256SUMS").is_file()
                and (CACHE / f"{name}.SHA256SUMS.sig").is_file()):
            out.append({"name": name, "path": str(p), "sha256": rec.get("sha256", ""), "size": st.st_size,
                        "version": iso_version(name), "edition": iso_edition(name), "time": rec.get("time", 0)})
    return sorted(out, key=lambda r: r["version"], reverse=True)


def remove_installer(name: str) -> int:
    freed = 0
    for suffix in ("", ".part", ".SHA256SUMS", ".SHA256SUMS.sig"):
        p = CACHE / (name + suffix)
        try:
            freed += p.stat().st_size
            p.unlink()
        except OSError:
            pass
    return freed


def cached_names() -> set:
    try:
        return {p.name.removesuffix(".part") for p in CACHE.iterdir()
                if ISO_NAME.fullmatch(p.name.removesuffix(".part"))}
    except OSError:
        return set()


def public(rec) -> dict | None:
    return {k: rec[k] for k in ("name", "version", "edition", "size", "time")} | {"sizeText": size_text(rec["size"])} if rec else None


# ------------------------------------------------------------------ download

class Offline(Exception):
    pass


class ServerUnavailable(Refused):
    """The site cannot supply an installer; a verified local copy can still be used."""


class NotPublished(ServerUnavailable):
    """The download site answered that it doesn't have the installer: trying again soon won't help."""


class EditionMissing(Refused):
    """This release has no online installer (a release may publish only the full one): the full one still works."""


def opener(url: str, start: int = 0):
    if not (url.startswith("https://") or os.environ.get("STARCHASER_RECOVERY_USB_TEST_LOCAL") == "1"):
        raise Refused("The download address must start with https://.")
    req = urllib.request.Request(url, headers={"User-Agent": f"starchaser-recovery-usb/{version()}"})
    if start:
        req.add_header("Range", f"bytes={start}-")
    try:
        return urllib.request.urlopen(req, timeout=30)
    except urllib.error.HTTPError as e:
        if e.code == 416 and start:                    # the part already here is the whole file
            return None
        raise (NotPublished if e.code in (403, 404, 410) else ServerUnavailable)(unavailable(e.code)) from None
    except (urllib.error.URLError, OSError) as e:
        raise Offline() from e


def unavailable(code: int = 0) -> str:
    """The download site answered, but not with the installer: say it isn't this computer's connection, and what to do."""
    if code in (403, 404, 410):
        why = "Starchaser's download site doesn't have it to give out at the moment. Your internet connection is working."
        # whoever reads this may be the person who installed Starchaser, so name a step they can take themselves
        then = "Other ways to make one shows how to make a stick on another computer, or try again later."
    else:
        why = (f"Starchaser's download site had a problem (error {code}), not your internet connection." if code
               else "Starchaser's download site sent an empty answer, not your internet connection.")
        then = "Try again in a few minutes."
    return f"The installer isn't available for download right now. {why} {then}"


def fetch_small(url: str) -> bytes:
    resp = opener(url)
    try:
        data = resp.read(SMALL + 1)
    except OSError as e:
        raise Offline() from e
    if len(data) > SMALL:
        raise Refused("The installer's checksum list isn't in the expected form.")
    return data


def throttle(phase: str):
    at = [0.0]

    def report(done: int, total: int) -> None:
        now = time.monotonic()
        if done >= total or now - at[0] >= 0.5:
            at[0] = now
            event(event="progress", phase=phase, done=done, total=total)
    return report


def check_file(p: Path, digest: str) -> bool:
    fd = os.open(p, os.O_RDONLY)
    try:
        size = os.fstat(fd).st_size
        return sha256_file(fd, size, throttle("verify")) == digest
    finally:
        os.close(fd)


def record_verified(name: str, digest: str, sums: bytes, sig: bytes) -> None:
    for suffix, data in ((".SHA256SUMS", sums), (".SHA256SUMS.sig", sig)):
        tmp = CACHE / f".{name}{suffix}.{os.getpid()}.tmp"
        tmp.write_bytes(data)
        tmp.replace(CACHE / (name + suffix))
    st = (CACHE / name).stat()
    state_update(verified={name: {"sha256": digest, "size": st.st_size, "mtime": int(st.st_mtime), "time": int(time.time())}})


def offline_answer(partial: bool = False) -> None:
    have = local_installers()
    # A failed connection to this site doesn't establish whether the rest of the internet works.
    disconnected = False
    try:
        network = subprocess.run(["nmcli", "-t", "-f", "STATE", "general"], capture_output=True,
                                 text=True, timeout=2, env={**os.environ, "LC_ALL": "C"})
        disconnected = network.returncode == 0 and network.stdout.strip() in {"disconnected", "asleep"}
    except (OSError, subprocess.TimeoutExpired):
        pass
    text = ("The download stopped before it finished. Try again: it picks up where it stopped."
            if partial else "Couldn't reach Starchaser's download site, so the newest installer couldn't be downloaded. Try again later.")
    if disconnected:
        text = "This computer is disconnected from the network. Open Network to reconnect, then resume the download. Your progress is saved."
    if have:
        text += f" You can still use the installer downloaded here (version {have[0]['version']})."
    answer(1, ok=False, offline=True, disconnected=disconnected, errors=text, installer=public(have[0] if have else None))


def cmd_download(edition: str = "full") -> None:
    CACHE.mkdir(parents=True, exist_ok=True)
    lock = open(CACHE / ".lock", "w")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        answer(1, ok=False, busy=True, errors="The installer is already downloading in another window.")

    def stop(*_):
        raise Canceled()
    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    try:
        download(edition)
    except Canceled:
        answer(1, ok=False, canceled=True, errors="Download canceled. Try again any time: it picks up where it stopped.")
    except ServerUnavailable as e:
        have = local_installers()
        flags = {"unpublished": True} if isinstance(e, NotPublished) else {}
        answer(1, ok=False, unavailable=True, errors=str(e), installer=public(have[0] if have else None), **flags)
    except KeysMissing as e:
        answer(1, ok=False, keysMissing=True, errors=str(e))
    except EditionMissing as e:
        answer(1, ok=False, editionMissing=True, errors=str(e))
    except Refused as e:
        answer(1, ok=False, errors=str(e))


def download(edition: str = "full") -> None:
    event(event="phase", phase="check")
    try:
        sums, sig = fetch_small(BASE + "SHA256SUMS"), fetch_small(BASE + "SHA256SUMS.sig")
    except Offline:
        offline_answer()
    listed = verify_sums(sums, sig)
    if edition not in listed:
        raise EditionMissing("The online installer isn't available for this version, only the full one. "
                             "Choose Full (works with no internet; bigger), then try again.")
    name, digest = listed[edition]
    older = [n for n in cached_names() if n != name]

    have = [r for r in local_installers() if r["name"] == name]
    if have and have[0]["sha256"] == digest:
        for n in older:
            remove_installer(n)
        answer(0, ok=True, already=True, installer=public(have[0]))
    final, part = CACHE / name, CACHE / f"{name}.part"
    if final.is_file():                                # here but never recorded (or touched since): check it again
        event(event="phase", phase="verify")
        if check_file(final, digest):
            record_verified(name, digest, sums, sig)
            for n in older:
                remove_installer(n)
            answer(0, ok=True, already=True, installer=public(local_installers()[0]))
        final.unlink()

    start = part.stat().st_size if part.is_file() else 0
    try:
        resp = opener(BASE + name, start)
    except Offline:
        offline_answer(partial=start > 0)
    if resp is None:                                   # the server says the part here is already all of it
        total = start
    else:
        if resp.status == 206 and resp.headers.get("Content-Range", "").startswith(f"bytes {start}-"):
            total = int(resp.headers["Content-Range"].rsplit("/", 1)[-1])
        else:
            start, total = 0, int(resp.headers.get("Content-Length") or 0)
        if total <= 0:
            raise Refused(unavailable())
        need = total - start + MARGIN
        free = os_free()
        if free < need:
            spare = sum(r["size"] for r in local_installers() if r["name"] in older)
            if free + spare < need:
                answer(1, ok=False, noSpace=True, need=total - start, free=free,
                       errors=f"Not enough free space to download the installer: it needs {size_text(total - start + MARGIN)} "
                              f"and this computer has {size_text(free)} free. Free up some space, then try again.")
            for n in older:                            # an older copy makes way only when the new one needs its room
                remove_installer(n)
            older = []
            event(event="note", text="The older installer copy was removed to make room for the new one.")
        event(event="phase", phase="download")
        report = throttle("download")
        done = start
        with open(part, "ab" if start else "wb") as out:
            try:
                while True:
                    b = resp.read(1 << 20)
                    if not b:
                        break
                    out.write(b)
                    done += len(b)
                    report(done, total)
            except (OSError, socket.timeout):
                out.flush()
                offline_answer(partial=True)
            out.flush()
            os.fsync(out.fileno())
        if done != total:
            offline_answer(partial=True)
    event(event="phase", phase="verify")
    if not check_file(part, digest):
        part.unlink(missing_ok=True)
        answer(1, ok=False, damaged=True, errors="The download was damaged on the way, so it was thrown away. Try again.")
    part.replace(final)
    record_verified(name, digest, sums, sig)
    for n in older:
        remove_installer(n)
    answer(0, ok=True, installer=public(local_installers()[0]))


def os_free() -> int:
    st = os.statvfs(CACHE)
    return st.f_bavail * st.f_frsize


# ------------------------------------------------------------------ the rest

def cmd_status() -> None:
    have = local_installers()
    d = state_read()
    made = d.get("made") if isinstance(d.get("made"), dict) else None
    parts = [n for n in cached_names() if (CACHE / f"{n}.part").is_file()]
    partial = sum((CACHE / f"{n}.part").stat().st_size for n in parts)
    answer(0, ok=True, installer=public(have[0] if have else None), partial=partial,
           partialEdition=iso_edition(max(parts)) if parts else "", made=made,
           reminded=bool(d.get("reminded")), stickAgeDays=max(0, int((time.time() - made["time"]) / 86400)) if made and made.get("time") else None,
           stale=bool(made and (time.time() - made.get("time", 0) > 180 * 86400 or have and made.get("version") != have[0]["version"])))


def cmd_drives() -> None:
    have = local_installers()
    need = have[0]["size"] if have else 0
    try:
        drives = removable_drives()
    except (OSError, ValueError) as e:
        answer(1, ok=False, errors=f"The USB drives couldn't be read ({e}). Try again.")
    for d in drives:
        d["fits"] = not need or d["size"] >= need
    answer(0, ok=True, drives=drives, need=need, needText=size_text(need) if need else "")


def job_read() -> dict:
    try:
        d = json.loads(JOB.read_text())
        return d if isinstance(d, dict) else {}
    except (OSError, ValueError):
        return {}


def job_write(d: dict) -> bool:
    tmp = JOB.with_name(f".{JOB.name}.{os.getpid()}.tmp")
    try:
        with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
            json.dump(d, f)
            f.flush()
            os.fsync(f.fileno())
        tmp.replace(JOB)
        return True
    except OSError:
        return False


def proc_start(pid: int) -> str:
    """When process pid started ("" when it's gone or a zombie), so a reused pid isn't taken for the runner."""
    try:
        st = Path(f"/proc/{pid}/stat").read_text()
    except OSError:
        return ""
    rest = st[st.rfind(")") + 2:].split()
    return "" if len(rest) < 20 or rest[0] in ("Z", "X") else rest[19]


def job_now() -> dict:
    """The job record; a "running" one whose runner is gone reads as done, with no answer."""
    d = job_read()
    if d.get("state") == "running":
        pid = d.get("pid") if isinstance(d.get("pid"), int) else 0
        if pid <= 0 or proc_start(pid) == "" or proc_start(pid) != d.get("pidStart"):
            message = ("The download stopped before it finished. Try again: it picks up where it stopped."
                       if d.get("kind") == "download" else
                       "Making the stick stopped before it finished. Make it again before you rely on it.")
            d = {**d, "state": "done", "code": 1, "result": {"ok": False, "incomplete": True, "errors": message}}
    return d


def cmd_download_start(edition: str = "full") -> None:
    start_job([sys.executable, str(Path(__file__).resolve()), "download", edition], {"kind": "download", "edition": edition})


def cmd_write(device: str, serial: str, size: str) -> None:
    """The runner is pkexec's parent in a session of its own, so leaving the page or closing Settings leaves the
    write running to the end; this command passes on its progress while it is there to read it, and the job
    record keeps it (and the answer) for a page that comes back. Cancel reaches the helper through its stdin."""
    have = local_installers()
    if not have:
        answer(1, ok=False, errors="Download the installer first.")
    iso = have[0]
    name = iso["name"]
    try:
        digest = sums_digest(parse_sums((CACHE / f"{name}.SHA256SUMS").read_text()), name)
    except (OSError, Refused, UnicodeDecodeError):
        answer(1, ok=False, errors="The downloaded installer's checksum list is missing. Download it again.")
    if digest != iso["sha256"]:
        answer(1, ok=False, errors="The downloaded installer's checksum list doesn't match it. Download it again.")
    if job_now().get("state") == "running":
        answer(1, ok=False, busy=True, errors="A recovery USB stick is already being made.")
    cmd = ["pkexec", HELPER, "write", device, serial, size, iso["path"],
           str(CACHE / f"{name}.SHA256SUMS"), str(CACHE / f"{name}.SHA256SUMS.sig")]
    if os.environ.get("STARCHASER_RECOVERY_USB_HELPER"):
        cmd = cmd[1:]                                  # the tests' stand-in helper runs without pkexec
    start_job(cmd, {"kind": "write", "device": device, "version": iso["version"]})


def start_job(cmd: list, rec: dict) -> None:
    # Serialize launches, including the handoff to the detached runner. Never replace a live job's record.
    try:
        lock = open(JOB.with_suffix(".lock"), "w")
    except OSError:
        answer(1, ok=False, errors="Nothing changed: Settings couldn't save a note it needs in your session folder "
                                   "(is the disk full?). Free up some space, then try again.")
    with lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            answer(1, ok=False, busy=True, errors="A recovery USB job is already running. Return to Recovery to see it.")
        if job_now().get("state") == "running":
            answer(1, ok=False, busy=True, errors="A recovery USB job is already running. Return to Recovery to see it.")
        follow_job(cmd, rec)


def follow_job(cmd: list, rec: dict) -> None:
    rec = {**rec, "id": f"{int(time.time() * 1000)}-{os.getpid()}", "seen": False}
    if not job_write({**rec, "state": "running", "pid": os.getpid(), "pidStart": proc_start(os.getpid()), "phase": "start"}):
        answer(1, ok=False, errors="Nothing changed: Settings couldn't save a note it needs in your session folder "
                                   "(is the disk full?). Free up some space, then try again.")
    rfd, wfd = os.pipe()
    pid = os.fork()
    if pid == 0:
        try:
            os.close(rfd)
            run_job(cmd, rec, wfd)
        finally:
            os._exit(0)
    os.close(wfd)
    signal.signal(signal.SIGTERM, lambda *_: os._exit(1))      # the page went away: the runner carries on
    with os.fdopen(rfd, "r", errors="replace") as lines:
        for line in lines:
            sys.stdout.write(line)
            sys.stdout.flush()
    os.waitpid(pid, 0)
    d = job_now()
    sys.exit(d.get("code", 1) if d.get("id") == rec["id"] else 1)


def run_job(cmd: list, rec: dict, wfd: int) -> None:
    os.setsid()
    signal.signal(signal.SIGHUP, signal.SIG_IGN)
    signal.signal(signal.SIGPIPE, signal.SIG_IGN)
    fd = os.open(os.devnull, os.O_RDWR)
    for n in (0, 1, 2):
        os.dup2(fd, n)
    out = [wfd]

    def tell(line: str) -> None:
        if out:
            try:
                os.write(out[0], (line + "\n").encode())
            except OSError:
                out.clear()                            # nobody reads anymore: keep going, the record has it
    me = {**rec, "state": "running", "pid": os.getpid(), "pidStart": proc_start(os.getpid()), "phase": "start"}
    job_write(me)
    ctl_r, ctl_w = os.pipe()
    try:
        p = subprocess.Popen(cmd, stdin=ctl_r, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="replace")
    except OSError:
        result = {"ok": False, "errors": ("The downloader couldn't start. Try again." if rec.get("kind") == "download" else
                  "The USB writer isn't installed. Install updates in Settings > Updates, then try again.")}
        job_write({**me, "state": "done", "code": 127, "result": result})
        tell(json.dumps(result))
        return
    os.close(ctl_r)
    signal.signal(signal.SIGUSR1, lambda *_: p.terminate() if rec.get("kind") == "download" else os.write(ctl_w, b"cancel\n"))
    last, written = "", 0.0
    for line in p.stdout:
        line = line.rstrip("\n")
        if line.startswith("@@"):
            try:
                ev = json.loads(line[2:])
            except ValueError:
                continue
            if ev.get("event") == "phase":
                me.update(phase=ev.get("phase", ""), done=0, total=0, remaining=None, measured=0)
            elif ev.get("event") == "progress":
                me.update(done=ev.get("done", 0), total=ev.get("total", 0), remaining=ev.get("remaining"), measured=time.time())
            if time.monotonic() - written >= 1 or ev.get("event") == "phase":
                job_write(me)
                written = time.monotonic()
            tell(line)
        elif line.strip():
            last = line
    err = p.stderr.read()[-4000:]
    code = p.wait()
    try:
        result = json.loads(last) if last else {}
    except ValueError:
        result = {}
    if not isinstance(result, dict):
        result = {}
    if code == 0 and result.get("ok") is True and rec.get("kind") != "download":
        state_update(made={"time": int(time.time()), "drive": result.get("drive", ""), "version": rec["version"]})
    job_write({**me, "state": "done", "code": code, "result": result, "err": err})
    tell(json.dumps(result) if result else json.dumps({"ok": False, "code": code, "err": err}))
    if rec.get("kind") == "download" and not result.get("canceled"):
        download_notice(code == 0 and result.get("ok") is True)


def download_notice(ok: bool) -> None:
    token = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "starchaser-notifications" / "token"
    fd = None
    try:
        fd = os.open(token, os.O_RDONLY) if token.is_file() else None
        credential = [f"--credential-fd={fd}"] if fd is not None else []
        subprocess.Popen(["starchaser", "notify", *credential, "-a", "Starchaser", "-i", "drive-removable-media", "-t", "10000",
                        "-A", "open=Choose a USB drive" if ok else "open=Open Recovery",
                        "-h", "string:x-starchaser-settings:recovery",
                        *(["-h", "string:x-starchaser-settings-target:usbdrive"] if ok else []),
                        "The recovery stick download is ready" if ok else "Recovery download didn't finish",
                        "The download was verified. Open Recovery to choose a USB drive. Nothing has been erased." if ok else
                        "Open Settings > Recovery to see what happened and try again."],
                       pass_fds=(fd,) if fd is not None else (), stdin=subprocess.DEVNULL,
                         stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
    except OSError:
        pass
    finally:
        if fd is not None:
            os.close(fd)


def cmd_cancel() -> None:
    d = job_now()
    if d.get("state") != "running":
        answer(0, ok=True, running=False)
    try:
        os.kill(int(d["pid"]), signal.SIGUSR1)
    except (OSError, ValueError, KeyError):
        message = ("The download couldn't be paused. Try again." if d.get("kind") == "download" else
                   "Making the stick couldn't be canceled. It will stop when it finishes.")
        answer(1, ok=False, errors=message)
    answer(0, ok=True, running=True)


def cmd_job() -> None:
    print(json.dumps(job_now()))
    sys.exit(0)


def cmd_job_seen(jid: str) -> None:
    d = job_read()
    if d.get("state") == "done" and d.get("id") == jid:
        job_write({**d, "seen": True})
    sys.exit(0)


def cmd_delete() -> None:
    freed = sum(remove_installer(n) for n in cached_names())
    state_update(verified=None)
    answer(0, ok=True, freed=freed, freedText=size_text(freed))


def cmd_remind() -> None:
    d = state_read()
    # only asks: a welcome closed before its last page was read, or left without an answer, suggests it again
    answer(0, show=not (d.get("made") or d.get("reminded")))


def cmd_remind_seen() -> None:
    state_update(reminded=True)
    sys.exit(0)


def usage_exit(message: str) -> None:
    print(f"starchaser recovery usb: {message}\nRun 'starchaser recovery usb --help' for more help.", file=sys.stderr)
    sys.exit(2)


def main(argv: list) -> None:
    if not argv:
        usage_exit("no command given.")
    cmd = argv[0]
    if cmd in ("-h", "--help", "help") or any(a in ("-h", "--help") for a in argv[1:]):
        print(__doc__.strip())
        sys.exit(0)
    simple = {"status": cmd_status, "drives": cmd_drives, "delete-download": cmd_delete,
              "remind": cmd_remind, "remind-seen": cmd_remind_seen, "job": cmd_job, "cancel": cmd_cancel}
    if cmd in simple:
        if len(argv) != 1:
            usage_exit(f"{cmd} takes nothing after it (got {argv[1]!r}).")
        simple[cmd]()
    elif cmd in ("download", "download-start"):
        if len(argv) > 2 or argv[1:] and argv[1] not in EDITIONS:
            usage_exit(f"{cmd} takes full or online (got {' '.join(argv[1:])!r}).")
        (cmd_download if cmd == "download" else cmd_download_start)(*argv[1:])
    elif cmd == "write":
        if len(argv) != 4 or not argv[3].isdigit():
            usage_exit("write needs DEVICE SERIAL SIZE (from drives).")
        cmd_write(*argv[1:])
    elif cmd == "job-seen":
        if len(argv) != 2:
            usage_exit("job-seen needs the job's id (from job).")
        cmd_job_seen(argv[1])
    else:
        usage_exit(f"unknown command {cmd!r}.")


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