#!/usr/bin/env python3
"""starchaser-recovery-usb-admin: writes the Starchaser installer to a USB stick for Settings > Recovery.

    starchaser-recovery-usb-admin write <device> <serial> <size> <iso> <SHA256SUMS> <SHA256SUMS.sig>
        erase the USB drive <device> (it must still be the drive with that serial number and size in bytes) and
        write the installer to it, then read it back to check it. Streams progress as "@@{json}" lines; the last
        line is the JSON answer. A line on stdin, or stdin closing, cancels.
    starchaser-recovery-usb-admin commands   JSON list of the commands (read-only, no root needed)
"""
# Run through pkexec (org.starchaser.recovery-usb.policy: one action per command, the password every time), from
# bin/starchaser-recovery-usb write. Installed root-owned beside starchaser-admin, so code the user can edit never
# runs as root. Root trusts nothing the caller says about the files: the checksum list's signature is checked here
# with the root-owned keyring, the ISO must match it before anything is erased, and again as it is written, and the
# stick must read back the same. The drive is checked again here too (recovery_usb.drive_problem), so a built-in disk
# can't be erased whatever the caller asks.
import fcntl
import contextlib
import fleet_media
import json
import os
import stat
import subprocess
import sys
import time
import unicodedata
from pathlib import Path

from recovery_usb import (DEVICE, Canceled, Refused, Unplugged, copy_image, drive_name, drive_problem, lsblk,
                          read_back, sha256_file, size_text, stdin_says_stop, sums_digest, verify_sums)

COMMANDS = {"write": 6, "fleet-write": 7}       # command -> words after it; each has its own action in org.starchaser.recovery-usb.policy
SMALL_FILE = 64 * 1024


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)



def estimate_seconds(done, total, elapsed):
    return max(0, (total - done) * elapsed / done) if elapsed >= 10 and 0 < done < total else None

class Throttle:
    """Progress at most every half second (and always the last one), so a fast stick doesn't flood the page."""
    def __init__(self, phase: str):
        self.phase, self.at = phase, 0.0
        self.started = time.monotonic()

    def __call__(self, done: int, total: int) -> None:
        now = time.monotonic()
        if done >= total or now - self.at >= 0.5:
            self.at = now
            event(event="progress", phase=self.phase, done=done, total=total, remaining=estimate_seconds(done, total, time.monotonic() - self.started))


def caller_uid() -> int:
    try:
        return int(os.environ.get("PKEXEC_UID", ""))
    except ValueError:
        return -1


def open_caller_file(path: str, limit: int = 0) -> int:
    """Open a file the person who asked owns, never through a link: root reads only their own download."""
    uid = caller_uid()
    try:
        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC)
    except OSError:
        raise Refused("The downloaded installer is missing. Download it again.") from None
    st = os.fstat(fd)
    if not stat.S_ISREG(st.st_mode) or st.st_uid != uid or (limit and st.st_size > limit):
        os.close(fd)
        raise Refused("The downloaded installer isn't where Settings keeps it. Download it again.")
    return fd


def read_small(path: str) -> bytes:
    fd = open_caller_file(path, SMALL_FILE)
    try:
        return os.read(fd, SMALL_FILE)
    finally:
        os.close(fd)


def unmount(dev: dict) -> None:
    """Unmount the stick's partitions (Files may have opened them); refuse when something still uses them."""
    def walk(d):
        for m in d.get("mountpoints") or []:
            if m:
                yield d["path"], m
        for c in d.get("children") or []:
            yield from walk(c)
    for part, _ in sorted(set(walk(dev)), key=lambda x: -len(x[1])):
        r = subprocess.run(["umount", part], capture_output=True, text=True, timeout=60)
        if r.returncode != 0:
            raise Refused("Something is still using a file on the drive. Close any windows showing it, then try again.")


def flush_buffers(fd: int) -> None:
    """Drop the kernel's cached copy of the stick, so reading back reads the stick itself (best-effort)."""
    try:
        fcntl.ioctl(fd, 0x1261)                        # BLKFLSBUF
    except OSError:
        pass
    try:
        os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)
    except OSError:
        pass


def authorization_label(dev):
    name = ''.join(c for c in drive_name(dev) if not unicodedata.category(c).startswith('C'))
    return ' '.join(name.split())[:100] + ' (' + size_text(dev.get('size')) + ')'


def authorize_write(dev, fleet=False):
    """The pkexec entry only validates. The separate action authorizes each actual erase."""
    uid = os.environ.get('PKEXEC_UID')
    if uid is None:
        return  # An already-root caller has administrator authority independently of polkit.
    parent = os.getppid()
    try:
        uid = int(uid)
        if uid == 0:
            return
        if uid < 0:
            raise ValueError('uid')
        status = Path(f'/proc/{parent}/status').read_text()
        uids = next(line.split()[1:] for line in status.splitlines() if line.startswith('Uid:'))
        if any(int(value) != uid for value in uids):
            raise ValueError('caller')
        start = Path(f'/proc/{parent}/stat').read_text().rsplit(')', 1)[1].split()[19]
    except (OSError, ValueError, StopIteration, IndexError):
        raise Refused('The requesting session ended. Nothing was erased.') from None
    action = 'org.starchaser.recovery-usb.erase-fleet' if fleet else 'org.starchaser.recovery-usb.erase'
    result = subprocess.run(['/usr/bin/pkcheck', '--action-id', action, '--process', f'{parent},{start},{uid}',
                             '--allow-user-interaction', '--detail', 'drive', authorization_label(dev)],
                            capture_output=True, text=True)
    if result.returncode != 0:
        raise Refused('No password was approved. Nothing was erased.')


def write(device: str, serial: str, size_word: str, iso: str, sums: str, sig: str, profile: str = "") -> None:
    if not DEVICE.fullmatch(device) or not size_word.isdigit():
        answer(2, ok=False, errors="That isn't a USB drive Settings can write to. Nothing was changed.")
    found = lsblk(device)
    dev = found[0] if len(found) == 1 else None
    if dev is None:
        answer(1, ok=False, unplugged=True, errors="The USB drive isn't plugged in anymore. Nothing was changed.")
    why = drive_problem(dev)
    if why:
        answer(1, ok=False, errors=f"That drive can't be used: it is {why}. Nothing was changed.")
    # the same stick the person picked, not another one plugged into the same place since
    if int(dev.get("size") or 0) != int(size_word) or (dev.get("serial") or "").strip() != serial:
        answer(1, ok=False, changed=True, errors="The USB drive changed since you picked it. Pick it again. Nothing was changed.")
    authorize_write(dev, fleet=bool(profile))
    name = drive_name(dev)

    event(event="phase", phase="check")
    # the list names the full installer and maybe the online one: this file must be one of them
    digest = sums_digest(verify_sums(read_small(sums), read_small(sig)), os.path.basename(iso))
    if not digest:
        raise Refused("The downloaded installer isn't one its checksum list names. Download it again.")
    src = open_caller_file(iso)
    size = os.fstat(src).st_size
    if size > int(size_word):
        answer(1, ok=False, small=True, errors=f"The installer doesn't fit on {name}. Use a larger USB drive. Nothing was changed.")
    if sha256_file(src, size, Throttle("check"), stdin_says_stop) != digest:
        answer(1, ok=False, damaged=True, errors="The downloaded installer is damaged. Download it again. Nothing was changed.")

    with contextlib.ExitStack() as cleanup:
        if profile:
            try:
                config = fleet_media.validate(json.loads(read_small(profile)))
                original = src
                cleanup.callback(os.close, original)
                prepared, size, digest = cleanup.enter_context(fleet_media.image(original, config, digest))
                src = os.dup(prepared)
            except (ValueError, OSError, subprocess.SubprocessError) as error:
                raise Refused(str(error)) from None
            if size > int(size_word):
                raise Refused("The fleet installer doesn't fit on this USB drive. Nothing was erased.")
        # Preparing a fleet image can take several minutes. Re-identify the selected drive immediately before writing.
        current = lsblk(device)
        dev = current[0] if len(current) == 1 else None
        if dev is None or drive_problem(dev) or int(dev.get("size") or 0) != int(size_word) or (dev.get("serial") or "").strip() != serial:
            raise Refused("The USB drive changed while the installer was being prepared. Pick it again. Nothing was erased.")
        unmount(dev)
        event(event="phase", phase="write")
        try:
            # O_EXCL: the kernel refuses while anything has the drive or one of its parts mounted
            dst = os.open(device, os.O_RDWR | os.O_EXCL | os.O_CLOEXEC)
        except OSError:
            answer(1, ok=False, errors="Something is still using the drive. Close any windows showing it, then try again. Nothing was changed.")
        erased = False
        try:
            end = int(size_word)
            # a partition table's backup copy lives at the very end of a drive: clear the old one, or some computers
            # see two disagreeing tables on the finished stick
            if end - size > 1 << 20:
                os.lseek(dst, end - (1 << 20), os.SEEK_SET)
                os.write(dst, bytes(1 << 20))
            os.lseek(dst, 0, os.SEEK_SET)
            erased = True
            if copy_image(src, dst, size, Throttle("write"), stdin_says_stop, device) != digest:
                answer(1, ok=False, damaged=True, incomplete=True,
                       errors=f"The installer file changed while it was being written, so {name} isn't usable. Download it again, then make the stick again.")
            os.fsync(dst)
            flush_buffers(dst)
            event(event="phase", phase="verify")
            if read_back(dst, size, Throttle("verify"), stdin_says_stop, device) != digest:
                answer(1, ok=False, incomplete=True, verifyFailed=True,
                       errors=f"{name} didn't read back the same as the installer, so it may be worn out or damaged. Try another USB drive.")
        except Canceled:
            answer(1, ok=False, canceled=True, incomplete=erased,
                   errors=f"Canceled. {name} is only partly written: make the stick again before you rely on it." if erased else "Canceled. Nothing was changed.")
        except Unplugged:
            answer(1, ok=False, unplugged=True, incomplete=True,
                   errors=f"{name} was unplugged before it was finished. Plug it back in and make the stick again.")
        except OSError as e:
            answer(1, ok=False, incomplete=True,
                   errors=f"{name} stopped taking data ({e.strerror or 'write error'}). Try again, or try another USB drive.")
        finally:
            os.close(dst)
            os.close(src)
        try:
            subprocess.run(["udevadm", "trigger", "--action=change", device], capture_output=True, timeout=10)  # best-effort: Files sees the new contents
        except (OSError, subprocess.SubprocessError):
            pass
        answer(0, ok=True, drive=name, size=size, sha256=digest)


def main(argv: list) -> None:
    cmd = argv[0] if argv else ""
    if cmd in ("-h", "--help", "help") or any(a in ("-h", "--help") for a in argv[1:]):
        print(__doc__.strip())
        return
    if cmd == "commands":
        print(json.dumps({"ok": True, "commands": sorted(COMMANDS)}))
        return
    if COMMANDS.get(cmd) != len(argv) - 1:
        print(json.dumps({"ok": False, "errors": "starchaser-recovery-usb-admin only writes a recovery USB stick; nothing was changed."}))
        sys.exit(2)
    if os.geteuid() != 0:
        print(json.dumps({"ok": False, "errors": "run through pkexec"}))
        sys.exit(1)
    try:
        write(*argv[1:])
    except Refused as e:
        answer(1, ok=False, errors=str(e))
    except Canceled:                                   # while checking the installer, before anything was erased
        answer(1, ok=False, canceled=True, errors="Canceled. Nothing was changed.")


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