#!/usr/bin/env python3
"""starchaser-install: the Starchaser Linux install engine (runs as root on the live ISO).

The graphical installer, the text installer and the test campaign all drive this one program with an answers
file, so every install takes the same path.

    starchaser-install disks                 JSON: drives, their partitions and free space, what each holds
                                             (Windows, BitLocker, Linux), how far each can shrink; TPM, UEFI
    starchaser-install check <answers.json>  JSON: the plan in words ("Erase ...", "Shrink ... to ...") or the problems
    starchaser-install peek [--passphrase-stdin] <partition>
                                             JSON: look inside a partition read-only (used space, first folders); an
                                             encrypted one opens with the passphrase given as one line on stdin
    starchaser-install wizard                the text installer: the graphical installer's questions in the console
                                             (for a computer whose graphics can't start it), then the same run
    starchaser-install run <answers.json>    do it. Progress as "@@{json}" lines (same protocol as Settings >
                                             Updates); everything is logged to /var/log/starchaser-install.log
                                             (copied onto the new system)

Answers (JSON; the file is read once and removed by `run`, since it holds passwords):
    disk         "/dev/nvme0n1"
    mode         "erase"   the whole drive
                 "free"    the largest free space on it (dual boot next to what's there)
                 "shrink"  shrink one partition ("shrink": {"partition": "/dev/nvme0n1p3", "size_mib": 200000}) and
                           install in the space it frees
    encrypt      "tpm-pin" (chip + PIN; laptop default) | "tpm" (chip only; desktop default) | "passphrase" | "none"
    pin          with encrypt = tpm-pin, 8 or more characters; private input only
    passphrase   with encrypt = passphrase
    user         {"name": "Alex Doe", "username": "alex", "password": "..."}
    hostname     "my-laptop"
    timezone     "America/Los_Angeles"
    keymap       "us"            the console's keymap;   xkb_layout "us" the desktop's ("de", "us(dvorak)", ...)
    locale       "en_US.UTF-8"
    autologin    false           log in at boot without the login screen
    keyring_unencrypted false    with autologin: also keep the saved-passwords keyring unencrypted (its own opt-in;
                                 otherwise it stays locked with the account password and apps may ask to unlock it)
    ssh          false           remote login (SSH) on; the firewall lets it in on networks you trust (the welcome asks)
    trust_network false          with ssh: the network this computer is installed on (the connection the live system
                                 is online through) counts as a network you trust, so SSH and the fleet reach it from
                                 the first start; the welcome still asks about every other network
    authorized_keys []           SSH public keys for the user ("live" = the keys root has on the live system: tests)
    sudo_nopasswd false          sudo without a password (a fleet of machines run unattended); otherwise it asks for yours
    fleet_token, fleet_name      a join token and the fleet name to join with: copied, root-only, to the new system's
                                 /etc/starchaser/firstboot.json and never printed (fleet rules 16.9, 25.2)
    remote_desktop false         Sunshine, so Moonlight on your other devices can see and control this computer
    displays     the screens as the graphical installer left them, the one it ran on marked "primary" (the layout
                 JSON of starchaser displays: [{"desc", "name", "mode", "x", "y", "scale", "transform", "primary"}]):
                 the new account's monitor layout, so the first sign-in opens on that screen, turned the same way
    desktop_source "auto" (default: package from an offline repo, repo_url or the online repo; the checkout when
                 none was supplied and the online repo can't be reached), "package", or "checkout"
    channel      "release" (default) or "testing"
    repo_url     http(s) repo base or URL ending in /$repo/$arch (default downloads.starchaserlinux.org)
    pkgrepo_dir  live system's offline repo folder (default /usr/share/starchaser/pkgrepo/x86_64)
    repo         where the Starchaser checkout is on the live system (default /usr/share/starchaser/repo)

Other drives (all optional; without them the install is exactly the single-drive one; see DRIVE-OPTIONS.md):
    disk_id      the system drive's id from `disks`: refused if the drive at "disk" no longer has it
    drives       [{"disk", "id", "use": "leave" | "files" | "home", "name": "Data"}]: a files drive is erased and
                 appears at /mnt/<name>; a home drive holds /home; both locked with the system's unlock
    keep         [{"partition", "uuid", "name", "passphrase"?}]: used as it is at /mnt/<name> (never formatted);
                 an encrypted one gets an added key that opens it with the system (its passphrase stays)
    mode         "manual" + "manual": {"drives": [{"disk", "id", "new_table", "delete": [{"partition", "uuid"}],
                 "existing": [{"partition", "uuid", "mount", "format"?, "passphrase"?}], "create": [{"size_mib",
                 "fs": btrfs|ext4|xfs|fat32|swap, "mount", "encrypt", "esp", "start"?}]}]}

Layouts:
    erase   GPT: 5 GiB EFI system partition at /boot (4 GiB startup files, 1 GiB Starchaser Recovery), the rest Starchaser
    dual    the drive's EFI partition (Windows' is often 100 MB: too small for Linux kernels) at /efi, holding only
            systemd-boot, which finds Windows by itself; a new 5 GiB XBOOTLDR at /boot for the kernels and Recovery; Starchaser
            in the free (or freed) space. Nothing else on the drive is touched.
    Starchaser: LUKS2 (unless encrypt = none) -> btrfs, subvolumes @ @home @log @pkg @snapshots, zstd.
"""
import contextlib
import datetime
import fcntl
import glob
import importlib.machinery
import importlib.util
import ipaddress
import json
import math
import os
import re
import secrets
import shlex
import shutil
import signal
import stat
import subprocess
import sys
import tempfile
import threading
import time
import traceback
from pathlib import Path

# In the ISO this module is beside the installed helpers; in a checkout it is in system/.
for _lib in (Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser", Path("/usr/local/lib/starchaser")):
    if (_lib / "pkgrepo.py").is_file():
        sys.path.insert(0, str(_lib))
        break
import drive_unlock
import hardware
import safegfx
import install_language
import installer_media
import kernels
import live_packages
import pkgrepo
import planned_restart
import secure_boot as signed_boot

LOG = Path("/var/log/starchaser-install.log")
MNT = Path("/mnt")
MAPPER = "cryptroot"
LOCK = Path("/run/starchaser-install.lock")
PACMAN_CONFIG = Path("/etc/pacman.conf")
# package servers the "online" checks try in turn (both installers): one that's blocked or down mustn't keep a working
# connection from going on
CHECK_URLS = ("https://geo.mirror.pkgbuild.com/", "https://mirrors.kernel.org/archlinux/",
              "https://mirror.rackspace.com/archlinux/")
MIB = 1024 * 1024
GIB = 1024 * MIB
MIN_ROOT = 24 * GIB                  # the smallest Starchaser we install into (desktop + room to update)
NEED_FREE = MIN_ROOT + GIB           # what Starchaser needs freed or free on a drive: the system and its boot partition
NEED_DRIVE = MIN_ROOT + 2 * GIB      # the smallest drive offered at all (a little room for the partition table)
SECURE_BOOT_VAR = "/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c"
# Names a new account can't take: users and groups the new system has or its packages create (base, desktop, login
# screen, firewall, ...). The live system's own lists are added at check time; its "live" account is not on the new
# system, so it stays allowed.
RESERVED_NAMES = set("""
root bin daemon nobody adm alpm audio avahi clock dbus disk empower floppy ftp games git greeter http input kmem kvm
lock log lp mail mem network optical pcscd polkitd power proc render rfkill scanner sgx smmsp storage sys tss tty users
utmp uucp uuidd video wheel systemd-coredump systemd-imds systemd-journal systemd-journal-remote systemd-network
systemd-oom systemd-resolve systemd-timesync flatpak gamemode rtkit colord geoclue usbguard opensnitch nm-openvpn
nvidia-persistenced brltty cups dnsmasq named sshd ntp seat seatd realtime wsdd sunshine claude
""".split())
XBOOTLDR = "BC13C2FF-59E6-4262-A352-B275FD6F7172"
ESP_TYPE = "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"
LINUX_TYPE = "0FC63DAF-8483-4772-8E79-3D69D8477DE4"
# No kernel here: the installed system gets only Starchaser's kernels (kernel_targets), after its package repo is set
# up. mkinitcpio is named because without a kernel in the list nothing else brings it in before the startup step.
BASE = ["base", "mkinitcpio", "linux-firmware", "sof-firmware", "btrfs-progs", "cryptsetup", "sudo", "openssh",
        "networkmanager", "wireless-regdb", "base-devel", "git", "vim", "nano", "terminus-font", "tpm2-tss",
        "man-db", "man-pages", "texinfo", "reflector", "zram-generator", "efibootmgr", "dosfstools", "ntfs-3g",
        "plymouth", "inetutils", "systemd-ukify", "sbsigntools", "mokutil", "openssl"]
# other drives (DRIVE-OPTIONS.md): every drive of at least 1 GB is listed; only big enough ones can hold Starchaser
MIN_LISTED = 10 ** 9
MIN_HOME = 8 * 10 ** 9                # a drive for the home folder: at least this (decimal, as the message says)


def typed_gb(gb) -> int:
    """The bytes the Advanced editor sends for a size typed in GB: decimal GB (as size_text prints), in whole MiB."""
    return round(gb * 10 ** 9 / MIB) * MIB


# The EFI (or boot) partition that holds the kernels, in Advanced. Decimal GB, exactly as the editor sends them
# (2 GB arrives as 1907 MiB, 4 GB as 3815 MiB), so typing the size a message asks for always passes.
MIN_ESP = typed_gb(2)                 # a new or formatted one: refused below this
WARN_ESP = typed_gb(4)                # ... and below this it is allowed with a warning (NVIDIA + several kernels)
# A kept one is judged by its free space, by the same two limits less what FAT32's own tables take from a new
# partition (two FATs are about 8 MiB on 4 GiB), so a partition this installer made itself passes when it is empty.
FAT_OVERHEAD = 32 * MIB
KEPT_BOOT_MIN = MIN_ESP - FAT_OVERHEAD
KEPT_BOOT_WARN = WARN_ESP - FAT_OVERHEAD
# A kept EFI partition at /efi only gets the startup loader (kernels go on /boot). Measured: systemd-boot is 0.2 MB
# and is written twice (0.4 MB); the signed set (shim 1 MB, its key manager 0.9 MB, the signed loader 0.2 MB) is at
# most written twice plus one copy in flight, about 5 MB. 16 MB leaves three times that, and a 100 MB Windows EFI
# partition (96 MiB file system, usually 26 to 40 MiB used) passes with room to spare.
KEPT_LOADER_BYTES = 16 * 10 ** 6
KEYS_DIR = Path("/run/starchaser-keys")          # keyfiles for extra drives while installing (tmpfs, 0700)
TABLES_DIR = Path("/run/starchaser-tables")      # each changed drive's partition table as it was (sfdisk --dump)
PEEK_DIR = Path("/run/starchaser-peek")
NEWVOL_DIR = Path("/run/starchaser-newvol")      # where a new home drive is mounted for a moment to add @home
PEEK_MAPPER = "starchaser-peek"
FAIL_AT = Path("/run/starchaser-test-fail-at")   # tests only (live ISO): a phase name to stop at on purpose
# keyslots that open with a keyfile (64 random bytes): a slow, memory-hard key derivation guards weak passphrases
# and adds nothing to a random key, while several argon2 unlocks at once at startup (up to 1 GiB each) took over
# 10 s and timed out the drive's mount. Passphrase and recovery-key slots keep cryptsetup's default (argon2id)
KEYFILE_PBKDF = ("--pbkdf", "pbkdf2", "--pbkdf-force-iterations", "1000")
MS_RESERVED = "E3C9E316-0B5C-4DB8-817D-F92DF00215AE"
WIN_RECOVERY = "DE94BBA4-06D1-4D40-A16A-BFD50179D6AC"
SWAP_TYPE = "0657FD6D-A4AB-43C4-84E5-0933C84B4F4F"
KEEP_FS = ("ext4", "btrfs", "xfs", "exfat", "ntfs")
# read-only probe mounts that never replay a journal or change anything on the partition
PEEK_MOUNT = {"ext4": ("ext4", "ro,noload"), "btrfs": ("btrfs", "ro,rescue=nologreplay"),
              "xfs": ("xfs", "ro,norecovery"), "ntfs": ("ntfs3", "ro"), "exfat": ("exfat", "ro"), "vfat": ("vfat", "ro")}
MANUAL_FS = ("btrfs", "ext4", "xfs", "fat32", "swap")
FS_WORD = {"btrfs": "btrfs", "ext4": "ext4", "xfs": "xfs", "fat32": "FAT32", "swap": "swap"}
SYSTEM_MOUNTS = ("/", "/boot", "/efi", "/home", "/var", "/srv", "/opt")
LIVE_USB = "That's the USB stick the installer runs from."
BOOT_FAT = ("A partition at /boot or /efi must be FAT32 and can't be encrypted: the computer reads it before "
            "anything is unlocked.")
ESP_NEEDED = ("Starchaser needs an EFI system partition: FAT32, at least 2 GB (4 GB is best), mounted at /boot. "
              "(Or keep the one that's there at /efi and add a FAT32 /boot of at least 2 GB.)")
BITLOCKER_KEEP = "Windows keeps this locked with BitLocker. Starchaser can't open it; it stays as it is."


# --------------------------------------------------------------------------------------------- plumbing
_log = None


def log(line: str) -> None:
    global _log
    if _log is None:
        LOG.parent.mkdir(parents=True, exist_ok=True)
        _log = open(LOG, "a", buffering=1)
    _log.write(time.strftime("%H:%M:%S ") + line.rstrip("\n") + "\n")


PHASE = ""                            # the phase the install is in (for a plain message when something breaks)
PASSWORD_CODE_WORDS = ("If you forget your password and no one can help, choose \"Can't log in?\" or \"Can't unlock?\", "
                       "then Use my password recovery code, and set a new password with it. Write it down and keep it somewhere "
                       "safe, away from this computer. It works once; then make a new one in Settings > Users.")
PASSWORD_CODE = ""                    # the account's password recovery code, shown once when the install is done
SECURE_BOOT_CODE = ""                 # physical enrollment, shown on success only and never logged
# what this attempt set up, so a failure can undo exactly that and nothing else (never a /mnt or a partition that
# was there before it started)
#   mounted   /mnt is this attempt's
#   opened    encrypted volumes this attempt opened (mapper names, in order)
#   new_parts (disk, partition, unique id) of every partition this attempt made, on any drive
#   keyslots  (partition, keyfile) for each key this attempt ADDED to a kept encrypted partition (removed by that
#             same keyfile on a failure: the person's own disk key is never touched)
#   lost      what can't be undone happened (a partition deleted or formatted, another drive erased): "manual" | "drives"
STATE = {"mounted": False, "opened": [], "new_parts": [], "keyslots": [], "keys_dir": False, "lost": "", "signed_boot_files": {}}


def emit(**ev) -> None:
    global PHASE
    if ev.get("event") == "phase":
        PHASE = ev.get("phase", "")
    # the disk key goes to the screen only: the log is copied onto the new system and gets shared for help
    logged = dict(ev, key="(shown on screen; not logged)") if ev.get("event") == "recovery-key" else \
        dict(ev, code="(shown on screen; not logged)") if ev.get("event") in ("password-code", "secure-boot-code") else \
        dict(ev, lines=f"({len(ev.get('lines', []))} lines from above)") if ev.get("event") == "log" else ev
    log("@@" + json.dumps(logged))
    print("@@" + json.dumps(ev), flush=True)
    # tests only, and only on the live ISO: stop at a named phase to prove the rollback
    if ev.get("event") == "phase" and Path("/run/archiso").is_dir():
        try:
            want = FAIL_AT.read_text().strip()
        except OSError:
            want = ""
        if want and want == ev.get("phase"):
            fail(f"Stopped on purpose at {want} (a test).")


_lock = None                          # the open lock file while this process runs an install (see run())


class Busy(Exception):
    """Another install holds the lock: stop without undoing anything (it would be the other install's work)."""


class Stop(Exception):
    """The install can't go on: the message is for the person installing. run() undoes what this attempt set up
    and reports it."""


class CommandFailed(Stop):
    """A command the install ran failed (sh's check): the message is the command's own last line, for the log and the
    details only. The install's failure page says it in a plain sentence instead (run())."""


def fail(msg: str) -> None:
    raise Stop(msg)


def sh(*cmd, check=True, input=None, quiet=False) -> subprocess.CompletedProcess:
    """Run a command, log it (never its input: that's where passwords go), return its output."""
    if cmd and str(cmd[0]) == 'pacman':
        import tested_releases
        tested_releases.guard_installer(cmd)
    log("$ " + " ".join(str(c) for c in cmd))
    r = subprocess.run([str(c) for c in cmd], capture_output=True, text=True, input=input)
    for l in (r.stdout + r.stderr).splitlines():
        log("  " + l)
    if check and r.returncode != 0:
        raise CommandFailed(f"{Path(str(cmd[0])).name} failed: " + ((r.stderr or r.stdout).strip().splitlines() or ["no output"])[-1])
    return r


def desktop_step(line):
    steps = {
        "Packages (official repos only)": "Installing desktop apps",
        "32-bit graphics driver for games (matches this computer's GPU)": "Setting up graphics support",
        "Starchaser screensaver and editor colors built from this checkout": "Setting up the screensaver and text editor",
        "Native app window colors": "Setting up app colors",
        "Starchaser tools -> ~/.local/bin": "Adding your desktop tools",
        "Hyprland config, scripts, corner shaders": "Setting up your windows and keys",
        "Quickshell: cockpit, settings, menu, lock screen, welcome, Ask": "Setting up your desktop controls",
        "App configs": "Setting up your apps",
        "System: power key, services": "Setting up power and background services",
        "Idle timers and theme": "Applying your look and screen settings",
    }
    return steps.get(line, "")


def stream(cmd, phase: str, total: int = 0, on_line=None) -> int:
    """Run a long command (pacstrap, the desktop setup), turning its "(n/N) installing x" lines into progress."""
    if cmd and str(cmd[0]) == 'pacman':
        import tested_releases
        tested_releases.guard_installer(cmd)
    log("$ " + " ".join(cmd))
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, errors="replace")
    done = 0
    for line in p.stdout:
        line = line.rstrip("\n")
        log("  " + line)
        m = re.match(r"\(\s*(\d+)/(\d+)\) (installing|upgrading|reinstalling) (\S+)", line)
        if m:
            done += 1
            emit(event="progress", phase=phase, done=done, total=max(total, int(m.group(2))), item="Installing system software")
        elif phase == "desktop" and line.startswith("==> "):
            # Only our own setup milestones belong on the progress card. Keep every raw
            # package/tool line in the log for Show details.
            step = desktop_step(line[4:])
            if step:
                emit(event="step", phase=phase, text=step)
        if on_line:
            on_line(line)
    return p.wait()


def part_path(disk: str, n: int) -> str:
    return f"{disk}p{n}" if disk[-1].isdigit() else f"{disk}{n}"


# --------------------------------------------------------------------------------------------- looking at drives
def tpm2() -> bool:
    try:
        return Path("/sys/class/tpm/tpm0/tpm_version_major").read_text().strip() == "2"
    except OSError:
        return False


def iso_age_note(path=Path("/usr/share/starchaser/iso-build"), now=None):
    try:
        text = path.read_text()
        match = re.search(r"^build-date: (\d{4}-\d{2}-\d{2})", text, re.M)
        if match:
            date = datetime.date.fromisoformat(match[1])
        else:
            from email.utils import parsedate_to_datetime
            date = parsedate_to_datetime(" ".join(text.splitlines()[0].split()[1:7])).date()
        age = (datetime.datetime.fromtimestamp(now or time.time(), datetime.timezone.utc).date() - date).days
        return (f"This installer stick was built on {date.isoformat()}, more than 30 days ago. "
                "A newer installer may be available at starchaserlinux.org/download.") if age > 30 else ""
    except (OSError, ValueError, IndexError, TypeError):
        return ""


def live_disks() -> set:
    """The drive(s) the live ISO booted from (never offered). Every disk under the boot source, not just its
    parent: booted through Ventoy the source is /dev/mapper/ventoy, whose parent is the stick's partition (sdb1),
    and comparing that with the disks offered let the stick the installer runs from be picked and erased."""
    src = subprocess.run(["findmnt", "-n", "-o", "SOURCE", "/run/archiso/bootmnt"], capture_output=True, text=True).stdout.strip()
    # A copy-to-RAM boot can unmount bootmnt. The volume label still identifies the source stick.
    labeled = subprocess.run(["blkid", "-t", "LABEL=STARCHASER", "-o", "device"], capture_output=True, text=True).stdout.split()
    found = set()
    for source in set(([src] if src else []) + labeled):
        rows = subprocess.run(["lsblk", "-s", "-n", "-l", "-o", "TYPE,PATH", source], capture_output=True, text=True).stdout
        parents = {path.strip() for typ, _, path in (l.strip().partition(" ") for l in rows.splitlines())
                   if typ == "disk" and path.strip()}
        if not parents:
            pk = subprocess.run(["lsblk", "-n", "-o", "PKNAME", source], capture_output=True, text=True).stdout.strip()
            parents = {"/dev/" + pk.splitlines()[0].strip()} if pk else {source}
        found.update(parents)
    return found


NTFS_CHECK = ("Windows wants to check this drive before it can be shrunk. Start Windows once, let it finish, and "
              "shut it down normally, then try again.")
NTFS_FAST = ("Windows didn't fully shut down (Fast Startup or hibernation). In Windows: hold Shift while choosing Shut "
             "down, or turn off Fast Startup in Power Options, then try again.")


def ntfs_info(dev: str) -> dict:
    """How small an NTFS partition can go, and whether it's safe to touch (not hibernated, not waiting for Windows'
    disk check). Asked without --force: forcing skips ntfsresize's own refusal of a volume marked for checking."""
    if not shutil.which("ntfsresize"):
        return {"blocked": "This installer can't shrink Windows (a tool it needs is missing)."}
    r = subprocess.run(["ntfsresize", "--info", "--no-action", dev], capture_output=True, text=True)
    out = r.stdout + r.stderr
    if re.search(r"hibernat|Fast Restart|unclean", out, re.I):
        return {"blocked": NTFS_FAST}
    if re.search(r"scheduled for check|chkdsk|inconsistent|dirty", out, re.I):
        return {"blocked": NTFS_CHECK}
    m = re.search(r"You might resize at (\d+) bytes", out)
    if r.returncode != 0 or not m:
        return {"blocked": "This Windows partition can't be measured for shrinking (" + (out.strip().splitlines() or ["?"])[-1] + ")."}
    return {"min": int(m.group(1))}


def linux_min(dev: str, fs: str, mounted_used: int) -> int:
    """The least an ext4 or btrfs partition can shrink to, measured (0 = couldn't be measured). FSUSED is there only
    for a mounted file system; an unmounted one is asked directly: resize2fs's own estimate for ext4, the space
    btrfs has handed out on the device (what a shrink has to keep) for btrfs. Nothing is mounted to find out."""
    if mounted_used:
        return mounted_used
    try:
        if fs == "ext4":
            hdr = subprocess.run(["dumpe2fs", "-h", dev], capture_output=True, text=True).stdout
            bs = int(re.search(r"^Block size:\s+(\d+)", hdr, re.M).group(1))
            est = re.search(r"minimum size of the filesystem: (\d+)",
                            subprocess.run(["resize2fs", "-P", dev], capture_output=True, text=True).stdout)
            if est:
                return int(est.group(1)) * bs
            cnt = int(re.search(r"^Block count:\s+(\d+)", hdr, re.M).group(1))
            free = int(re.search(r"^Free blocks:\s+(\d+)", hdr, re.M).group(1))
            return (cnt - free) * bs
        if fs == "btrfs":
            out = subprocess.run(["btrfs", "filesystem", "show", "--raw", dev], capture_output=True, text=True).stdout
            if len(re.findall(r"^\s*devid\s", out, re.M)) != 1:
                return 0                                    # several devices: not something to shrink here
            return int(re.search(r"^\s*devid\s+\d+\s+size\s+\d+\s+used\s+(\d+)", out, re.M).group(1))
    except (AttributeError, ValueError, OSError):
        pass
    return 0


def _lsblk() -> dict:
    out = subprocess.run(["lsblk", "-J", "-b", "-o", "NAME,PATH,SIZE,TYPE,FSTYPE,LABEL,MODEL,PARTTYPE,PARTLABEL,"
                          "MOUNTPOINT,RM,TRAN,ROTA,PTTYPE,FSAVAIL,FSUSED,WWN,SERIAL,PTUUID,PARTUUID,UUID,LOG-SEC"],
                         capture_output=True, text=True).stdout
    return json.loads(out or '{"blockdevices": []}')


def _sfdisk(path: str):
    """The drive's partition table as sfdisk reads it (sectors), or None when it can't (no table, or unreadable)."""
    sf = subprocess.run(["sfdisk", "-J", path], capture_output=True, text=True)
    try:
        return json.loads(sf.stdout)["partitiontable"] if sf.returncode == 0 else None
    except (ValueError, KeyError):
        return None


def uefi() -> bool:
    return Path("/sys/firmware/efi").is_dir()


def active_swaps() -> set:
    try:
        return {l.split()[0] for l in Path("/proc/swaps").read_text().splitlines()[1:] if l.split()}
    except OSError:
        return set()


def dev_exists(path: str) -> bool:
    return Path(path).exists()


def mapper_exists(name: str) -> bool:
    return Path(f"/dev/mapper/{name}").exists()


def _flag(v) -> bool:
    return v is True or v in (1, "1", "true")


def _in_use(node: dict, swaps: set) -> bool:
    """Something on the live system uses it: mounted, active swap, or held by a mapper (open LUKS, LVM, RAID)."""
    if node.get("mountpoint") or node.get("path") in swaps:
        return True
    return any(c.get("type") != "part" or _in_use(c, swaps) for c in node.get("children") or [])


def drive_speed(d: dict) -> dict:
    """How fast a drive is likely to be, from how it's connected: 3 NVMe, 2 SSD, 1 hard drive or built-in flash,
    0 USB or removable. kind is the words on the drive's row."""
    tran = (d.get("tran") or "").lower()
    if tran == "usb":
        return {"rank": 0, "kind": "USB drive"}
    if _flag(d.get("rm")):
        return {"rank": 0, "kind": "Removable drive"}
    if tran == "nvme" or d["path"].startswith("/dev/nvme"):
        return {"rank": 3, "kind": "NVMe SSD"}
    if d["path"].startswith("/dev/mmcblk"):
        return {"rank": 1, "kind": "Built-in storage"}
    if not _flag(d.get("rota")):
        return {"rank": 2, "kind": "SSD"}
    return {"rank": 1, "kind": "Hard drive"}


def drive_name(x: dict) -> str:
    return f"{x['model']} ({size_text(x['size'])})"


def keep_verdict(info: dict, in_use: bool, ntfs: dict) -> dict:
    """Whether a partition can be kept and used as it is (mounted, never formatted), with a plain reason if not."""
    fs, typ = info["fs"], info["type"]
    if typ == ESP_TYPE:
        return {"blocked": "This is a startup partition the computer needs."}
    if fs == "bitlocker":
        return {"blocked": BITLOCKER_KEEP}
    if typ == WIN_RECOVERY:
        return {"blocked": "This is Windows' recovery partition: it doesn't hold files."}
    if typ in (MS_RESERVED, SWAP_TYPE) or fs == "swap":
        return {"blocked": "This doesn't hold files."}
    if in_use:
        return {"blocked": "This is in use right now on this computer, so it can't be used here."}
    if fs == "crypto_luks":
        return {"ok": True, "unlock": True}
    if fs == "ntfs":
        why = (ntfs or {}).get("blocked", "")
        if why == NTFS_FAST:
            return {"blocked": "Windows didn't fully shut down, so this can't be used safely yet. In Windows: hold Shift "
                               "while choosing Shut down, or turn off Fast Startup in Power Options, then look again."}
        if why == NTFS_CHECK:
            return {"blocked": "Windows wants to check this drive first. Start Windows once, let it finish, and shut it "
                               "down normally, then look again."}
        return {"ok": True}
    if fs in KEEP_FS:
        return {"ok": True}
    return {"blocked": "Starchaser can't read what's on this."}


SHAPE_ID = "shape:"         # a drive id made from its size, model and partitions (the drive has no serial number)


def drive_identity(d: dict) -> str:
    """A drive's id, from its lsblk node: the WWN, else the serial number, else the partition table's id. A drive
    with none of them (a blank virtual drive, some USB, SD and eMMC drives) is known by its size, model and the ids
    of what is on it instead, the way the graphical installer still lets it be chosen; that can't tell two blank
    drives of the same model and size apart, and drive_safety says so on screen."""
    strong = (d.get("wwn") or d.get("serial") or d.get("ptuuid") or "").strip()
    if strong:
        return strong
    parts = sorted((c.get("partuuid") or c.get("uuid") or c.get("name") or "").strip() for c in d.get("children") or [])
    return SHAPE_ID + "|".join([str(d.get("size") or 0), (d.get("model") or "").strip(), (d.get("uuid") or "").strip()]
                               + parts)


def disks() -> dict:
    lb = _lsblk()
    skip = live_disks()
    swaps = active_swaps()
    out = []
    for d in lb["blockdevices"]:
        if d["type"] != "disk" or d["path"] in skip or d["path"].startswith(("/dev/zram", "/dev/loop", "/dev/sr")):
            continue
        if d["size"] < MIN_LISTED:
            continue
        disk = {"path": d["path"], "size": d["size"], "model": (d.get("model") or "").strip() or "Drive",
                "removable": bool(d.get("rm")), "transport": d.get("tran") or "", "table": d.get("pttype") or "",
                "partitions": [], "free": [], "esp": "", "windows": False, "bitlocker": False, "oses": [],
                # other drives: a stable id (checked again before anything is written), how fast it is, whether it
                # can hold Starchaser at all, and whether the live system is using it
                "id": drive_identity(d),
                "speed": drive_speed(d), "system_ok": d["size"] >= required_drive(), "in_use": _in_use(d, swaps)}
        # free space, from the partition table itself (sectors)
        pt = _sfdisk(d["path"])
        ss = (pt or {}).get("sectorsize") or d.get("log-sec") or 512
        first = (pt or {}).get("firstlba", 2048)
        last = (pt or {}).get("lastlba", d["size"] // ss - 34)
        if pt:
            used = sorted((p["start"], p["start"] + p["size"]) for p in pt.get("partitions", []))
            cur = first
            for a, b in used + [(last + 1, last + 1)]:
                if (a - cur) * ss >= 64 * MIB:
                    disk["free"].append({"start": cur, "end": a - 1, "bytes": (a - cur) * ss})
                cur = max(cur, b)
        # a blank drive (no table at all) can still be started over; one whose table can't be read can't be edited
        disk["table_ok"] = pt is not None or not (d.get("children") or d.get("pttype"))
        disk["sector"], disk["first"], disk["last"] = ss, first, last
        rows = {p["node"]: p for p in (pt or {}).get("partitions", []) if p.get("node")}
        for p in d.get("children", []):
            fs = (p.get("fstype") or "").lower()
            info = {"path": p["path"], "size": p["size"], "fs": fs, "label": p.get("label") or "",
                    "name": p.get("partlabel") or "", "type": (p.get("parttype") or "").upper(), "mounted": bool(p.get("mountpoint"))}
            if info["type"] == ESP_TYPE:
                disk["esp"] = p["path"]
                info["role"] = "EFI system partition"
            elif fs == "bitlocker":
                disk["bitlocker"] = disk["windows"] = True
                info["role"] = "Windows (BitLocker encrypted)"
                info["shrink"] = {"blocked": "BitLocker is on. In Windows, turn off BitLocker (or suspend it and shrink the "
                                             "drive in Disk Management), then try again."}
            elif fs == "ntfs":
                disk["windows"] = True
                info["role"] = "Windows" if info["size"] > 30 * GIB else "Windows (data or recovery)"
                if info["size"] > MIN_ROOT:
                    info["shrink"] = ntfs_info(p["path"])
            elif fs in ("ext4", "btrfs"):
                info["role"] = "Linux"
                if info["mounted"]:
                    info["shrink"] = {"blocked": "This partition is in use right now, so it can't be shrunk."}
                else:
                    used_b = linux_min(p["path"], fs, int(p.get("fsused") or 0))
                    info["shrink"] = {"min": used_b + 4 * GIB} if used_b else \
                        {"blocked": "Can't measure how full this partition is, so it can't be shrunk here."}
            elif fs == "crypto_luks":
                info["role"] = "Encrypted (Linux)"
            elif fs == "swap":
                info["role"] = "Swap"
            if info.get("shrink", {}).get("min"):
                info["shrink"]["max_free"] = max(0, info["size"] - info["shrink"]["min"] - GIB)
                if info["shrink"]["max_free"] < required_free():      # the range to pick from would be empty
                    info["shrink"] = {"blocked": f"Not enough room in it: Starchaser needs {size_text(required_free())} freed, "
                                                 f"and it can give up only {size_text(info['shrink']['max_free'])}."}
            # for keeping it, and for the Advanced editor
            row = rows.get(p["path"], {})
            num = re.search(r"(\d+)$", p["path"])
            p_busy = _in_use(p, swaps)
            ntfs = None
            if fs == "ntfs" and info["type"] != WIN_RECOVERY:
                sk = info.get("shrink") or {}
                ntfs = sk or ntfs_info(p["path"])            # already measured when it's big enough to shrink
            info.update({"uuid": (row.get("uuid") or p.get("partuuid") or "").upper(),
                         "number": int(num.group(1)) if num else 0,
                         "start": row.get("start"), "end": row["start"] + row["size"] - 1 if row else None,
                         "fs_uuid": p.get("uuid") or "",
                         "encrypted": "luks" if fs == "crypto_luks" else "bitlocker" if fs == "bitlocker" else "",
                         "used": int(p.get("fsused") or 0), "in_use": p_busy,
                         "keep": keep_verdict(info, p_busy, ntfs)})
            disk["partitions"].append(info)
        # the systems on it, each named once ("Windows", not also its recovery partition)
        disk["oses"] = sorted({p["role"].split(" (")[0] for p in disk["partitions"]
                               if p.get("role", "").startswith(("Windows", "Linux")) and "recovery" not in p["role"]})
        out.append(disk)
    # fastest first, then largest; the suggested system drive is the first that can hold Starchaser (a USB drive
    # only when nothing else can)
    out.sort(key=lambda x: (-x["speed"]["rank"], -x["size"]))
    able = [x for x in out if x["system_ok"]]
    suggested = next((x["path"] for x in able if x["speed"]["rank"] > 0), able[0]["path"] if able else "")
    return {"disks": out, "suggested": suggested, "live": sorted(skip), "uefi": uefi(), "tpm2": tpm2(),
            "hiddenDrives": hardware.HIDDEN_DRIVES if hardware.hidden_drives() else "",
            "ram": os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES"), "cpu": cpu_vendor(),
            "on_battery": on_battery(), "battery": has_battery(),
            # the sizes both installers work with, so neither keeps its own copy of the numbers
            "need": {"free": required_free(), "drive": required_drive(), "boot": boot_bytes()}, "reserved": sorted(reserved_names()),
            # the online image needs the internet before Drive; the Welcome says about how much it downloads
            "edition": "online" if online_edition() else "full", "typicalDownload": edition_download_text()}


def _blkid(dev: str, tag: str) -> str:
    return subprocess.run(["blkid", "-c", "/dev/null", "-o", "value", "-s", tag, dev],
                          capture_output=True, text=True).stdout.strip()


def peek(dev: str, passphrase: str = "") -> dict:
    """Look inside a partition without changing it: an encrypted one is opened read-only with its passphrase, the
    file system is mounted read-only without replaying its journal, and the used space and first few folder names
    are read. Always unmounted and closed again. Never logs the passphrase."""
    opened = mounted = False
    # names of this run's own: the graphical installer's look and an engine check can run at the same moment, and
    # with one shared name each would close or mount over the other's
    mp, pdir = f"{PEEK_MAPPER}-{os.getpid()}", PEEK_DIR / str(os.getpid())
    try:
        if os.geteuid() != 0:
            return {"ok": False, "error": "The installer needs to run as root to look inside it."}
        if not Path(dev).exists():
            return {"ok": False, "error": "It isn't here any more. Look again on the Drive step."}
        target, fs = dev, _blkid(dev, "TYPE").lower()
        luks = fs == "crypto_luks"
        if luks:
            if mapper_exists(mp):                  # left over from an interrupted look
                subprocess.run(["cryptsetup", "close", mp], capture_output=True)
            r = subprocess.run(["cryptsetup", "open", "--readonly", "--key-file=-", dev, mp],
                               input=passphrase, capture_output=True, text=True)
            if r.returncode == 2 or (r.returncode and "No key available" in r.stderr):
                return {"ok": False, "wrong_passphrase": True,
                        "error": "That disk key didn't open it. Check it and try again."}
            if r.returncode:
                return {"ok": False, "error": "It couldn't be opened (" + ((r.stderr or r.stdout).strip().splitlines() or ["?"])[-1] + ")."}
            opened = True
            target = f"/dev/mapper/{mp}"
            subprocess.run(["udevadm", "settle"], capture_output=True)
            fs = _blkid(target, "TYPE").lower()
            if fs not in PEEK_MOUNT:
                return {"ok": False, "error": f"It opened, but Starchaser can't read what's inside ({fs or 'unknown'})."}
        elif fs not in PEEK_MOUNT:
            return {"ok": False, "error": f"Starchaser can't read what's on this ({fs or 'unknown'})."}
        label, fs_uuid = _blkid(target, "LABEL"), _blkid(target, "UUID")
        pdir.mkdir(parents=True, exist_ok=True)
        typ, opts = PEEK_MOUNT[fs]
        r = subprocess.run(["mount", "-t", typ, "-o", opts, target, str(pdir)], capture_output=True, text=True)
        if r.returncode and fs == "ntfs":                   # a kernel without ntfs3: the ntfs-3g driver
            r = subprocess.run(["mount", "-t", "ntfs-3g", "-o", "ro", target, str(pdir)], capture_output=True, text=True)
        if r.returncode:
            return {"ok": False, "error": "It couldn't be opened for reading (" + ((r.stderr or r.stdout).strip().splitlines() or ["?"])[-1] + ")."}
        mounted = True
        st = os.statvfs(pdir)
        top = sorted(n for n in os.listdir(pdir) if not n.startswith(".") and n not in ("lost+found", "$RECYCLE.BIN",
                                                                                            "System Volume Information"))
        subs = []
        if fs == "btrfs":
            lst = subprocess.run(["btrfs", "subvolume", "list", str(pdir)], capture_output=True, text=True).stdout
            subs = [l.split(" path ", 1)[1] for l in lst.splitlines() if " path " in l]
        return {"ok": True, "fs": fs, "luks": luks, "label": label, "fs_uuid": fs_uuid,
                "size": st.f_blocks * st.f_frsize, "used": (st.f_blocks - st.f_bfree) * st.f_frsize,
                "top": top[:5], "subvolumes": subs,
                "last_changed": datetime.datetime.fromtimestamp(max((p.stat().st_mtime for p in pdir.iterdir() if not p.is_symlink()), default=0)).strftime("%Y-%m-%d")}
    finally:
        if mounted:
            subprocess.run(["umount", str(pdir)], capture_output=True)
        try:
            pdir.rmdir()
        except OSError:
            pass
        if opened:
            subprocess.run(["cryptsetup", "close", mp], capture_output=True)


def drive_health(dev):
    """A SMART read never starts a self-test or changes drive settings."""
    try:
        result = subprocess.run(["smartctl", "-H", "-j", dev], capture_output=True, text=True, timeout=20)
        data = json.loads(result.stdout)
        passed = data.get("smart_status", {}).get("passed")
        if passed is False or result.returncode & 8:
            return "Drive reports a health warning. Back up before installing."
        if passed is True:
            return "Drive reports healthy. A backup is still recommended."
    except (OSError, ValueError, subprocess.TimeoutExpired):
        pass
    return "Drive health is unavailable. This does not confirm the drive is healthy."


def safety_drive(info, dev, identity):
    disk = next((d for d in info["disks"] if d["path"] == dev), None)
    if not disk or not identity or disk.get("id") != identity or dev in info.get("live", []):
        fail("The drive changed or cannot be identified safely. Look again before continuing.")
    return disk


def drive_safety(dev, identity):
    info = disks()
    disk = safety_drive(info, dev, identity)
    used, unknown, changed = 0, [], []
    for part in disk["partitions"]:
        if part.get("type") == MS_RESERVED:
            continue  # Windows reserves this space; it has no filesystem or user files.
        if part["fs"] not in PEEK_MOUNT:
            if part["fs"] not in ("vfat", "swap"):
                unknown.append(part["path"])
            continue
        found = peek(part["path"])
        if found.get("ok"):
            used += found["used"]
            if found.get("last_changed"):
                changed.append(found["last_changed"])
        else:
            unknown.append(part["path"])
    who = " and ".join("another system" if n == "Linux" else n for n in disk.get("oses", []))
    words = "This drive has " + who + " and about " + size_text(used) + " of files" if who else (
        "This drive has about " + size_text(used) + " of files" if disk["partitions"] else "This drive is empty")
    if changed:
        date = datetime.date.fromisoformat(max(changed))
        words += f". Last changed {date.strftime('%B')} {date.day}, {date.year}"
    if unknown:
        words += ". Part of this drive could not be read and may hold more files"
    if disk.get("id", "").startswith(SHAPE_ID):
        words += (". It has no serial number, so the installer knows it by its size, model and partitions: don't swap "
                  "drives until the install is done")
    return {"ok": True, "words": words, "health": drive_health(dev), "unreadable": unknown}


@contextlib.contextmanager
def safety_mount(part, writable=False):
    # A failed unmount must never let recursive temporary-directory cleanup reach the drive's files.
    where = Path(tempfile.mkdtemp(prefix="starchaser-backup-"))
    try:
        fs = part["fs"]
        if writable:
            sh("mount", "-o", "rw,nosuid,nodev,noexec", part["path"], where)
        else:
            typ, opts = PEEK_MOUNT[fs]
            # The default Btrfs subvolume is often only @; @home and other siblings are outside it.
            # Enumerate and copy from the top-level tree so every linked subvolume is traversed,
            # including nested subvolumes and snapshots, without replaying the source journal.
            if fs == "btrfs":
                opts += ",subvolid=5"
            sh("mount", "-t", typ, "-o", opts + ",nosuid,nodev,noexec", part["path"], where)
        try:
            yield where
        finally:
            sh("umount", where)
    finally:
        try:
            where.rmdir()
        except OSError:
            log(f"Backup mount point kept at {where}; it may still be mounted. No files were removed.")


def copy_before_erase(source, target):
    folder = Path(tempfile.mkdtemp(prefix="Files before installing-", dir=target))
    contents = folder / "Files"
    contents.mkdir()
    # Record links instead of following them into the live system or requiring link support on the backup drive.
    links, required = {}, 0
    with tempfile.TemporaryDirectory(prefix="starchaser-backup-list-") as tmp:
        listing = Path(tmp) / "files"
        def unreadable(error):
            fail("Some files could not be read. A partial copy was kept; keep your original drive and back it up before erasing.")
        with listing.open("wb") as out:
            for directory, dirs, files in os.walk(source, followlinks=False, onerror=unreadable):
                relative = Path(directory).relative_to(source)
                (contents / relative).mkdir(parents=True, exist_ok=True)
                traversed_dirs = set(dirs)
                for name in dirs + files:
                    path = Path(directory) / name
                    key = str(path.relative_to(source))
                    try:
                        info = path.lstat()
                        if stat.S_ISLNK(info.st_mode):
                            links[key] = os.readlink(path)
                        elif stat.S_ISREG(info.st_mode):
                            required += info.st_size
                            out.write(os.fsencode(key) + b"\0")
                        elif stat.S_ISDIR(info.st_mode) and name not in traversed_dirs:
                            # os.walk suppresses is_dir() errors; lstat must confirm every directory will be visited.
                            raise OSError("Source directory was omitted from traversal")
                    except OSError as error:
                        unreadable(error)
        if shutil.disk_usage(target).free < required + 64 * MIB:
            fail("The backup drive does not have enough free space. Your original files were kept.")
        (folder / "Links.json").write_text(json.dumps(links, indent=2) + "\n")
        args = ["rsync", "-rt", "--modify-window=2", "--from0", "--files-from", listing, "--no-devices", "--no-specials"]
        sh(*args, str(source) + "/", str(contents) + "/")
        check = sh(*args, "--checksum", "--dry-run", "--itemize-changes", str(source) + "/", str(contents) + "/")
        if check.stdout.strip():
            fail("The partial copy did not verify. Keep your original drive and try another backup drive.")
        sh("sync", "-f", folder)
    return folder.name


def locked_backup(a):
    with LOCK.open("w") as guard:
        try:
            fcntl.flock(guard, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            fail("An install or backup is already running. Wait for it to finish.")
        previous = {sig: signal.getsignal(sig) for sig in (signal.SIGTERM, signal.SIGHUP)}
        def interrupted(signum, frame):
            for sig in previous:
                signal.signal(sig, signal.SIG_IGN)
            terminate_install_children()
            fail("The backup stopped. A partial copy was kept; your original files were not changed.")
        try:
            for sig in previous:
                signal.signal(sig, interrupted)
            return backup_drive(a)
        finally:
            for sig, handler in previous.items():
                signal.signal(sig, handler)


def backup_drive(a):
    info = disks()
    source = safety_drive(info, a["disk"], a["disk_id"])
    dst_disk = next((d for d in info["disks"] if any(p["path"] == a["target"] for p in d["partitions"])), None)
    if not dst_disk:
        fail("The backup drive is no longer connected.")
    safety_drive(info, dst_disk["path"], a["target_id"])
    target = next(p for p in dst_disk["partitions"] if p["path"] == a["target"])
    if (dst_disk["path"] == source["path"] or not (dst_disk.get("removable") or dst_disk.get("transport") == "usb")
            or dst_disk.get("in_use") or target.get("in_use") or target.get("mounted")
            or target.get("uuid") != a.get("target_uuid") or not a.get("target_uuid")
            or target["fs"] not in ("ext4", "btrfs", "exfat", "ntfs")):
        fail("Choose an unused external backup drive, separate from the drive being erased and the installer stick.")
    file_parts = [p for p in source["partitions"] if p.get("type") != MS_RESERVED]
    parts = [p for p in file_parts if p["fs"] in PEEK_MOUNT]
    unreadable = [p for p in file_parts if p["fs"] not in (*PEEK_MOUNT, "vfat", "swap")]
    if not parts or unreadable or any(p.get("in_use") or p.get("mounted") for p in parts):
        fail("Some files cannot be read safely. Unlock and back them up in the original system before erasing.")
    saved = []
    # Re-scan immediately before mounting either side, just as installation rechecks before writes.
    current = disks()
    safety_drive(current, source["path"], a["disk_id"])
    safety_drive(current, dst_disk["path"], a["target_id"])
    current_target = next((p for d in current["disks"] for p in d["partitions"] if p["path"] == target["path"]), {})
    if current_target.get("uuid") != a["target_uuid"] or current_target.get("in_use"):
        fail("The backup partition changed. Look again.")
    with safety_mount(target, writable=True) as dst:
        for part in parts:
            with safety_mount(part) as src:
                saved.append(copy_before_erase(src, dst))
    folders = ", ".join("“" + name + "”" for name in saved)
    location = "the folder " if len(saved) == 1 else "the folders "
    return {"ok": True, "message": "Your files were copied and checked. They are in " + location + folders + " on the backup drive. Disconnect the backup drive before erasing."}


def has_battery(power=Path("/sys/class/power_supply")) -> bool:
    """Battery presence defines a laptop even when plugged in or fully charged."""
    for supply in power.glob("*"):
        try:
            if (supply / "type").read_text().strip() == "Battery" and (not (supply / "present").exists() or (supply / "present").read_text().strip() == "1") and (not (supply / "scope").exists() or (supply / "scope").read_text().strip() != "Device"):
                return True
        except OSError:
            continue
    return False


def default_encryption(info: dict) -> str:
    if not info.get("tpm2"):
        return "passphrase"
    return "tpm-pin" if info.get("battery") else "tpm"


def on_battery() -> bool:
    """True on a laptop running from its battery: a mains supply that is there but not plugged in. A desktop
    (no mains entry at all) is never "on battery"."""
    mains, has_battery = [], False
    for d in Path("/sys/class/power_supply").glob("*"):
        try:
            kind = (d / "type").read_text().strip()
            if kind == "Mains":
                mains.append((d / "online").read_text().strip() == "1")
            elif kind == "Battery":
                has_battery = True
        except OSError:
            continue
    return bool(has_battery and mains and not any(mains))


def cpu_vendor() -> str:
    try:
        return "amd" if "AuthenticAMD" in Path("/proc/cpuinfo").read_text() else "intel"
    except OSError:
        return "intel"


def reserved_names() -> set:
    """Usernames that would clash with a user or group on the new system (see RESERVED_NAMES), plus any the live
    system's packages declare."""
    names = set(RESERVED_NAMES)
    for f in glob.glob("/usr/lib/sysusers.d/*.conf"):
        try:
            for line in Path(f).read_text().splitlines():
                parts = line.split()
                if len(parts) >= 2 and parts[0][:1] in ("u", "g", "m"):
                    names.add(parts[1])
        except OSError:
            pass
    return names - {"live"}


def secure_boot() -> bool:
    try:
        return Path(SECURE_BOOT_VAR).read_bytes()[4:5] == b"\x01"     # 4 attribute bytes, then the value
    except OSError:
        return False



# 4 GiB for startup files always (11-16, Derek's Legion): with NVIDIA every initramfs carries the driver, and four
# kernels plus their fallback images filled the old 1 GiB partition (Secure Boot off) halfway through the install ("No
# space left on device" from mkinitcpio). Secure Boot on already used 4 GiB.
STARTUP_BOOT = 4 * GIB
# Plus room for the on-disk Starchaser Recovery entry (decision #65: stick AND disk). The compact payload is ~630 MB
# and rescue.install_environment wants 128 MB spare beside it; iso/build.sh refuses a payload that outgrows this, so
# Recovery never eats the kernels' room (QA 11-16 P2-7: the 1 GiB partition left the installed drive without it).
RECOVERY_BOOT = 1 * GIB


def boot_bytes():
    return STARTUP_BOOT + RECOVERY_BOOT


def required_free():
    return MIN_ROOT + boot_bytes()


def required_drive():
    return MIN_ROOT + boot_bytes() + GIB


def gpus() -> list:
    """The graphics devices: [(vendor id, device id)] from lspci, one per graphics line (VGA, 3D or display)."""
    return hardware.gpus()


NVIDIA_INITRAMFS = kernels.NVIDIA_INITRAMFS     # NVIDIA's driver in the start-up image: it is the graphics driver


def live_safegfx() -> bool:
    """The installer stick was started from its "safe graphics" boot entry (starchaser.safegfx=1 on the kernel line)."""
    try:
        return safegfx.requested(Path("/proc/cmdline").read_text())
    except OSError:
        return False


def default_entry() -> str:
    """The boot entry loader.conf starts first: safe graphics for the first start when the stick needed it."""
    return safegfx.ENTRY if live_safegfx() else "starchaser"


def nvidia_old() -> bool:
    """An NVIDIA card older than Turing (GeForce 16/20 series): the open kernel modules don't drive it, so it gets
    the built-in open-source driver from mesa only (no proprietary driver from outside the official repos)."""
    return hardware.nvidia_old(gpus())


# --------------------------------------------------------------------------------------------- the plan
def room_text(b) -> str:
    """A size next to a limit: never rounded up (1.96 GB is "1.9 GB", not "2 GB", beside "needs at least 2 GB"),
    except by the half MiB the editor's whole-MiB sizes can fall short (a typed 3 GB is 2861 MiB: "3 GB")."""
    b += MIB // 2
    if b < 1e9 or b >= 1e10:
        return size_text(b) if b >= 1e9 else f"{int(b // 1e6)} MB"
    tenths = int(b // 1e8)
    return f"{tenths // 10} GB" if tenths % 10 == 0 else f"{tenths / 10:.1f} GB"


def size_text(b) -> str:
    """A size the way a drive's box says it (1 GB = 10^9 bytes, 1 TB = 10^12)."""
    if 0 < b < 1e9:                       # a few hundred MB used is not "0 GB used"
        return f"{max(1, round(b / 1e6))} MB"
    return f"{b / 1e9:,.0f} GB" if b < 1e12 else f"{b / 1e12:.1f} TB"



def zone_words(tz: str, label=None) -> str:
    """The zone as the Time zone page named it ("Pacific Time (Los Angeles)"), so the Summary says what was picked;
    without the page's name (the text installer), the same reading the page gives zones it has no name for."""
    if isinstance(label, str) and 0 < len(label) <= 80 and label.isprintable():
        return label
    return ", ".join(reversed(tz.replace("_", " ").split("/")))


def plan(a: dict) -> dict:
    """Validate the answers against the drives; describe what will happen, in words, before anything does."""
    errs, steps, notes = [], [], []
    back = []                  # per error: the graphical installer's step that can fix it ("" = no earlier step can)

    def mark(step: str) -> None:
        back.extend([step] * (len(errs) - len(back)))
    info = disks()
    if not info["uefi"]:
        errs.append("This computer started the installer in legacy BIOS mode. Starchaser needs UEFI: restart, open "
                    "the firmware setup and boot the USB stick's UEFI entry.")
    mark("")
    mode = a.get("mode", "erase")
    enc = a.get("encrypt", default_encryption(info))
    root_enc = None                        # manual: whether / is set to be encrypted (None: no / chosen)
    if mode == "manual":
        layout = {"mode": mode, "disk": "", "volumes": [], "tables": [], "erased": [], "extra_pkgs": []}
        d, root_enc = plan_manual(a, info, errs, steps, notes, layout)
    else:
        # only drives big enough for Starchaser can be the system drive (smaller ones are listed for other uses)
        d = next((x for x in info["disks"] if x["path"] == a.get("disk") and x.get("system_ok", True)), None)
    if not d and mode != "manual":
        return {"ok": False, "errors": errs + [f"No drive {a.get('disk')!r} here (or it's the installer's own USB stick)."],
                "back": back + ["disk"], "steps": [], "notes": []}
    if mode != "manual":
        name = f"{d['model']} ({size_text(d['size'])})"
        layout = {"mode": mode, "disk": d["path"], "volumes": [], "tables": [], "erased": [], "extra_pkgs": []}
        if a.get("disk_id") and a["disk_id"] != d.get("id"):
            errs.append(f"{name} changed since the list of drives was made (it may have been unplugged). Look again "
                        "on the Drive step.")
    if mode == "manual":
        pass
    elif mode == "erase":
        if d.get("in_use"):
            errs.append(f"{name} is in use right now, so it can't be erased.")
        steps.append(f"Erase everything on {name}" + (f", including {', '.join(d['oses'])}" if d["oses"] else ""))
        layout["root_bytes"] = d["size"] - boot_bytes()
    elif mode in ("free", "shrink"):
        if d["table"] != "gpt":
            errs.append(f"{name} doesn't use a GPT partition table, so Starchaser can only install there by erasing it.")
        if not d["esp"]:
            errs.append(f"{name} has no EFI system partition to share. Choose Erase, or install on the drive that has one.")
        layout["esp"] = d["esp"]
        if mode == "free":
            room = max(d["free"], key=lambda f: f["bytes"], default=None)
            if not room or room["bytes"] < required_free():
                errs.append(f"{name} has {size_text(room['bytes']) if room else 'no'} free space; Starchaser needs at least "
                            f"{size_text(required_free())}. Choose Shrink to make room.")
            else:
                layout["free"] = room
                layout["root_bytes"] = room["bytes"] - boot_bytes()
                steps.append(f"Use the {size_text(room['bytes'])} of free space on {name}; everything already there stays")
        else:
            s = a.get("shrink") or {}
            p = next((x for x in d["partitions"] if x["path"] == s.get("partition")), None)
            if not p:
                errs.append("Pick the partition to shrink.")
            elif not p.get("shrink") or p["shrink"].get("blocked"):
                errs.append((p.get("shrink") or {}).get("blocked") or f"{p['path']} ({p['fs'] or 'unknown'}) can't be shrunk here.")
            else:
                new = int(s.get("size_mib", 0)) * MIB
                lo = p["shrink"]["min"] + GIB
                if new < lo:
                    errs.append(f"{p.get('role', p['path'])} needs at least {size_text(lo)} (it holds {size_text(p['shrink']['min'])}).")
                freed = p["size"] - new
                if freed < required_free():
                    errs.append(f"That frees {size_text(max(freed, 0))}; Starchaser needs at least {size_text(required_free())}.")
                layout["shrink"] = {"partition": p["path"], "fs": p["fs"], "new_bytes": new, "old_bytes": p["size"]}
                layout["root_bytes"] = freed - boot_bytes()
                steps.append(f"Shrink {p.get('role', p['path'])} ({p['path']}) from {size_text(p['size'])} to {size_text(new)}; its files stay")
                if p["fs"] == "ntfs":
                    notes.append("Windows checks its drive the first time it starts after this. That's normal: let it finish.")
        steps.append("Add Starchaser to the boot menu next to " + (", ".join(d["oses"]) or "what's there"))
    else:
        errs.append(f"Unknown mode {mode!r}.")
    if mode != "manual":
        plan_other_drives(a, info, d, mode, enc, errs, steps, notes, layout)
    mark("disk")
    if enc not in ("tpm", "tpm-pin", "passphrase", "none"):
        # a misspelled value ("pasphrase") would otherwise erase the drive and then try the TPM
        errs.append(f"Unknown encryption choice {enc!r}: it's tpm, tpm-pin, passphrase or none.")
    if enc in ("tpm", "tpm-pin") and not info["tpm2"]:
        errs.append("This computer has no security chip for drive unlock. Choose a disk key instead.")
    if secure_boot():
        problem = signed_boot.installer_ready()
        if problem:
            errs.append(problem)
        else:
            steps.append("Keep Secure Boot on; sign the startup files and enroll this computer's boot certificate at the next start")
            notes.append("Before restarting, save the enrollment code shown when installation finishes. At the startup screen choose Enroll MOK, Continue, Yes, type that code, then Reboot. Keep the drive recovery key ready for the first start. After signing in, open Settings > Security to relink chip unlock if needed.")
    if enc == "passphrase" and len(a.get("passphrase", "")) < 8:
        errs.append("The disk key needs at least 8 characters.")
    if root_enc is True and enc not in ("tpm", "tpm-pin", "passphrase"):
        errs.append("/ is set to be encrypted (Advanced): choose how it unlocks (this computer, or a disk key).")
    elif root_enc is False and enc != "none":
        errs.append("/ isn't set to be encrypted (Advanced), so choose Don't encrypt.")
    if enc == "tpm-pin" and (not isinstance(a.get("pin"), str) or len(a["pin"]) < 8 or len(a["pin"]) > 256 or any(c in a["pin"] for c in "\r\n\0")):
        errs.append("The startup PIN needs 8 or more characters on one line.")
    mark("encrypt")
    steps.append({"tpm-pin": "Encrypt Starchaser with this computer and a startup PIN; keep the emergency sheet away from this computer",
                  "tpm": "Encrypt Starchaser; this computer unlocks it at startup (you'll get a disk key to keep). "
                         "This protects your files if the drive is taken out of the computer",
                  "passphrase": "Encrypt Starchaser; type the disk key at every startup",
                  "none": "Don't encrypt (anyone with the drive can read it)"}.get(enc, "?"))
    deferred = a.get("account_setup", "me") == "later"
    if a.get("account_setup", "me") not in ("me", "later"):
        errs.append("Choose who will use this computer: Me, or Someone else, later.")
    u = a.get("user") or {}
    if deferred:
        if any(a.get(k) for k in ("autologin", "authorized_keys", "sudo_nopasswd", "ssh", "trust_network", "remote_desktop")):
            errs.append("The new person chooses remote access and automatic sign-in after making their account.")
    else:
        if not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", u.get("username", "")):
            errs.append("The username needs lowercase letters, digits, - or _ and must start with a letter.")
        elif u.get("username") in info["reserved"]:
            errs.append(f"The username {u.get('username')!r} is already used by the system. Pick another.")
        name_problem = full_name_problem(u.get("name", ""))
        if name_problem:
            errs.append(name_problem)
        if len(u.get("password", "")) < 4:
            errs.append("The password needs at least 4 characters.")
        elif a.get("ssh") and len(u.get("password", "")) < 8:
            errs.append("Remote login needs a password with at least 8 characters.")
        elif re.search(r"[\r\n]", u.get("password", "")):
            # it goes to chpasswd as one "user:password" line: a line break would split it into other records
            errs.append("The password can't contain a line break.")
    if not re.fullmatch(r"[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?", a.get("hostname", "")):
        errs.append("The computer name may use letters, digits and - (not at the start or end).")
    mark("you")
    tz = a.get("timezone", "")
    if not tz or ".." in tz or not Path("/usr/share/zoneinfo", tz).is_file():
        errs.append(f"Unknown time zone {tz!r}.")
    mark("time")
    for e in setting_problems(a):
        errs.append(e)
        mark("" if e.startswith("The Starchaser files") else "welcome")     # keyboard and language: the first step
    # Windows somewhere this install leaves alone: on another drive (only the firmware's boot menu reaches it, since
    # the Starchaser menu lists only what shares its drive), or on this drive next to Starchaser
    # (a Windows drive this install erases holds no Windows afterwards; in Advanced, "this drive" is the one with the
    # EFI system partition, whose boot menu lists what shares it)
    erased = set(layout.get("erased", []))
    here = d["path"] if d else ""
    # Only drives big enough to hold a system count (Windows itself needs 64 GB): a small drive with a Windows data
    # or BitLocker partition on it is no Windows to start, and drives that small weren't listed before drive options
    others = [x for x in info["disks"] if x["path"] != here and x["windows"] and x["path"] not in erased
              and x.get("system_ok", True)]
    if others:
        notes.append("Windows on " + ", ".join(x["model"] for x in others) + " stays as it is. To start it, pick it "
                     "in this computer's own startup menu (a key like F12, F11 or F8 as the computer turns on).")
    if others or (mode != "erase" and d and d["windows"] and here not in erased):
        # Windows keeps the hardware clock in local time; Starchaser does the same, or each would show the other's
        # time off by hours after every switch
        layout["rtc_local"] = True
        notes.append("Windows keeps this computer's clock in local time, so Starchaser does too: both show the "
                     "right time when you switch between them.")
    kept_windows = others + ([d] if d and mode != "erase" and here not in erased else [])
    if any(x.get("windows") for x in kept_windows):
        notes.append("Before installing next to Windows, turn off Fast Startup: open Control Panel > Hardware and Sound > Power Options > Choose what the power buttons do > Change settings that are currently unavailable. Clear Turn on fast startup, then Save changes. Hold Shift while choosing Shut down before returning to this stick.")
    if any(x.get("bitlocker") for x in kept_windows):
        notes.append("Windows may ask for its BitLocker recovery key after Secure Boot is turned off or the startup menu changes. "
                     "Save that key before installing: on another device, visit aka.ms/myrecoverykey and sign in to your Microsoft account. "
                     "For a work or school computer, ask your IT team. In Windows, open Control Panel > System and Security > BitLocker Drive Encryption > Suspend protection before changing startup settings. Resume protection after you have checked that Windows starts.")
    if info.get("on_battery"):
        notes.append("Plug in the power before you start: this computer is running on its battery, and if the "
                     "battery runs out halfway, the drive is left unable to start.")
    if a.get("autologin") and enc in ("tpm", "none"):
        notes.append("You'll be logged in automatically and "
                     + ("the drive isn't encrypted" if enc == "none" else "the drive unlocks by itself")
                     + ", so anyone who turns this computer on gets straight to your files and saved passwords. On a laptop, consider "
                     "turning automatic login off.")
    if nvidia_old():
        notes.append("This computer has an older NVIDIA graphics card, so Starchaser uses the basic built-in "
                     "driver for its NVIDIA graphics. The desktop works; games and video may be slower.")
    if info["uefi"] and not secure_boot():
        notes.append("This installation is being made with Secure Boot off. Use a signed Starchaser installer "
                     "to set up Secure Boot before turning it on." + (" Changing startup security can make the drive ask for its recovery key." if enc in ("tpm", "tpm-pin") else ""))

    found = [row for row in hardware.detect(cards=gpus()) if row["detected"]]
    if found:
        steps.append("Set up hardware support: " + ", ".join(row["title"] for row in found))
    here = install_network() if a.get("ssh") and a.get("trust_network") else {}
    if a.get("ssh") and here:
        steps.append("Turn on remote login (SSH): you can sign in to this computer from your other computers with your "
                     "password, and it can join your fleet")
        steps.append(f"This network ({here['name']}) will be trusted: SSH and your fleet can reach this computer on it. "
                     "The welcome still asks about any other network")
    elif a.get("ssh"):
        steps.append("Turn on remote login (SSH): once you say this network is one you trust (the welcome asks), you can "
                     "sign in to this computer from your other computers with your password, and it can join your fleet")
        if a.get("trust_network"):
            notes.append("This computer isn't connected to a network now, so no network will be trusted: the welcome "
                         "asks about it after the install.")
    elif a.get("trust_network"):
        errs.append("Trusting this network needs remote login (SSH) turned on.")
        mark("you")
    if a.get("remote_desktop"):
        steps.append("Add remote desktop (Sunshine, from its makers): your other computers can see and use this one "
                     "once it joins your fleet")
    keys = a.get("authorized_keys")
    if isinstance(keys, list) and keys:
        steps.append(f"Let {len(keys)} SSH key{'s' if len(keys) != 1 else ''} sign in as {u.get('username')} without a password")
    if a.get("sudo_nopasswd"):
        steps.append(f"Let {u.get('username')} use sudo without typing the password")
    if a.get("fleet_profile"):
        steps.append("Connect to the fleet Wi-Fi and join your fleet after the new person makes their account; use computer name " + a["hostname"])
    if deferred:
        steps.append("At first start, ask the new person to make their own account and password")
    else:
        steps.append(f"Create {u.get('name') or u.get('username')} ({u.get('username')}) on {a.get('hostname')}, "
                     f"time zone {zone_words(tz, a.get('timezone_label'))}")
    if a.get("autologin"):
        steps.append(f"Log {u.get('name') or u.get('username')} in automatically when the computer starts, without "
                     "asking for the password. "
                     + ("Saved app passwords are kept unencrypted, as you chose, so apps don't ask either; "
                        "Settings > Security can protect them again" if a.get("keyring_unencrypted") else
                        "Saved app passwords stay protected by your password, so an app may ask you to unlock them"))
    if Path(a.get("media_dir") or installer_media.MEDIA).is_dir():
        steps.append("Install all software from this stick after checking every package. Internet is optional; get the latest updates after installation.")
    elif online_edition():
        step, error = online_download_step(a, layout.get("extra_pkgs") or [])
        if error:
            errs.append(error)
            mark("network")
        else:
            steps.append(step)
    elif not pkgrepo.answer_problems(a) and pkgrepo.desktop_source(a) == "package":
        offline = Path(a.get("pkgrepo_dir") or pkgrepo.OFFLINE_REPO)
        channel_words = "testing, with main as a fallback" if a.get("channel") == "testing" else "main"
        if offline.is_dir():
            steps.append(f"Install Starchaser from the online repo {pkgrepo.server_url(a.get('repo_url'))}, "
                         f"with its signing keys first ({channel_words} channel); if it can't be reached, "
                         f"from the offline package folder {offline} on this installer")
        elif pkgrepo.tries_online(a):
            steps.append("Install Starchaser from the online Starchaser repo, with its signing keys first (main channel); "
                         "if it can't be reached, from the copy on this installer")
        else:
            steps.append(f"Install Starchaser from {pkgrepo.server_url(a.get('repo_url'))}, with its signing keys first "
                         f"({channel_words} channel)")
    # anything erased, deleted or formatted: the installers say "Erase and install" and ask for the word erase
    destructive = mode == "erase" or bool(layout.get("erased")) or any(
        t.get("delete") or t.get("new_table") for t in layout.get("tables", [])) or any(
        v["kind"] == "format" for v in layout.get("volumes", []))
    return {"ok": not errs, "errors": errs, "back": back, "steps": steps, "notes": notes, "layout": layout,
            "destructive": destructive}


def name_slug(name, mount: str = "") -> tuple:
    """(name, folder name, problem): what the person typed, and the folder it becomes ("Old Photos" ->
    "old-photos", for /mnt/old-photos). A scripted answers file may give "mount": "/mnt/x" instead."""
    if mount and not name:
        m = re.fullmatch(r"/mnt/([a-z0-9_][a-z0-9_-]{0,31})", str(mount))
        if not m:
            return "", "", f"The folder {mount!r} can't be used: use /mnt/ and a short name in lowercase letters."
        return m.group(1), m.group(1), ""
    name = str(name or "").strip()
    if not name:
        return "", "", "Give each drive its own name."
    if not re.fullmatch(r"[A-Za-z0-9 _-]{1,32}", name):
        return "", "", (f"The name {name!r} can't be used. Use letters, numbers, spaces or - (it becomes the folder "
                        "/mnt/…).")
    slug = re.sub(r"[^a-z0-9_-]", "", name.lower().replace(" ", "-")).strip("-")[:32]
    if not slug:
        return "", "", (f"The name {name!r} can't be used. Use letters, numbers, spaces or - (it becomes the folder "
                        "/mnt/…).")
    return name, slug, ""


def _on_disk(disk: str, part: str) -> bool:
    return bool(re.fullmatch(re.escape(disk) + r"p?\d+", part or ""))


def find_partition(info: dict, part: str) -> tuple:
    for x in info["disks"]:
        for p in x["partitions"]:
            if p["path"] == part:
                return x, p
    return None, None


def _same_uuid(a: str, b: str) -> bool:
    return bool(a) and str(a).upper() == str(b or "").upper()


def _extra_pkgs(layout: dict, fs: str) -> None:
    pk = {"exfat": "exfatprogs", "xfs": "xfsprogs"}.get(fs)
    if pk and pk not in layout["extra_pkgs"]:
        layout["extra_pkgs"].append(pk)


def _keep_errors(name: str, p: dict, pk: dict) -> str:
    if pk.get("ok"):
        return ""
    if pk.get("wrong_passphrase") or (p["encrypted"] == "luks" and "passphrase" in pk.get("error", "")):
        return f"The disk key for {name} didn't open it. Check it and type it again."
    return f"{name}: {pk.get('error') or 'it could not be read.'}"


def plan_other_drives(a: dict, info: dict, d: dict, mode: str, enc: str, errs: list, steps: list, notes: list,
                      layout: dict) -> None:
    """The simple view's other drives ("drives": files / home) and kept partitions ("keep"). Neither key, or every
    drive left alone: nothing is added (today's install, exactly)."""
    drives, keeps = a.get("drives") or [], a.get("keep") or []
    if not isinstance(drives, list) or not isinstance(keeps, list):
        errs.append("The other drives in the answers file aren't a list.")
        return
    if not any(e.get("use", "leave") != "leave" for e in drives) and not keeps:
        return
    locked = enc in ("tpm", "tpm-pin", "passphrase")
    alldisks = {x["path"]: x for x in info["disks"]}
    live = set(info.get("live", []))
    names, used_disks, homes, removable, owners_note = {}, set(), 0, [], False
    vols, tables = layout["volumes"], layout["tables"]
    for e in drives:
        use = e.get("use", "leave")
        if use == "leave":
            continue
        path = e.get("disk")
        if use not in ("files", "home"):
            errs.append(f"Unknown choice {use!r} for {path}.")
            continue
        if path in live:
            errs.append(LIVE_USB)
            continue
        x = alldisks.get(path)
        if not x:
            errs.append(f"{path} isn't here any more (it may have been unplugged). Look again on the Drive step.")
            continue
        dn = drive_name(x)
        if x["path"] == d["path"]:
            errs.append(f"{dn} is the drive Starchaser goes on, so it can't also be used "
                        + ("for files." if use == "files" else "for your home folder."))
            continue
        if e.get("id") and e["id"] != x["id"]:
            errs.append(f"{dn} changed since the list of drives was made (it may have been unplugged). Look again on "
                        "the Drive step.")
            continue
        if x["path"] in used_disks:
            errs.append(f"{dn} is chosen twice. Pick one use for it.")
            continue
        used_disks.add(x["path"])
        if x["in_use"]:
            errs.append(f"{dn} is in use right now, so it can't be erased.")
            continue
        if use == "home":
            homes += 1
            if x["size"] < MIN_HOME:
                errs.append(f"{dn} is too small for your home folder (it needs at least {size_text(MIN_HOME)}).")
                continue
            name, slug, mount, mapper = "Home", "home", "/home", "crypthome"
        else:
            name, slug, problem = name_slug(e.get("name", "Data") if "name" in e or not e.get("mount") else "",
                                            e.get("mount", ""))
            if problem:
                errs.append(problem)
                continue
            if slug in names:
                errs.append(f"Two drives are named {name}. Give each one its own name.")
                continue
            names[slug] = name
            mount, mapper = f"/mnt/{slug}", f"crypt-{slug}"
        if locked and mapper_exists(mapper):
            errs.append(f"Something on this computer already uses the name {mapper}. Restart the computer and try again.")
            continue
        layout["erased"].append(x["path"])
        tables.append({"disk": x["path"], "id": x["id"], "new_table": True, "delete": [], "retype": [],
                       "create": [{"number": 1, "start": 0, "end": 0, "code": "8300",
                                   "name": "Starchaser home" if use == "home" else "Starchaser data", "vol": len(vols)}]})
        vols.append({"kind": "new", "role": "home" if use == "home" else "data", "disk": x["path"], "partition": "",
                     "uuid": "", "fs": "btrfs" if use == "home" else "ext4", "mount": mount,
                     "subvol": "@home" if use == "home" else "", "encrypt": locked, "mapper": mapper if locked else "",
                     "keyfile": locked, "name": name, "label": "home" if use == "home" else name[:16],
                     "owner": use == "files", "nofail": use == "files", "bookmark": use == "files",
                     "removable": x["speed"]["rank"] == 0, "size": x["size"]})
        lock = ", locked with the same unlock as Starchaser" if locked else ""
        oses = f", including {', '.join(x['oses'])}," if x["oses"] else ""
        if use == "home":
            steps.append(f"Erase everything on {dn}{oses} and keep your home folder there (documents, downloads, "
                         f"settings){lock}")
        else:
            steps.append(f"Erase everything on {dn}{oses} and use it for files: it appears as {name} in Files{lock}")
            if x["speed"]["rank"] == 0:
                removable.append(name)
    if homes > 1:
        errs.append("Only one drive can hold your home folder.")
    for e in keeps:
        part = e.get("partition", "")
        if any(_on_disk(l, part) for l in live):
            errs.append(LIVE_USB)
            continue
        x, p = find_partition(info, part)
        label = (p or {}).get("label", "")
        default = label if re.fullmatch(r"[A-Za-z0-9 _-]{1,32}", label or "") else "Drive"
        name, slug, problem = name_slug(e.get("name") or ("" if e.get("mount") else default), e.get("mount", ""))
        if not p:
            errs.append(f"{name or part} ({part}) isn't here any more. Look again on the Drive step.")
            continue
        where = f"{name} (on {x['model']})"
        if problem:
            errs.append(problem)
            continue
        if e.get("uuid") and not _same_uuid(e["uuid"], p["uuid"]):
            errs.append(f"{where} changed since the list was made. Look again on the Drive step.")
            continue
        if x["path"] in layout["erased"] or (x["path"] == d["path"] and mode == "erase"):
            errs.append(f"{where} is on a drive this install erases. Keep it, or erase the drive, not both.")
            continue
        if (layout.get("shrink") or {}).get("partition") == part:
            errs.append(f"{where} is the partition being shrunk. Keep it after Starchaser is installed instead.")
            continue
        if p["keep"].get("blocked"):
            errs.append(p["keep"]["blocked"])
            continue
        if slug in names:
            errs.append(f"Two drives are named {name}. Give each one its own name.")
            continue
        names[slug] = name
        luks = p["encrypted"] == "luks"
        mapper = f"crypt-{slug}" if luks else ""
        if luks and mapper_exists(mapper):
            errs.append(f"Something on this computer already uses the name {mapper}. Restart the computer and try again.")
            continue
        pk = peek(part, e.get("passphrase", ""))
        problem = _keep_errors(name, p, pk)
        if problem:
            errs.append(problem)
            continue
        fs = pk.get("fs") or p["fs"]
        used = pk.get("used") or p["used"]
        vols.append({"kind": "keep", "role": "data", "disk": x["path"], "partition": part, "uuid": p["uuid"],
                     "fs": fs, "luks": luks, "luks_uuid": p["fs_uuid"] if luks else "",
                     "fs_uuid": pk.get("fs_uuid") or ("" if luks else p["fs_uuid"]), "mount": f"/mnt/{slug}",
                     "mapper": mapper, "keyfile": luks and locked, "encrypt": False, "name": name, "owner": False,
                     "nofail": True, "bookmark": True, "removable": x["speed"]["rank"] == 0, "size": p["size"]})
        _extra_pkgs(layout, fs)
        if luks:
            steps.append(f"Use {name} ({size_text(p['size'])}, on {x['model']}) as it is: "
                         + ("it opens with Starchaser from now on" if locked else "it asks for its own disk key at every start")
                         + "; its disk key stays the same")
            if not locked:
                notes.append(f"{name} asks for its own disk key at every start, since Starchaser itself isn't locked.")
        else:
            steps.append(f"Use {name} ({size_text(p['size'])}" + (f", {size_text(used)} used" if used else "")
                         + f", on {x['model']}) as it is: its files stay, and it appears as {name} in Files")
        if fs == "ntfs":
            notes.append(f"Windows must be fully shut down (not Fast Startup) before Starchaser can open {name}. If it "
                         f"isn't, Starchaser still starts, and {name} stays closed until it is.")
        if fs in ("ext4", "btrfs", "xfs") and not owners_note:
            owners_note = True
            notes.append(f"Files on {name} keep their current owners; if they came from another computer, you may need "
                         "to take ownership in Files.")
        if x["speed"]["rank"] == 0:
            removable.append(name)
    for n in removable:
        notes.append(f"{n} is on a USB drive: Starchaser starts without it when it's unplugged, and it appears in Files "
                     "when it's back.")
    touched = {d["path"], *used_disks, *(v["disk"] for v in vols)}
    rest = [drive_name(x) for x in info["disks"] if x["path"] not in touched]
    if rest:
        notes.append("Not touched: " + ", ".join(rest) + ".")


def _mount_ok(m: str) -> bool:
    return m in SYSTEM_MOUNTS or bool(re.fullmatch(r"/(mnt|data|home)/[A-Za-z0-9_][A-Za-z0-9._-]{0,31}", m))


def _free_blocks(x: dict, gone: set, new_table: bool) -> list:
    """[[first, last]] free sectors on a drive once the partitions in gone are deleted (or all, with new_table)."""
    first, last = x["first"], x["last"]
    if new_table:
        return [[max(first, 2048 if x["sector"] == 512 else first), last]]
    used = sorted((p["start"], p["end"]) for p in x["partitions"] if p["path"] not in gone and p.get("start") is not None)
    blocks, cur = [], first
    for s, e in used + [(last + 1, last + 1)]:
        if s > cur:
            blocks.append([cur, s - 1])
        cur = max(cur, e + 1)
    return blocks


def _place(blocks: list, sectors: int, start, align: int):
    """Carve a partition out of the free blocks (updated in place): at start (sectors) when given, else in the first
    block it fits (sectors 0 = all of the largest block). -> (start, end), "overlap" or "room"."""
    order = range(len(blocks))
    if start is None and sectors == 0:
        order = sorted(order, key=lambda i: blocks[i][0] - blocks[i][1])          # the largest first
    for i in order:
        bs, be = blocks[i]
        if start is not None:
            if not bs <= start <= be:
                continue
            s = -(-start // align) * align
        else:
            s = -(-bs // align) * align
        e = be if sectors == 0 else s + sectors - 1
        if s > be or e > be or e - s + 1 < align:
            if start is not None:
                return "room"
            continue
        blocks[i:i + 1] = ([[bs, s - 1]] if s > bs else []) + ([[e + 1, be]] if e < be else [])
        return s, e
    return "overlap" if start is not None else "room"


GENERIC_PART_NAMES = re.compile(r"(EFI system( partition)?|Microsoft reserved partition|Basic data partition|"
                                r"Microsoft basic data|Linux filesystem|Linux swap|Linux root.*|Starchaser)", re.I)


def _part_desc(p: dict) -> str:
    """A partition in the Advanced view's words: its own name (file system label, else its GPT name unless that's
    a generic one), then what it holds ("ext4", "locked", "Windows data")."""
    if p.get("encrypted") == "luks":
        what = "locked"
    elif p.get("fs") in ("ext4", "btrfs", "xfs", "exfat"):
        what = p["fs"]
    else:
        what = (p.get("role") or p["fs"] or "empty").replace(" (data or recovery)", " data")
    name = p.get("label") or ("" if GENERIC_PART_NAMES.fullmatch(p.get("name") or "") else p.get("name") or "")
    return ", ".join(x for x in (name, what) if x)


def _folder_name(mount: str, label: str = "") -> str:
    """What Files calls a data folder: the partition's own label when the folder is named after it ("Photos" for
    /mnt/photos), else the folder's name."""
    base = mount.rsplit("/", 1)[-1]
    slug = re.sub(r"[^a-z0-9_-]", "", str(label or "").strip().lower().replace(" ", "-"))
    return label.strip() if label and slug == base else base


def plan_manual(a: dict, info: dict, errs: list, steps: list, notes: list, layout: dict) -> tuple:
    """Advanced ("mode": "manual"): every drive's partitions as the person set them. -> (the drive that holds /,
    whether / is encrypted), (None, None) without a /."""
    man = a.get("manual") or {}
    if any(e.get("use", "leave") != "leave" for e in a.get("drives") or []) or a.get("keep"):
        errs.append("Advanced already says what happens to every drive.")
    alldisks = {x["path"]: x for x in info["disks"]}
    live = set(info.get("live", []))
    luks_steps = []                        # steps for kept locked partitions (what happens to their passphrase)
    vols, tables, seen = layout["volumes"], layout["tables"], set()
    for md in man.get("drives") or []:
        path = md.get("disk")
        if path in live:
            errs.append(LIVE_USB)
            continue
        x = alldisks.get(path)
        if not x:
            errs.append(f"{path} isn't here any more (it may have been unplugged). Look again on the Drive step.")
            continue
        dn = drive_name(x)
        if path in seen:
            errs.append(f"{dn} is listed twice.")
            continue
        seen.add(path)
        if md.get("id") and md["id"] != x["id"]:
            errs.append(f"{dn} changed since the list of drives was made (it may have been unplugged). Look again on "
                        "the Drive step.")
            continue
        new_table = bool(md.get("new_table"))
        deletes, existing, creates = md.get("delete") or [], md.get("existing") or [], md.get("create") or []
        changes = new_table or deletes or creates or any(e.get("format") for e in existing)
        if not x["table_ok"] and not new_table and (deletes or creates or existing):
            errs.append(f"{dn}'s partition list couldn't be read, so it can't be changed here.")
            continue
        if x["in_use"] and changes:
            errs.append(f"{dn} is in use right now, so it can't be changed.")
            continue
        if creates and not new_table and x["table"] != "gpt":
            errs.append(f"The partition table on {dn} isn't GPT. Start it over (Erase the partition table) to add "
                        "partitions.")
            continue
        parts = {p["path"]: p for p in x["partitions"]}
        t = {"disk": path, "id": x["id"], "new_table": new_table, "delete": [], "retype": [], "create": []}
        gone = set()
        if new_table:
            gone = set(parts)
            layout["erased"].append(path)
            steps.append(f"Erase the partition table on {dn}: every partition on it goes")
        else:
            for dl in deletes:
                p = parts.get(dl.get("partition"))
                if not p or not _same_uuid(dl.get("uuid"), p["uuid"]):
                    errs.append(f"Partition {dl.get('partition')} on {dn} changed since the list was made. Look again "
                                "on the Drive step.")
                    continue
                gone.add(p["path"])
                t["delete"].append({"partition": p["path"], "uuid": p["uuid"], "number": p["number"]})
                steps.append(f"Delete partition {p['number']} on {dn} ({_part_desc(p)}, {size_text(p['size'])}): "
                             "its files are lost")
        for ex in existing:
            p = parts.get(ex.get("partition"))
            mount, fmt = ex.get("mount") or "", ex.get("format") or ""
            if not p:
                errs.append(f"Partition {ex.get('partition')} on {dn} isn't here any more. Look again on the Drive step.")
                continue
            if new_table:
                errs.append(f"Partition {p['number']} on {dn} is on a drive this install starts over. Keep it, or "
                            "start the drive over, not both.")
                continue
            if p["path"] in gone:
                errs.append(f"Partition {p['number']} on {dn} is set to be deleted and also used. Pick one.")
                continue
            if (fmt or ex.get("uuid")) and not _same_uuid(ex.get("uuid"), p["uuid"]):
                errs.append(f"Partition {p['number']} on {dn} changed since the list was made. Look again on the Drive "
                            "step.")
                continue
            desc = f"partition {p['number']} on {dn} ({_part_desc(p)}, {size_text(p['size'])})"
            base = {"disk": path, "partition": p["path"], "uuid": p["uuid"], "number": p["number"], "size": p["size"],
                    "mount": "" if fmt == "swap" else mount, "name": "", "owner": False, "nofail": False,
                    "bookmark": False, "removable": x["speed"]["rank"] == 0, "mapper": "", "keyfile": False,
                    "luks": False, "subvol": "", "label": "", "used": p.get("used") or 0}
            if fmt:
                if fmt not in MANUAL_FS:
                    errs.append(f"Unknown file system {fmt!r} for {desc}.")
                    continue
                if p["in_use"]:
                    errs.append(f"{desc[0].upper() + desc[1:]} is in use right now, so it can't be formatted.")
                    continue
                esp = p["type"] == ESP_TYPE and fmt == "fat32"
                vols.append(dict(base, kind="format", fs=fmt, encrypt=bool(ex.get("encrypt")), esp=esp))
                if fmt == "fat32" and mount == "/boot" and not esp and p["type"] != XBOOTLDR:
                    t["retype"].append({"partition": p["path"], "uuid": p["uuid"], "number": p["number"], "code": "ea00"})
                steps.append(f"Format {desc} as {FS_WORD[fmt]}" + (f" for {mount}" if mount and fmt != "swap" else "")
                             + (", encrypted" if ex.get("encrypt") else "") + ": everything on it is lost")
                continue
            if not mount:
                continue                                       # listed without a job: left as it is
            if mount in ("/boot", "/efi"):
                if p["fs"] != "vfat":
                    errs.append(BOOT_FAT)
                    continue
                if mount == "/boot" and p["type"] not in (ESP_TYPE, XBOOTLDR):
                    errs.append(f"A FAT32 partition kept at /boot must be an EFI system partition or a boot partition "
                                f"(XBOOTLDR). Format {desc} for /boot instead.")
                    continue
                # what is on it now (read-only look; an unmounted partition reports no used space itself). "free" stays
                # None when the look fails: the checks below then refuse instead of taking the partition for empty.
                pk = peek(p["path"])
                if pk.get("ok"):
                    base["used"] = int(pk.get("used") or 0)
                    base["free"] = max(0, int(pk.get("size") or p["size"]) - base["used"])
                elif p.get("used"):                            # mounted right now: lsblk knows
                    base["free"] = max(0, p["size"] - p["used"])
                else:
                    base["free"], base["look_error"] = None, pk.get("error") or ""
                vols.append(dict(base, kind="keep", fs="fat32", encrypt=False, esp=p["type"] == ESP_TYPE))
            elif mount == "/":
                errs.append("/ must be a new or formatted partition: Starchaser doesn't install over files that are there.")
                continue
            else:
                if p["keep"].get("blocked"):
                    errs.append(p["keep"]["blocked"])
                    continue
                luks = p["encrypted"] == "luks"
                data = mount not in SYSTEM_MOUNTS
                if luks and not data:
                    errs.append("A locked partition you keep can be used only under /mnt or /data.")
                    continue
                slug = mount.strip("/").replace("/", "-").lower()
                pk = peek(p["path"], ex.get("passphrase", ""))
                problem = _keep_errors(f"partition {p['number']} on {dn}", p, pk)
                if problem:
                    errs.append(problem)
                    continue
                fs = pk.get("fs") or p["fs"]
                vols.append(dict(base, kind="keep", fs=fs, encrypt=False, esp=False, luks=luks,
                                 luks_uuid=p["fs_uuid"] if luks else "",
                                 fs_uuid=pk.get("fs_uuid") or ("" if luks else p["fs_uuid"]),
                                 mapper=f"crypt-{slug}" if luks else "", name=_folder_name(mount, pk.get("label") or p.get("label")),
                                 nofail=data, bookmark=data,
                                 # a Linux home kept from an earlier install keeps its folders in @home
                                 subvol="@home" if mount == "/home" and fs == "btrfs"
                                 and "@home" in (pk.get("subvolumes") or []) else ""))
                _extra_pkgs(layout, fs)
                if mount == "/home":
                    notes.append("If your home folder is already on it, its files stay. Starchaser replaces only its own "
                                 "settings folders there and keeps copies of the old ones in "
                                 ".local/share/starchaser/before-install.")
                if fs == "ntfs":
                    notes.append(f"Windows must be fully shut down (not Fast Startup) before Starchaser can open "
                                 f"{mount}. If it isn't, Starchaser still starts, and {mount} stays closed until it is.")
            if p["encrypted"] == "luks" and mount not in ("/boot", "/efi"):
                luks_steps.append(len(steps))             # finished below, once it's known whether / is locked
            steps.append(f"Use {desc} as it is at {mount}")
        # new partitions: explicit sectors, 1 MiB aligned, in the free space left after the deletes
        blocks = _free_blocks(x, gone, new_table)
        align = max(1, MIB // x["sector"])
        numbers = {p["number"] for p in x["partitions"] if p["path"] not in gone}
        short = 0
        for c in creates:
            fs, mount = c.get("fs"), c.get("mount") or ""
            if fs not in MANUAL_FS:
                errs.append(f"Unknown file system {fs!r} for a new partition on {dn}.")
                continue
            if c.get("esp") and fs != "fat32":
                errs.append("The EFI system partition must be FAT32.")
                continue
            try:
                size_mib = int(c.get("size_mib") or 0)
                start = None if c.get("start") in (None, "") else int(c["start"])
            except (TypeError, ValueError):
                errs.append(f"A new partition on {dn} has a size or start that isn't a number.")
                continue
            if size_mib < 0:
                errs.append(f"A new partition on {dn} has a size below zero.")
                continue
            sectors = size_mib * MIB // x["sector"]
            pos = _place(blocks, sectors, start, align)
            if pos == "overlap":
                errs.append(f"A new partition at {size_text(start * x['sector'])} overlaps a partition you're keeping.")
                continue
            if pos == "room":
                short += max(sectors, align) * x["sector"]
                continue
            n = next(i for i in range(1, 129) if i not in numbers) if len(numbers) < 128 else 0
            if not n:
                errs.append(f"{dn} has no room for another partition in its table.")
                continue
            numbers.add(n)
            s, e = pos
            esp = bool(c.get("esp"))
            code = "ef00" if esp else "ea00" if fs == "fat32" and mount == "/boot" else "8200" if fs == "swap" else "8300"
            pname = {"/": "Starchaser", "/boot": "Starchaser boot"}.get(mount, "EFI system" if esp else
                                                                          "Starchaser swap" if fs == "swap" else "Starchaser data")
            size_b = (e - s + 1) * x["sector"]
            t["create"].append({"number": n, "start": s, "end": e, "code": code, "name": pname, "vol": len(vols)})
            vols.append({"kind": "new", "disk": path, "partition": "", "uuid": "", "number": n, "size": size_b,
                         "fs": fs, "mount": "" if fs == "swap" else mount, "encrypt": bool(c.get("encrypt")), "esp": esp,
                         "name": "", "owner": False, "nofail": False, "bookmark": False,
                         "removable": x["speed"]["rank"] == 0, "mapper": "", "keyfile": False, "luks": False,
                         "subvol": "", "label": ""})
            steps.append(f"Create a {size_text(size_b)} {FS_WORD[fs]}" + (" EFI system" if esp else "")
                         + f" partition on {dn}" + (f" for {mount}" if mount and fs != "swap" else "")
                         + (", encrypted" if c.get("encrypt") else ""))
        if short:
            errs.append(f"The new partitions on {dn} need {size_text(short)} more than its free space.")
        if t["new_table"] or t["delete"] or t["create"] or t["retype"]:
            tables.append(t)
    # every mount point once, only where the system allows it; one /; the EFI system partition; locking
    mounts = {}
    for v in vols:
        if v["fs"] == "swap":
            continue
        m = v["mount"]
        if not m:
            errs.append("Each new or formatted partition needs a mount point (or swap).")
        elif not _mount_ok(m):
            errs.append("Mount points start with / and can't be /usr, /etc, /var/log or other folders the system manages.")
        elif m in mounts:
            if len(mounts[m]) == 1:
                errs.append(f"Two partitions are set to {m}. Each mount point can be used once.")
            mounts[m].append(v)
        else:
            mounts[m] = [v]
    if any(v["fs"] == "fat32" and v["mount"] not in ("/boot", "/efi") for v in vols):
        errs.append("FAT32 is only for the startup partitions (/boot or /efi). Choose ext4, btrfs or xfs for files.")
    roots = mounts.get("/", [])
    root = roots[0] if roots else None
    if not root:
        errs.append("One partition must be mounted at /: that's where Starchaser goes.")
    else:
        if root["fs"] not in ("btrfs", "ext4", "xfs"):
            errs.append("/ must be btrfs, ext4 or xfs.")
        if root["size"] < MIN_ROOT:
            errs.append(f"/ is {size_text(root['size'])}; Starchaser needs at least {size_text(MIN_ROOT)}.")
    for m in ("/boot", "/efi"):
        if any(v["fs"] != "fat32" or v.get("encrypt") for v in mounts.get(m, [])):
            errs.append(BOOT_FAT)
    esps = [v for v in vols if v.get("esp") and v["mount"] in ("/boot", "/efi")]
    dual, esp = False, None
    boot = (mounts.get("/boot") or [None])[0]
    if len(esps) > 1:
        errs.append("Only one EFI system partition can be used.")
    elif not esps:
        errs.append(ESP_NEEDED)
    else:
        esp = esps[0]
        boot = (mounts.get("/boot") or [None])[0]
        if esp["mount"] == "/boot":
            if "/efi" in mounts or (esp["kind"] != "keep" and esp["size"] < MIN_ESP):
                errs.append(ESP_NEEDED)
        elif not boot or boot.get("esp") or (boot["kind"] != "keep" and boot["size"] < MIN_ESP):
            errs.append(ESP_NEEDED)
        elif boot["disk"] != esp["disk"]:
            # systemd-boot looks for the boot partition (XBOOTLDR) only on the drive its EFI partition is on
            errs.append("The /boot partition must be on the same drive as the EFI system partition at /efi.")
        else:
            dual = True
        # the partition that holds the kernels: new or formatted ones are judged by size, a kept one by free space
        holder = esp if esp["mount"] == "/boot" else boot
        if holder and not any(e == ESP_NEEDED for e in errs):
            where = drive_name(alldisks[holder["disk"]])
            if holder["kind"] != "keep":
                if holder["size"] < WARN_ESP:
                    notes.append(f"The boot partition is {room_text(holder['size'])}. NVIDIA graphics and several kernels "
                                 "need about 4 GB, and the install could run out of space. 4 GB is best.")
            elif holder["size"] < KEPT_BOOT_MIN:               # too small even when empty: no look needed
                errs.append(f"The existing boot partition on {where} is only {room_text(holder['size'])}, and this "
                            "install needs at least 2 GB free there (4 GB is best). Nothing has been changed. "
                            + ("Keep it at /efi and add a new /boot of at least 2 GB." if holder.get("esp") else
                               "Use a partition of at least 2 GB for /boot."))
            elif holder.get("free") is None:
                errs.append(f"Starchaser couldn't check how much room is free on the existing boot partition on {where}. "
                            f"{holder.get('look_error') or ''} Nothing has been changed. Format it, or add a new /boot "
                            "of at least 2 GB.".replace("  ", " "))
            elif holder["free"] < KEPT_BOOT_MIN:
                errs.append(f"The existing boot partition on {where} has only {room_text(holder['free'])} free, and this "
                            "install needs at least 2 GB free there (4 GB is best). Nothing has been changed. Make "
                            "room, or format it, or add a new /boot of at least 2 GB.")
            elif holder["free"] < KEPT_BOOT_WARN:
                # free space within FAT32's own tables of 2 GB counts as 2 GB here, as it does for the limit above:
                # "has 1.9 GB free" next to a refusal that says "needs at least 2 GB free" would read as a mistake
                notes.append(f"The existing boot partition on {where} has {room_text(max(holder['free'], MIN_ESP))} "
                             "free. NVIDIA graphics and several kernels need about 4 GB, and the install could run "
                             "out of space. 4 GB is best.")
        if dual and esp["kind"] == "keep":
            where = drive_name(alldisks[esp["disk"]])
            if esp.get("free") is None:
                errs.append(f"Starchaser couldn't check how much room is free on the existing EFI system partition on "
                            f"{where}. {esp.get('look_error') or ''} Nothing has been changed.".replace("  ", " "))
            elif esp["free"] < KEPT_LOADER_BYTES:
                errs.append(f"The existing EFI system partition on {where} has only {int(esp['free'] // 10 ** 6)} MB "
                            f"free, and the startup loader needs about {KEPT_LOADER_BYTES // 10 ** 6} MB. Nothing has "
                            "been changed. Make room on it from the system that is already there (old startup files "
                            "are the usual cause), then try again.")
    if secure_boot() and boot and boot['size'] < 4_000_000_000:
        errs.append("Secure Boot needs at least 4 GB at /boot for signed startup files and a previous working start.")
    root_enc = bool(root and root.get("encrypt"))
    if any(v is not root and v.get("encrypt") and v["fs"] != "swap" for v in vols) and not root_enc:
        errs.append("To lock other partitions, lock / too.")
    # what each volume is, its encrypted volume's name, and how it starts
    mappers = {MAPPER}
    for v in vols:
        m = v["mount"]
        if v is root:
            v["role"], v["mapper"] = "root", MAPPER if root_enc else ""
        elif v is esp or (m in ("/boot", "/efi")):
            v["role"] = "esp" if v is esp else "boot"
        elif v["fs"] == "swap":
            v["role"], v["mapper"] = "swap", "cryptswap" if v.get("encrypt") else ""
        else:
            data = m not in SYSTEM_MOUNTS
            slug = m.strip("/").replace("/", "-").lower()
            v["role"] = "data" if data else "system"
            if v["kind"] != "keep":
                v["mapper"] = ("crypthome" if m == "/home" else f"crypt-{slug}") if v.get("encrypt") else ""
                v["keyfile"] = bool(v.get("encrypt"))
                v["owner"] = v["nofail"] = v["bookmark"] = data
                v["name"] = m.rsplit("/", 1)[-1]
                v["label"] = v["name"][:16]
            else:
                v["keyfile"] = bool(v.get("luks")) and root_enc
        if v.get("mapper") and v["role"] != "root":
            # each encrypted volume needs its own name (and keyfile): /mnt/A and /mnt/a, or two encrypted swaps,
            # would otherwise share one, and the second would never open
            base_m, k = v["mapper"], 2
            while v["mapper"] in mappers:
                v["mapper"], k = f"{base_m}-{k}", k + 1
            mappers.add(v["mapper"])
        if v.get("mapper") and v["role"] != "root" and mapper_exists(v["mapper"]):
            errs.append(f"Something on this computer already uses the name {v['mapper']}. Restart the computer and try again.")
        _extra_pkgs(layout, v["fs"])
    if root:
        layout["disk"] = root["disk"]
        layout["root_fs"] = root["fs"]
        if root["fs"] != "btrfs":
            notes.append(f"With {root['fs']} for /, Starchaser can't take snapshots: Settings › Recovery stays empty.")
    layout["dual"] = dual
    if esp:
        layout["esp_disk"] = esp["disk"]
        if root and esp["disk"] != root["disk"]:
            notes.append(f"If this computer doesn't start Starchaser, pick {drive_name(alldisks[esp['disk']])} in its own "
                         "startup menu (a key like F12, F11 or F8 as it turns on).")
    for i in luks_steps:                   # a key is added to it (a write): the Summary says so, as the simple view does
        steps[i] += (": it opens with Starchaser from now on; its disk key stays the same" if root_enc
                     else ": it asks for its own disk key at every start")
    for v in vols:
        if v["kind"] == "keep" and v.get("luks") and not v["keyfile"]:
            notes.append(f"{v['mount']} asks for its own disk key at every start, since Starchaser itself isn't locked.")
    d = alldisks.get(esp["disk"]) if esp else (alldisks.get(root["disk"]) if root else None)
    return d, (root_enc if root else None)


def full_name_problem(name: str) -> str:
    """The full name goes into the account's comment field: anything there is fine (accents, apostrophes, emoji)
    except a colon, which separates the fields, and control characters such as a line break."""
    if not name.strip():
        return "Type your name."              # the same words as the graphical installer
    if ":" in name:
        return "Your name can't contain a colon (:)."
    if any(ord(c) < 32 or ord(c) == 127 for c in name):
        return "Your name can't contain a line break or tab."
    return ""


def keymaps() -> set:
    return {Path(f).name.split(".")[0] for f in glob.glob("/usr/share/kbd/keymaps/**/*.map*", recursive=True)}


def xkb_layouts() -> tuple:
    """(layouts, {layout: variants}) from the keyboard database; (set(), {}) when it isn't there."""
    lays, variants, sec = set(), {}, ""
    try:
        for line in Path("/usr/share/X11/xkb/rules/evdev.lst").read_text().splitlines():
            if line.startswith("! "):
                sec = line[2:].strip()
            elif line.strip() and sec == "layout":
                lays.add(line.split()[0])
            elif line.strip() and sec == "variant":
                parts = line.split()
                if len(parts) >= 2:
                    variants.setdefault(parts[1].rstrip(":"), set()).add(parts[0])
    except OSError:
        pass
    return lays, variants


DISPLAY_MODE = re.compile(r"\d{2,5}x\d{2,5}@\d{1,3}(\.\d{1,3})?")


def _whole(v) -> bool:
    return isinstance(v, int) and not isinstance(v, bool)


def displays_ok(ds) -> bool:
    """An answers file's "displays" (none at all is fine): screens starchaser displays can write, at most one main."""
    if ds is None:
        return True
    return (isinstance(ds, list) and 0 < len(ds) <= 16 and all(
        isinstance(m, dict) and isinstance(m.get("desc"), str) and 0 < len(m["desc"]) <= 200
        and isinstance(m.get("name", ""), str) and len(m.get("name", "")) <= 32
        and isinstance(m.get("mode"), str) and DISPLAY_MODE.fullmatch(m["mode"]) is not None
        and _whole(m.get("x")) and _whole(m.get("y")) and _whole(m.get("transform", 0)) and 0 <= m.get("transform", 0) <= 7
        and isinstance(m.get("scale"), (int, float)) and not isinstance(m["scale"], bool) and 0 < m["scale"] <= 4
        for m in ds) and sum(1 for m in ds if m.get("primary")) <= 1)


def setting_problems(a: dict) -> list:
    """The keyboard, language and checkout an answers file names, checked against the system's own lists (scripted
    installs can name anything, not just what the two installers offer)."""
    errs = []
    km = a.get("keymap", "us")
    if not re.fullmatch(r"[A-Za-z0-9_.-]+", km) or (Path("/usr/share/kbd/keymaps").is_dir() and km not in keymaps()):
        errs.append(f"Unknown console keyboard {km!r}.")
    loc = a.get("locale", "en_US.UTF-8")
    try:
        supported = {l.split()[0] for l in Path("/usr/share/i18n/SUPPORTED").read_text().splitlines() if l.strip()}
    except OSError:
        supported = set()
    if not re.fullmatch(r"[A-Za-z0-9_@.-]+", loc) or ".UTF-8" not in loc or (supported and loc not in supported):
        errs.append(f"Unknown language and formats {loc!r}.")
    xkb = a.get("xkb_layout") or "us"
    m = re.fullmatch(r"([a-z0-9_]+)(?:\(([A-Za-z0-9_-]+)\))?", xkb)
    lays, variants = xkb_layouts()
    if not m or (lays and (m.group(1) not in lays or (m.group(2) and m.group(2) not in variants.get(m.group(1), set())))):
        errs.append(f"Unknown keyboard layout {xkb!r}.")
    errs.extend(pkgrepo.answer_problems(a))
    if not displays_ok(a.get("displays")):
        errs.append("The screen layout in the answers isn't one the installer can use.")
    repo = Path(a.get("repo") or "/usr/share/starchaser/repo")
    if not errs and pkgrepo.desktop_source(a) == "checkout" and (
            not (repo / "config/hypr/hyprland.lua").is_file() or not (repo / "installer/starchaser-desktop-setup.sh").is_file()):
        errs.append(f"The Starchaser files this installer needs aren't at {repo}.")
    return errs


# --------------------------------------------------------------------------------------------- doing it
def shrink_partition(disk: str, sh_: dict) -> None:
    dev, fs, new = sh_["partition"], sh_["fs"], sh_["new_bytes"]
    emit(event="phase", phase="shrink", label=f"Shrinking {dev}")
    fs_bytes = new - 16 * MIB                                   # the filesystem a little smaller than its partition
    if fs == "ntfs":
        # checked again right before, by its exit code, without --force: Windows may have marked it for a disk
        # check since the drive list was made, and forcing would skip that refusal
        r = sh("ntfsresize", "--info", "--no-action", dev, check=False)
        if r.returncode != 0:
            out = r.stdout + r.stderr
            fail(NTFS_FAST if re.search(r"hibernat|Fast Restart|unclean", out, re.I) else NTFS_CHECK)
        sh("ntfsresize", "--no-action", "--size", str(fs_bytes), dev)
        sh("ntfsresize", "--force", "--force", "--size", str(fs_bytes), dev, input="y\n")   # --force twice: no prompt
    elif fs == "ext4":
        # e2fsck's 1 means it found problems and fixed them: the file system is fine to shrink now
        rc = sh("e2fsck", "-f", "-y", dev, check=False).returncode
        if rc not in (0, 1):
            fail(f"The check of {dev} before shrinking found problems it couldn't fix. Nothing was shrunk. "
                 "Check that drive from the system on it first, then try again.")
        sh("resize2fs", dev, f"{fs_bytes // 1024}K")
    elif fs == "btrfs":
        tmp = Path("/run/starchaser-shrink")
        tmp.mkdir(exist_ok=True)
        sh("mount", dev, tmp)
        try:
            sh("btrfs", "filesystem", "resize", str(fs_bytes), tmp)
        finally:
            sh("umount", tmp, check=False)
    else:
        fail(f"Can't shrink a {fs} partition.")
    n = int(re.search(r"(\d+)$", dev).group(1))
    ss = sector_size(disk)
    sh("sfdisk", "--no-reread", "-N", str(n), disk, input=f", {new // ss}\n")   # same start, new size (in sectors)
    sh("partprobe", disk, check=False)
    sh("udevadm", "settle")
    got = next((pp["size"] * ss for pp in partition_table(disk).get("partitions", []) if pp.get("node") == dev), 0)
    if got < fs_bytes:
        fail(f"The partition table didn't take the new size for {dev}.")


def partition_table(disk: str) -> dict:
    try:
        return json.loads(subprocess.run(["sfdisk", "-J", disk], capture_output=True, text=True).stdout)["partitiontable"]
    except (ValueError, KeyError):
        return {}


def sector_size(disk: str) -> int:
    """The drive's own sector size: sfdisk counts in it (512 on most drives, 4096 on 4Kn ones)."""
    return int(partition_table(disk).get("sectorsize") or 512)


def partition_ids(disk: str, table: dict = None) -> dict:
    """{partition: its unique id} from the partition table."""
    t = partition_table(disk) if table is None else table
    return {p["node"]: p.get("uuid", "") for p in t.get("partitions", []) if p.get("node")}


OUR_NAMES = ("Starchaser boot", "Starchaser")


def free_regions(table: dict) -> list:
    """[(first sector, last sector)] of every gap in a partition table (the same walk as disks())."""
    used = sorted((p["start"], p["start"] + p["size"]) for p in table.get("partitions", []))
    cur, last, out = table.get("firstlba", 2048), table.get("lastlba", 0), []
    for a, b in used + [(last + 1, last + 1)]:
        if a > cur:
            out.append((cur, a - 1))
        cur = max(cur, b)
    return out


def target_region(disk: str, mode: str, lay: dict, table: dict) -> tuple:
    """The gap the reviewed plan named, in sectors: the free space it measured, or the space a shrink just freed
    (right after the shrunk partition). Never "the largest gap": with two gaps of about the same size, adding the
    boot partition changed which one was largest, and root landed somewhere the plan never said."""
    gaps = free_regions(table)
    if mode == "free":
        want = (lay.get("free") or {}).get("start")
        gap = next((g for g in gaps if g[0] == want), None)
    else:
        node = (lay.get("shrink") or {}).get("partition")
        p = next((x for x in table.get("partitions", []) if x.get("node") == node), None)
        gap = next((g for g in gaps if p and g[0] == p["start"] + p["size"]), None)
    ss = int(table.get("sectorsize") or 512)
    if not gap or (gap[1] - gap[0] + 1) * ss < required_free():
        fail("The free space the plan was going to use isn't there now, so nothing was added. Try again.")
    return gap


def new_partitions(disk: str, mode: str, lay: dict = None) -> tuple:
    """-> (esp, xbootldr or "", root partition). Erase makes a fresh table; free/shrink adds two partitions in the
    gap the plan named (target_region)."""
    emit(event="phase", phase="partition", label="Partitioning")
    if mode == "erase":
        sh("wipefs", "-af", disk)
        sh("sgdisk", "--zap-all", disk)
        sh("sgdisk", "-n", f"1:0:+{boot_bytes() // GIB}G", "-t", "1:ef00", "-c", "1:EFI system", disk)
        sh("sgdisk", "-n", "2:0:0", "-t", "2:8300", "-c", "2:Starchaser", disk)
        sh("partprobe", disk, check=False)
        sh("udevadm", "settle")
        time.sleep(2)
        return part_path(disk, 1), "", part_path(disk, 2)
    before = {p["path"] for d in disks()["disks"] if d["path"] == disk for p in d["partitions"]}
    # the partitions this attempt adds, by their unique ids: a failure removes exactly these (a finished Starchaser
    # elsewhere on the drive has the same names, so names are never used for that)
    # A table that couldn't be read would make every partition on the drive look new (and a failure would then
    # delete them all): stop before anything is written instead.
    table = partition_table(disk)
    old_ids = set(partition_ids(disk, table).values())
    if not table or (before and len(old_ids) < len(before)) or "" in old_ids:
        fail("Couldn't read the list of partitions on this drive, so no new ones were added. Try again.")
    first, last = target_region(disk, mode, lay or {}, table)
    try:
        # partition number 0 = the next free number; both inside the planned gap, by sector
        sh("sgdisk", "-n", f"0:{first}:+{boot_bytes() // GIB}G", "-t", "0:ea00", "-c", "0:Starchaser boot", disk)
        boot = next((p for p in partition_table(disk).get("partitions", [])
                     if p.get("uuid") and p["uuid"] not in old_ids and p.get("name") == "Starchaser boot"), None)
        if not boot or not first <= boot["start"] <= last:
            fail("The new boot partition didn't land in the planned free space.")
        sh("sgdisk", "-n", f"0:{boot['start'] + boot['size']}:{last}", "-t", "0:8300", "-c", "0:Starchaser", disk)
    finally:
        # only a partition that wasn't there before AND carries one of the two names this attempt gave: at most two
        now = partition_table(disk).get("partitions", [])
        STATE["new_parts"] += [(disk, p["node"], p["uuid"]) for p in now
                              if p.get("node") and p.get("uuid") and p["uuid"] not in old_ids
                              and p.get("name") in OUR_NAMES][:2]
    sh("partprobe", disk, check=False)
    sh("udevadm", "settle")
    time.sleep(2)
    d = next(x for x in disks()["disks"] if x["path"] == disk)
    added = [p for p in d["partitions"] if p["path"] not in before]
    xb = next((p["path"] for p in added if p["name"] == "Starchaser boot"), "")
    root = next((p["path"] for p in added if p["name"] == "Starchaser"), "")
    if not xb or not root:
        fail("The new partitions didn't appear.")
    return d["esp"], xb, root


def mapper_device() -> str:
    """The partition behind /dev/mapper/cryptroot ("" when it isn't open or can't be read)."""
    r = subprocess.run(["cryptsetup", "status", MAPPER], capture_output=True, text=True)
    m = re.search(r"^\s*device:\s*(\S+)", r.stdout, re.M)
    return os.path.realpath(m.group(1)) if r.returncode == 0 and m else ""


def mapper_free() -> None:
    """Before any drive is changed: no encrypted volume may already be open under the name this install uses. One
    left open (another drive, unlocked by hand or by an earlier try) would be reused by the TPM step, and the file
    system would then be made on THAT drive."""
    if Path(f"/dev/mapper/{MAPPER}").exists():
        fail(f"An encrypted drive is already unlocked on this computer under the name {MAPPER}, so nothing was "
             "changed. Restart the computer, then try again.")


def check_mapper(dev: str) -> None:
    if mapper_device() != os.path.realpath(dev):
        fail("The unlocked drive isn't the new Starchaser partition, so nothing was written to it. Restart the "
             "computer, then try again.")


def passphrase_recovery(dev: str, passphrase: str, runtime=Path("/run")) -> None:
    """A separate recovery key also covers installs that use a startup passphrase."""
    with tempfile.TemporaryDirectory(prefix="starchaser-recovery-", dir=runtime) as folder:
        keyfile = Path(folder) / "key"
        fd = os.open(keyfile, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, "w") as stream:
            stream.write(passphrase)
        key = drive_unlock.enroll_recovery(dev, keyfile)
    emit(event="recovery-key", key=key)


def encrypt(dev: str, how: str, passphrase: str, pin: str = "", runtime=Path("/run")) -> str:
    if how == "none":
        return dev
    emit(event="phase", phase="encrypt", label="Encrypting")
    mapper_free()
    if how == "passphrase":
        sh("cryptsetup", "luksFormat", "--type", "luks2", "--batch-mode", "--key-file=-", dev, input=passphrase)
        sh("cryptsetup", "open", "--key-file=-", dev, MAPPER, input=passphrase)
        STATE["opened"].append(MAPPER)
        check_mapper(dev)
        passphrase_recovery(dev, passphrase, runtime)
        return f"/dev/mapper/{MAPPER}"
    with tempfile.TemporaryDirectory(prefix="starchaser-encrypt-", dir=runtime) as folder:
        tmp = Path(folder) / "key"
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, "wb") as stream:
            stream.write(passphrase.encode() if how == "passphrase" else os.urandom(64))
        sh("cryptsetup", "luksFormat", "--type", "luks2", "--batch-mode", "--key-file", tmp, dev)
        if how != "passphrase":
            drive_unlock.enroll_tpm(dev, tmp, pin=pin if how == "tpm-pin" else "", runtime=runtime)
        try:
            key = drive_unlock.enroll_recovery(dev, tmp)
        except ValueError:
            fail("No disk key was produced; the drive was not set up.")
        log("  (disk key produced; shown on screen, not logged)")
        fd = os.open(runtime / "starchaser-recovery-key.txt", os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
        with os.fdopen(fd, "w") as stream:
            stream.write(key + "\n")
        emit(event="recovery-key", key=key)
        if how == "tpm-pin":
            # Prove chip + PIN authorization before discarding the temporary key. Credentials stay in RAM.
            drive_unlock.enrollment(["/usr/lib/systemd/systemd-cryptsetup", "attach", MAPPER, dev, "-", "tpm2-device=auto,timeout=15s,tries=1"],
                                    {"cryptsetup.tpm2-pin": pin, "cryptsetup.luks2-pin": pin}, runtime=runtime)
        elif how == "tpm":
            sh("/usr/lib/systemd/systemd-cryptsetup", "attach", MAPPER, dev, "-", "tpm2-device=auto")
        else:
            sh("cryptsetup", "open", "--key-file", tmp, dev, MAPPER)
        if Path(f"/dev/mapper/{MAPPER}").exists():
            STATE["opened"].append(MAPPER)
        if not Path(f"/dev/mapper/{MAPPER}").exists():
            fail("The new encrypted drive couldn't be opened.")
        check_mapper(dev)
        if how in ("tpm", "tpm-pin"):
            sh("systemd-cryptenroll", "--unlock-tpm2-device=auto", "--wipe-slot=0", dev)
    return f"/dev/mapper/{MAPPER}"


# Bulk stores never travel with system restore points. The same list is mounted for simple and Advanced installs.
BULK_SUBVOLUMES = tuple((name, '@data-' + name.replace('/', '-')) for name in (
    'srv', 'opt', 'usr/local', 'var/lib/starchaser/secure-boot', 'var/lib/libvirt', 'var/lib/docker', 'var/lib/containerd', 'var/lib/lxc', 'var/lib/lxd', 'var/lib/incus', 'var/lib/containers', 'var/lib/machines',
    'var/lib/postgres', 'var/lib/postgresql', 'var/lib/mysql', 'var/lib/mariadb', 'var/lib/mongodb',
    'var/lib/redis', 'var/lib/couchdb', 'var/lib/elasticsearch'))


def filesystems(root: str, esp: str, xb: str, mode: str, home: str = "") -> None:
    """home: the home drive's volume (its @home made by format_volumes): mounted at /home instead of a @home on
    the system drive."""
    emit(event="phase", phase="format", label="Making the file system")
    if mode == "erase":
        sh("mkfs.fat", "-F32", "-n", "ESP", esp)
    if xb:
        sh("mkfs.fat", "-F32", "-n", "SCBOOT", xb)
    sh("mkfs.btrfs", "-f", "-L", "starchaser", root)
    STATE["mounted"] = True                          # from here on, /mnt is this attempt's (run() checked it was free)
    sh("mount", root, MNT)
    for sv in ("@", "@home", "@log", "@pkg", "@snapshots", *(sv for _, sv in BULK_SUBVOLUMES)):
        if not (home and sv == "@home"):
            sh("btrfs", "subvolume", "create", MNT / sv)
    sh("umount", MNT)
    o = "noatime,compress=zstd:3,space_cache=v2"
    sh("mount", "-o", f"{o},subvol=@", root, MNT)
    for sub, sv in (("home", "@home"), ("var/log", "@log"), ("var/cache/pacman/pkg", "@pkg"), (".snapshots", "@snapshots"), *BULK_SUBVOLUMES):
        (MNT / sub).mkdir(parents=True, exist_ok=True)
        sh("mount", "-o", f"{o},subvol={sv}", home if home and sv == "@home" else root, MNT / sub)
    (MNT / "boot").mkdir(exist_ok=True)
    if xb:                                    # dual boot: kernels on the new XBOOTLDR, systemd-boot on the shared ESP
        sh("mount", "-o", "fmask=0077,dmask=0077", xb, MNT / "boot")
        (MNT / "efi").mkdir(exist_ok=True)
        sh("mount", "-o", "fmask=0077,dmask=0077", esp, MNT / "efi")
    else:
        sh("mount", "-o", "fmask=0077,dmask=0077", esp, MNT / "boot")


def gpu_packages() -> list:
    """Drivers for the graphics devices found. NVIDIA's own driver (the open kernel modules) only for Turing and
    newer (device id 0x1e00 and up); older NVIDIA cards stay on mesa's built-in driver, which nvidia-utils would
    switch off, leaving no working driver at all."""
    return [p for p in hardware.graphics_packages(gpus()) if p != "mesa"]


def gpu32_packages():
    """The desktop's extra graphics packages for 32-bit games also need resolution before erasing anything."""
    packages = []
    drivers = set(gpu_packages())
    for vendor, _device in gpus():
        if vendor == "1002":
            packages += ["lib32-mesa", "lib32-vulkan-radeon"]
        elif vendor == "8086":
            packages += ["lib32-mesa", "lib32-vulkan-intel"]
        elif vendor == "10de" and "nvidia-utils" in drivers:
            packages.append("lib32-nvidia-utils")
    return list(dict.fromkeys(packages))


HARDWARE_REPORT = []


def hardware_setup():
    """A support check must never turn a bootable installation into a failed attempt."""
    global HARDWARE_REPORT
    try:
        rows = hardware.detect(cards=gpus())
        emit(event="step", text="Checking hardware support in the installed system")
        hardware.enable_services([r for r in rows if not r.get("testingOnly")], root=MNT, live=False)
        hardware.apply_quirks(rows, root=MNT, live=False)
        HARDWARE_REPORT = hardware.status(root=MNT, rows=rows, live=False)
        folder = MNT / "var/lib/starchaser"
        folder.mkdir(parents=True, exist_ok=True)
        (folder / "hardware.json").write_text(json.dumps(HARDWARE_REPORT, indent=2) + "\n")
        emit(event="step", text="Hardware support checked")
        if not any(row["needsFix"] for row in HARDWARE_REPORT):
            return ""
    except Exception as error:
        log(f"hardware check: {type(error).__name__}: {error}")
    return "Some hardware support could not be checked or set up. Open Settings > Hardware and choose Fix."


def supports_kernel_v3() -> bool:
    """The same processor check the installed system's kernel hook makes."""
    return kernels.supports_v3()


def kernel_packages(available: set, v3: bool, nvidia: bool) -> list:
    """Use complete kernel/driver pairs from the signed repo. Old rehearsal ISOs have no native kernels yet."""
    if "linux-starchaser-lts" not in available:
        return []
    targets = ["linux-starchaser-lts"]
    if nvidia:
        if "linux-starchaser-lts-nvidia-open" not in available:
            fail("The package repo is missing the LTS kernel's graphics driver. Use a complete release.")
        targets.append("linux-starchaser-lts-nvidia-open")
    for name in (["linux-starchaser-v3", "linux-starchaser"] if v3 else ["linux-starchaser"]):
        if name in available and (not nvidia or name + "-nvidia-open" in available):
            targets += [name] + ([name + "-nvidia-open"] if nvidia else [])
            break
    return targets


# Arch's kernel, only for a package source with no Starchaser kernels: a rehearsal repo, or a checkout install.
STOCK_KERNEL = "linux"
FALLBACK_TITLE = "Starchaser Linux (if the normal start fails)"


def kernel_targets(available: set, v3: bool, nvidia: bool) -> list:
    """The kernels the installed system gets: Starchaser's only. Arch's kernel never goes beside them (it showed
    Arch's name at startup and filled the boot partition); it stands in only where there is no Starchaser kernel."""
    return kernel_packages(available, v3, nvidia) or [STOCK_KERNEL]


def default_kernel(targets: list) -> str:
    """The kernel the normal boot entry starts: the main Starchaser kernel, else the long-term one, else Arch's."""
    return next((name for name in (*kernels.NATIVE, kernels.LTS) if name in targets), STOCK_KERNEL)


def fallback_preset(text: str, name: str) -> str:
    """mkinitcpio's preset makes only the default image: the boot menu's fallback entry ("if the normal start
    fails", in plain words: the same kernel with every driver in its start-up image) needs the fallback one too."""
    text = re.sub(r"(?m)^PRESETS=.*$", "PRESETS=('default' 'fallback')", text)
    if not re.search(r"(?m)^fallback_image=", text):
        text += f'\nfallback_image="/boot/initramfs-{name}-fallback.img"\n'
    if not re.search(r"(?m)^fallback_options=", text):
        text += 'fallback_options="-S autodetect"\n'
    return text


def startup_entries(name: str, options: str, safe: bool) -> dict:
    """The boot entries for the kernel package `name`, as {entry: text}. kernels.py keeps them current afterwards
    (it reads its own title and the fallback's from these same files); these are the first ones, and the only ones
    for Arch's kernel, which kernels.py leaves as the installer wrote them."""
    kernel = f"/vmlinuz-{name}"
    entries = {"starchaser": f"title   Starchaser Linux\nlinux   {kernel}\ninitrd  /initramfs-{name}.img\noptions {options}\n"}
    if (MNT / f"boot/initramfs-{name}-fallback.img").is_file():
        entries["starchaser-fallback"] = (f"title   {FALLBACK_TITLE}\nlinux   {kernel}\n"
                                          f"initrd  /initramfs-{name}-fallback.img\noptions {options}\n")
    else:
        log(f"no initramfs-{name}-fallback.img: the boot menu has no {FALLBACK_TITLE} entry")   # can't start: left out
    if safe:
        entries[safegfx.ENTRY] = (f"title   {safegfx.TITLE}\nlinux   {kernel}\ninitrd  /initramfs-{name}.img\n"
                                  f"options {safegfx.safe_options(options)}\n")
    return entries


def install_kernel_packages(config: str | None = None) -> None:
    """The system's kernels, their startup images and the boot entries. The base system has no kernel until here:
    Starchaser's come from its own package repo, which the new system only now trusts."""
    args = ["pacman"] + (["--config", config] if config else [])
    available = set(sh("arch-chroot", MNT, *args, "-Slq").stdout.split())
    targets = kernel_targets(available, supports_kernel_v3(), "nvidia-open" in gpu_packages())
    if targets == [STOCK_KERNEL]:
        log("startup: this package source has no Starchaser kernels (a rehearsal repo or a checkout); using the stock kernel")
    sh("arch-chroot", MNT, *args, "-S", "--needed", "--noconfirm", *targets)
    name = default_kernel(targets)
    preset = MNT / f"etc/mkinitcpio.d/{name}.preset"
    if preset.is_file():
        preset.write_text(fallback_preset(preset.read_text(), name))
    chroot("mkinitcpio -P")
    missing = [f for f in (f"vmlinuz-{name}", f"initramfs-{name}.img") if not (MNT / "boot" / f).is_file()]
    if missing:
        fail("The new system's startup files could not be made (" + ", ".join(missing) + " is missing).")
    options = (MNT / "etc/kernel/cmdline").read_text().strip()
    ent = MNT / "boot/loader/entries"
    ent.mkdir(parents=True, exist_ok=True)
    # NVIDIA's driver can freeze a computer as it loads, before any desktop could fall back by itself: such a
    # computer always keeps a boot menu entry without it (kernels.py keeps it there across kernel updates)
    safe = live_safegfx() or (MNT / NVIDIA_INITRAMFS).is_file()
    for entry, text in startup_entries(name, options, safe).items():
        (ent / f"{entry}.conf").write_text(text)
    if (MNT / "usr/local/lib/starchaser/kernels.py").is_file():      # a checkout install has it only after setup
        chroot("python3 /usr/local/lib/starchaser/kernels.py post")


def rank_mirrors(lookup: bool = True) -> None:
    """The live ISO lists every Arch mirror, alphabetically, and pacman takes the first that answers: often slow.
    Time a small download (core.db) from each HTTPS mirror in this computer's country (all at once) and put the
    fastest first; pacstrap copies the list into the new system, so its updates come from them too. Done here,
    not with reflector: reflector needs archlinux.org's mirror status, and archlinux.org is sometimes down when
    the mirrors are fine. On any failure the full list stays: slower, never broken."""
    import urllib.request
    from concurrent.futures import ThreadPoolExecutor
    emit(event="phase", phase="mirrors", label="Finding fast download servers")
    ml = Path("/etc/pacman.d/mirrorlist")
    full = Path(str(ml) + ".all")
    if not full.exists():
        shutil.copy2(ml, full)
    country = ""
    # over https only (the old lookup was plain http, which anyone on the network could read or change). ipinfo.io
    # answers with the two-letter code, named from the time zone data's own country list (iso3166.tab) plus the few
    # names the mirror list's "## <country>" headings spell differently; ipapi.co (the name itself) is the second try
    # because it rate-limits often (429)
    names = {"GB": "United Kingdom", "KR": "South Korea", "CZ": "Czechia"}
    try:
        for line in Path("/usr/share/zoneinfo/iso3166.tab").read_text().splitlines():
            if not line.startswith("#") and "\t" in line:
                code, name = line.split("\t", 1)
                names.setdefault(code.strip(), name.strip())
    except OSError:
        pass
    ua = {"User-Agent": "starchaser-install/1"}
    # "Don't look it up" (answers: no_lookup): no country is asked for; only the worldwide servers are timed
    for url in (("https://ipinfo.io/country", "https://ipapi.co/country_name/") if lookup else ()):
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=ua), timeout=4) as r:
                ans = r.read(100).decode("utf-8", "replace").strip()
        except Exception:
            continue
        country = names.get(ans.upper(), "") if re.fullmatch(r"[A-Za-z]{2}", ans) else ans
        if country:
            break
    servers, section = [], ""
    for line in full.read_text().splitlines():
        if line.startswith("## "):
            section = line[3:].strip()
        m = re.match(r"#?\s*Server\s*=\s*(https://\S+)", line)
        if m and section in (country, "Worldwide"):
            servers.append(m.group(1))
    if not servers:
        log(f"mirrors: none listed for {country!r}; keeping the full list")
        return

    def speed(url: str) -> float:
        test = url.replace("$repo", "core").replace("$arch", "x86_64") + "/core.db"
        try:
            t = time.monotonic()
            with urllib.request.urlopen(urllib.request.Request(test, headers=ua), timeout=5) as r:
                n = len(r.read())
            return n / max(time.monotonic() - t, 0.001) if n > 10000 else 0
        except Exception:
            return 0

    with ThreadPoolExecutor(max_workers=32) as ex:
        rates = list(ex.map(speed, servers))
    best = [u for r, u in sorted(zip(rates, servers), reverse=True) if r > 0][:8]
    if not best:
        log("mirrors: none answered; keeping the full list")
        return
    # a temp file renamed over the list: an install stopped mid-write leaves the old list, not a cut-off one
    tmp = ml.with_name(f".{ml.name}.{os.getpid()}.tmp")
    with open(tmp, "w") as fh:
        fh.write(f"# Starchaser Linux installer: the fastest of {len(servers)} mirrors ({country or 'worldwide'}), "
                 f"timed {time.strftime('%Y-%m-%d')}\n" + "".join(f"Server = {u}\n" for u in best))
        fh.flush()
        os.fsync(fh.fileno())
    os.replace(tmp, ml)
    log("mirrors ranked: " + ", ".join(f"{u.split('/')[2]} {r / 1e6:.1f} MB/s" for r, u in sorted(zip(rates, servers), reverse=True)[:8]))


def mb(n: int) -> str:
    return f"{n / 1e9:.1f} GB" if n >= 1e9 else f"{n / 1e6:.0f} MB"


def desktop_packages(repo: Path) -> list:
    """The packages starchaser-desktop-setup.sh installs from Arch's repos (its PKGS list, and the few it adds on
    its own), read from the script itself so the two can't drift apart."""
    script = repo / "installer/starchaser-desktop-setup.sh"
    r = subprocess.run(["bash", "-c", 'eval "$(sed -n "/^PKGS=(/,/^)/p" "$1")"; printf "%s\\n" "${PKGS[@]}"', "_", str(script)],
                       capture_output=True, text=True)
    return r.stdout.split() + ["moonlight-qt", "snapper", "snap-pac", "greetd", "mpv-mpris"] if r.returncode == 0 else []


def installer_repo_conf(text, choice=None, server=None):
    """Use the selected install source instead of a live image's old file:// server or Include.

    Settings keeps custom mirrors when switching channels; a fresh installation must check and install from
    the server it selected. With no package channel, keep only the other repos for the carried checkout.
    """
    text = re.sub(r"(?ms)^[ \t]*\[starchaser(?:-testing)?\][ \t]*(?:#[^\n]*)?\n.*?(?=^[ \t]*\[|\Z)", "", text)
    return pkgrepo.select_channel(text, choice, server) if choice else text


@contextlib.contextmanager
def live_package_source():
    """Keep installation sources active for this attempt, then restore the live system for a fresh retry."""
    config = PACMAN_CONFIG
    original = config.read_bytes() if config.is_file() else None
    mode = config.stat().st_mode & 0o777 if original is not None else 0o644
    try:
        yield
    finally:
        if original is not None and (not config.is_file() or config.read_bytes() != original):
            fd, name = tempfile.mkstemp(prefix="pacman.conf.starchaser-", dir=config.parent)
            try:
                with os.fdopen(fd, "wb") as out:
                    os.fchmod(out.fileno(), mode)
                    out.write(original)
                    out.flush()
                    os.fsync(out.fileno())
                os.replace(name, config)
            finally:
                Path(name).unlink(missing_ok=True)


def install_targets(a, repo, extra, available) -> list:
    """Every package this computer's installation takes: the system, its hardware's drivers and firmware, the desktop
    and Starchaser's own packages. The full image resolves it against the stick, the online image downloads it."""
    return list(dict.fromkeys(BASE + [f"{cpu_vendor()}-ucode", "mesa"] + gpu_packages()
        + hardware.packages(hardware.detect(cards=gpus()), channel=a.get("channel", "release"))
        + gpu32_packages() + list(extra) + desktop_packages(repo)
        + list(pkgrepo.PACKAGES) + (["sunshine"] if a.get("remote_desktop") else [])
        + kernel_targets(available, supports_kernel_v3(), "nvidia-open" in gpu_packages())))


# ----------------------------------------------------------------------------------- the online image's download
# The online image carries no packages. Before any drive change it downloads this computer's whole transaction (the
# same packages the full image would take from the stick) into RAM, with pacman checking every signature, indexes it
# as the [complete] repo and then installs from it exactly as the full image does. A dropped connection waits and
# resumes; nothing on a drive changes until everything is in and checked.
ONLINE_WORK = Path("/run/starchaser-online-work")     # the scratch pacman config and package database (RAM)
ONLINE_TRIES = 4
ONLINE_WAIT = 120                                     # seconds to wait for a dropped connection before each retry
ONLINE_HEADROOM = GIB                                 # RAM left for the live system while the download sits in RAM
NO_INTERNET = ("This installer downloads Starchaser while it installs, and the internet can't be reached. Nothing on "
               "your drive was changed. Go back to Network and connect, then try again.")


def edition_download_text() -> str:
    """The typical download the image was built with ("3.1 GB"), for the Welcome; "" when it isn't known."""
    size = installer_media.edition()["typical_download"]
    return mb(size) if size and online_edition() else ""


def online_edition() -> bool:
    """The online image (and not a stick that carries the complete package set after all)."""
    return installer_media.edition()["edition"] == "online" and not installer_media.MEDIA.is_dir()


def online_conf(a) -> str:
    """The live system's repos with the selected Starchaser channel and multilib: what the download resolves against."""
    text = installer_repo_conf(PACMAN_CONFIG.read_text(), a.get("channel", "release"), a.get("repo_url"))
    text = re.sub(r"(?m)^#\[multilib\]\n#Include", "[multilib]\nInclude", text)
    if "[multilib]" not in text:
        text += "\n[multilib]\nInclude = /etc/pacman.d/mirrorlist\n"
    return text


def online_transaction(a, repo, extra) -> list:
    """-> [(file name, download size)] for this computer's whole installation, resolved against the online repos
    with an empty scratch database (so nothing the live system has is left out). Raises Stop when it can't be."""
    ONLINE_WORK.mkdir(parents=True, exist_ok=True)
    os.chmod(ONLINE_WORK, 0o755)                     # pacman 7 downloads as its own user (DownloadUser)
    conf = ONLINE_WORK / "pacman.conf"
    conf.write_text(online_conf(a))
    db = ONLINE_WORK / "db"
    (db / "local").mkdir(parents=True, exist_ok=True)
    # an empty cache: --print-format %s is the DOWNLOAD size, 0 for anything already in pacman's cache, and the sizes
    # here must be the whole transaction's (what is already in ONLINE_MEDIA is counted separately)
    cache = ONLINE_WORK / "size-cache"
    shutil.rmtree(cache, ignore_errors=True)
    cache.mkdir()
    opts = ["--config", conf, "--dbpath", db, "--cachedir", cache]
    if sh("pacman", *opts, "-Sy", check=False).returncode:
        fail(NO_INTERNET)
    available = set(sh("pacman", *opts, "-Slq").stdout.split())
    targets = install_targets(a, repo, extra, available)
    r = sh("pacman", *opts, "-Sp", "--print-format", "%f %s", *targets, check=False)
    rows = [l.split() for l in r.stdout.splitlines()]
    rows = [(f, int(s)) for f, s in (x for x in rows if len(x) == 2) if s.isdigit() and ".pkg.tar." in f]
    if r.returncode or not rows:
        fail("The list of software to download couldn't be worked out, so nothing was changed. Try again in a few "
             "minutes; the download server may be updating.")
    return rows


def online_download_step(a, extra) -> tuple:
    """-> (the Summary's line with this computer's download size, "") or ("", why it can't be worked out)."""
    try:
        size = sum(s for _, s in online_transaction(a, Path(a.get("repo") or "/usr/share/starchaser/repo"), extra))
    except Stop as error:
        return "", str(error)
    return (f"Download Starchaser from the internet first: about {mb(size)} for this computer. Every package's "
            "signature is checked, and the drive changes only after the whole download has passed. Keep this "
            "computer connected until the download finishes"), ""


def memory_available() -> int:
    try:
        for line in Path("/proc/meminfo").read_text().splitlines():
            if line.startswith("MemAvailable:"):
                return int(line.split()[1]) * 1024
    except (OSError, ValueError, IndexError):
        pass
    return 0


def online_room(need: int, available: int) -> str:
    """"" when the download fits in this computer's memory with room to spare; else what to do, in plain words."""
    if need + ONLINE_HEADROOM <= available:
        return ""
    return (f"This computer doesn't have enough free memory to hold the download (about {mb(need)}) before it changes "
            f"the drive; it has {mb(available)} free. Nothing was changed. Use the Full installer stick, which needs no "
            "download, or close the other apps you opened while trying Starchaser.")


def fetch_online_media(a, repo, extra, config=None) -> Path:
    """Download and check the whole transaction into ONLINE_MEDIA; -> that folder, a complete [complete] repo."""
    if not pkgrepo.repo_reachable(pkgrepo.channel_name(a.get("channel", "release")), a.get("repo_url")):
        fail(NO_INTERNET)
    # The live system trusts the Starchaser certificate it carries (checked when the image was built).
    if Path("/usr/share/pacman/keyrings/starchaser.gpg").is_file():
        sh("pacman-key", "--populate", "starchaser", check=False)
    rank_mirrors(lookup=not a.get("no_lookup"))
    rows = online_transaction(a, repo, extra)
    folder = installer_media.ONLINE_MEDIA
    total = sum(s for _, s in rows)
    have = sum((folder / f).stat().st_size for f, _ in rows if (folder / f).is_file())
    room = online_room(total - have, memory_available())
    if room:
        fail(room)
    folder.mkdir(parents=True, exist_ok=True)
    os.chmod(folder, 0o755)
    if subprocess.run(["mountpoint", "-q", str(folder)]).returncode:
        sh("mount", "-t", "tmpfs", "-o", f"size={total + ONLINE_HEADROOM},mode=0755", "tmpfs", folder)
    else:                                            # a retry: the earlier download is kept, the size follows the list
        sh("mount", "-o", f"remount,size={total + ONLINE_HEADROOM}", folder, check=False)
    emit(event="phase", phase="fetch", label="Downloading Starchaser before changing the drive")
    opts = ["--config", str(ONLINE_WORK / "pacman.conf"), "--dbpath", str(ONLINE_WORK / "db"), "--cachedir", str(folder)]
    names = [f for f, _ in rows]
    targets = [f.rsplit("-", 3)[0] for f in names]
    stop = threading.Event()
    # While the connection is down, every progress line carries the waiting message: the screen shows the latest
    # line's item, so a one-off "step" would be replaced within a second (seen on the first online install test).
    waiting = {"text": ""}

    def watch() -> None:
        while not stop.wait(1):
            got = 0
            for f in list(folder.rglob("*.pkg.tar.*")):
                try:
                    if f.is_file() and not f.name.endswith(".sig"):
                        got += f.stat().st_size
                except OSError:
                    pass
            item = f"{mb(min(got, total))} of {mb(total)} downloaded"
            emit(event="progress", phase="fetch", done=min(got, total), total=total,
                 item=f"{waiting['text']}. {item}" if waiting["text"] else item)

    t = threading.Thread(target=watch, daemon=True)
    t.start()
    try:
        for attempt in range(1, ONLINE_TRIES + 1):
            # pacman checks each package's signature as it arrives and keeps what is complete, so a retry resumes
            if stream(["pacman", "-Sw", "--noconfirm", *opts, *targets], "fetch") == 0:
                break
            if attempt == ONLINE_TRIES:
                break
            waiting["text"] = ("The connection dropped. Waiting for it to come back, then the download continues "
                               f"where it stopped (try {attempt + 1} of {ONLINE_TRIES})")
            emit(event="step", phase="fetch", text=waiting["text"])
            deadline = time.monotonic() + ONLINE_WAIT
            while not pkgrepo.repo_reachable(pkgrepo.channel_name(a.get("channel", "release")), a.get("repo_url")):
                if time.monotonic() > deadline:
                    fail("The internet connection dropped while Starchaser was downloading and didn't come back. "
                         "Nothing on your drive was changed, and what already downloaded is kept. Reconnect on the "
                         "Network step, then press Try again to finish the download.")
                time.sleep(5)
            waiting["text"] = ""
    finally:
        stop.set()
        t.join()
    missing = [f for f in names if not (folder / f).is_file()]
    if missing:
        log("online download: missing after every try: " + ", ".join(missing[:20]))
        fail("Some of the software couldn't be downloaded or didn't pass its signature check, so nothing on your "
             "drive was changed. Press Try again; if it happens again, wait a few minutes (the download server may "
             "be updating).")
    # Only this transaction goes into the index: an older version left from an earlier try is dropped.
    keep = set(names) | {f + ".sig" for f in names}
    for f in folder.iterdir():
        if f.is_file() and ".pkg.tar." in f.name and f.name not in keep:
            f.unlink()
    emit(event="step", phase="fetch", text="Checking every downloaded package")
    # the lists this download was resolved against: the new system starts with them (leave_package_lists)
    installer_media.keep_lists(ONLINE_WORK / "db/sync", folder)
    installer_media.assemble(folder)
    return folder


def live_progress(phase: str):
    """The progress callback for reading the live image (live_packages.check and rebuild call it for every file,
    about 190,000 on the full image): the screen and the log get the first, then two a second, and the last."""
    shown = [-1.0]

    def progress(done: int, total: int) -> None:
        now = time.monotonic()
        if done < total and now - shown[0] < 0.5:
            return
        shown[0] = now
        emit(event="progress", phase=phase, done=done, total=total, item=f"{mb(done)} of {mb(total)}")
    return progress


def media_live_files(media: Path, opts: list, targets: list) -> dict:
    """The full image keeps the packages its live system already has only in that system (P2-10, live_packages.py):
    -> {"files": the plain .pkg.tar files this install writes out of the live system, "fetch": the pacman -Sw
    arguments that check every package the stick does carry}. Every live one is checked against the live image here,
    before any drive changes, down to each file's contents (decision #56: a damaged stick must stop with nothing
    changed); raises if one isn't there as the stick was built."""
    if not live_packages.has_live(media):
        sh("pacman", "-Sp", *opts, *targets)
        return {"files": [], "fetch": list(targets)}
    rows = [line.split() for line in sh("pacman", "-Sp", *opts, "--print-format", "%r %n %f", *targets).stdout.splitlines()]
    rows = [r for r in rows if len(r) == 3]
    files = [f for repo, _, f in rows if repo == live_packages.REPO]
    live_packages.check(media, files, progress=live_progress("prepare"))
    # only the stick's own packages are fetched (-dd: no dependency pull-in; every one is already on the list)
    carried = [f"{repo}/{name}" for repo, name, _ in rows if repo != live_packages.REPO]
    return {"files": files, "fetch": ["-dd", *carried] if carried else []}


def preflight_packages(a, repo, extra, config=None):
    """Resolve every transaction against an empty scratch database before any drive is changed."""
    config = config or PACMAN_CONFIG
    emit(event="phase", phase="prepare", label="Checking all software before changing the drive")
    media = Path(a.get("media_dir") or installer_media.MEDIA)
    fetched = "media_dir" not in a and not media.exists() and online_edition()
    if fetched:
        # The online image: download this computer's whole transaction first, into RAM, then install from it
        # exactly as the full image installs from the stick. fetch_online_media() stops (nothing changed) otherwise.
        media = fetch_online_media(a, repo, extra, config)
    if "media_dir" in a or media.exists():
        try:
            installer_media.verify(media)
            with tempfile.TemporaryDirectory(prefix="starchaser-media-check-") as tmp:
                work = Path(tmp)
                conf = work / "pacman.conf"
                conf.write_text(installer_media.config(media.resolve(), live=live_packages.has_live(media)))
                db = work / "db"
                (db / "local").mkdir(parents=True)
                opts = ["--config", conf, "--dbpath", db, "--cachedir", media.resolve()]
                sh("pacman", *opts, "-Sy")
                available = set(sh("pacman", *opts, "-Slq").stdout.split())
                targets = install_targets(a, repo, extra, available)
                live = media_live_files(media, opts, targets)
                # Checks package signatures and payload availability before the first drive write.
                if live["fetch"]:
                    sh("pacman", "-Sw", *opts, "--noconfirm", *live["fetch"])
            a["_updates_conf"] = installer_repo_conf(config.read_text(), a.get("channel", "release"), a.get("repo_url"))
            a["_live_files"] = live["files"]
            config.write_text(installer_media.config(media.resolve(), live=live_packages.has_live(media)))
            a["_complete_media"] = str(media)
            a["_desktop_source"] = "package"
            a["_package_online"] = False
            return
        except Exception as error:
            log(f"complete media preflight: {error}")
            if fetched:
                fail("The downloaded software didn't pass its check, so nothing on your drive was changed. "
                     "Press Try again to download it again.")
            fail("This installer is incomplete or damaged; nothing was changed. Make a new installer stick.")
    source = pkgrepo.desktop_source(a)
    offline = Path(a.get("pkgrepo_dir") or pkgrepo.OFFLINE_REPO)
    channel = pkgrepo.channel_name(a.get("channel", "release"))
    online_repo = source == "package" and pkgrepo.repo_reachable(channel, a.get("repo_url"))
    if source == "package" and not online_repo and pkgrepo.tries_online(a):
        source = "checkout"
        log("software preflight: the online Starchaser repo can't be reached; using the checkout on this installer")
    try:
        with tempfile.TemporaryDirectory(prefix="starchaser-preflight-") as tmp:
            work = Path(tmp)
            os.chmod(work, 0o755)
            text = installer_repo_conf(config.read_text())
            # The desktop needs multilib too; do not silently drop packages absent from the live ISO's repos.
            text = re.sub(r"(?m)^#\[multilib\]\n#Include", "[multilib]\nInclude", text)
            if "[multilib]" not in text:
                text += "\n[multilib]\nInclude = /etc/pacman.d/mirrorlist\n"
            live_text = text
            if source == "package":
                if not online_repo and not offline.is_dir():
                    fail("This installer is out of date; nothing was changed.")
                keyring = pkgrepo.find_keyring(offline) if offline.is_dir() else pkgrepo.fetch_keyring(work, channel, a.get("repo_url"))
                # The release stick's keyring was checked at build time; online bootstrap is verified before -U.
                boot = work / "bootstrap.conf"
                boot.write_text(pkgrepo.bootstrap_conf(local=True))
                sh("pacman", "--config", boot, "-U", "--noconfirm", keyring)
                sh("pacman-key", "--populate", "starchaser")
                text = installer_repo_conf(text, a.get("channel", "release"), a.get("repo_url"))
                live_text = text
                if not online_repo:
                    text = installer_repo_conf(text)
                    local = work / "repo"
                    shutil.copytree(offline, local)
                    db = local / (channel + ".db")
                    if not db.exists():
                        db = local / "starchaser.db"
                    shutil.copy2(db, local / "starchaser-offline.db")
                    # Later downloads use the live config, after this scratch copy has been removed. The stick
                    # keeps its original database name; never leave a temporary file:// source in that config.
                    live_block = (f"[{db.stem}]\nSigLevel = Required DatabaseOptional\n"
                                  f"Server = file://{offline.resolve()}\n\n")
                    live_text = text.replace("[core]", live_block + "[core]", 1) if "[core]" in text else text + "\n" + live_block
                    block = f"[starchaser-offline]\nSigLevel = Required DatabaseOptional\nServer = file://{local}\n\n"
                    text = text.replace("[core]", block + "[core]", 1) if "[core]" in text else text + "\n" + block
            conf = work / "pacman.conf"
            conf.write_text(text)
            db = work / "db"
            (db / "local").mkdir(parents=True)
            opts = ["--config", conf, "--dbpath", db]
            if sh("pacman", *opts, "-Sy", check=False).returncode:
                fail("This installer is out of date; nothing was changed.")
            available = set(sh("pacman", *opts, "-Slq").stdout.split())
            desktop_pkgs = desktop_packages(repo)
            if not desktop_pkgs:
                fail("This installer is out of date; nothing was changed.")
            targets = list(dict.fromkeys(BASE + [f"{cpu_vendor()}-ucode", "mesa"] + gpu_packages()
                                        + hardware.packages(hardware.detect(cards=gpus()), channel=a.get("channel", "release"))
                                        + gpu32_packages() + extra + desktop_pkgs
                                        + (list(pkgrepo.PACKAGES) if source == "package" else [])
                                        + kernel_targets(available, supports_kernel_v3(), "nvidia-open" in gpu_packages())))
            result = sh("pacman", "-Sp", *opts, "--print-format", "%n %v", *targets, check=False)
            if result.returncode:
                fail("This installer is out of date; nothing was changed.")
            # download() and pacstrap read the live system's config. Switch it only after the entire check passes,
            # before any drive write, so neither can silently return to the old stick's package versions.
            fd, name = tempfile.mkstemp(prefix="pacman.conf.starchaser-", dir=config.parent)
            try:
                with os.fdopen(fd, "w") as out:
                    os.fchmod(out.fileno(), config.stat().st_mode & 0o777)
                    out.write(live_text)
                    out.flush()
                    os.fsync(out.fileno())
                os.replace(name, config)
            finally:
                Path(name).unlink(missing_ok=True)
            # Keep the selected source for the later transaction, so an online install never prefers the old stick.
            a["_package_online"] = online_repo
            a["_desktop_source"] = source
    except Stop as error:
        log(f"software preflight: {error}")
        fail("This installer is out of date; nothing was changed.")
    except Exception as error:
        log(f"software preflight: {type(error).__name__}: {error}")
        fail("This installer is out of date; nothing was changed.")


def download(pk: list, repo: Path | None = None, live: list | None = None) -> None:
    """Download every package into the new system's package cache first (pacstrap then installs from it): pacman
    prints nothing while it downloads without a terminal, so progress is the bytes arriving against the total.
    From the full image: copy the stick's packages, and write LIVE (the preflight's list) out of the live system."""
    emit(event="phase", phase="download", label="Downloading Starchaser")
    live_conf = PACMAN_CONFIG.read_text()
    if "[complete]" in live_conf:
        folder = Path(next(l.split("file://", 1)[1] for l in live_conf.splitlines() if l.startswith("Server = file://")))
        cache = MNT / "var/cache/pacman/pkg"
        shutil.copytree(folder, cache, dirs_exist_ok=True)
        if live:
            try:
                live_packages.rebuild(folder, live, cache, progress=live_progress("download"))
            except (OSError, ValueError, KeyError) as error:
                # every file passed the check before the drive changed (media_live_files), so this is a stick that
                # stopped reading partway; the person must know the drive isn't as it was
                log(f"live packages: {type(error).__name__}: {error}")
                fail("Some of the software on this stick couldn't be read while it was copied, so Starchaser isn't "
                     "installed, and the drive you chose was already changed. Make a new installer stick and try "
                     "again.")
        return
    sh("pacman", "-Sy", "--needed", "--noconfirm", "archlinux-keyring")
    cache = MNT / "var/cache/pacman/pkg"
    cache.mkdir(parents=True, exist_ok=True)
    # an empty package database of its own: against the live system's, everything it already has (most of the
    # base) would be skipped here and downloaded silently by pacstrap after all
    db = Path("/tmp/starchaser-dl-db")
    shutil.rmtree(db, ignore_errors=True)
    (db / "local").mkdir(parents=True)
    shutil.copytree("/var/lib/pacman/sync", db / "sync")
    opts = ["--dbpath", str(db), "--cachedir", str(cache)]
    # the desktop setup's packages too (it installs from this same cache), so every download shows here; ones the
    # live system's repos don't have (the 32-bit multilib ones) it downloads itself, later
    have = set(subprocess.run(["pacman", "--dbpath", str(db), "-Slq"], capture_output=True, text=True).stdout.split())
    pk = list(dict.fromkeys(pk + ([p for p in desktop_packages(repo) if p in have] if repo else [])))
    out = subprocess.run(["pacman", "-Sp", *opts, "--print-format", "%n %s", *pk], capture_output=True, text=True).stdout
    total = sum(int(l.split()[1]) for l in out.splitlines() if len(l.split()) == 2 and l.split()[1].isdigit())
    stop = threading.Event()

    def watch() -> None:
        while not stop.wait(1):
            got = 0
            # pacman 7 downloads into a download-XXXXXX folder inside the cache and moves the files up when done
            for f in list(cache.rglob("*")):
                try:
                    if f.is_file() and not f.name.endswith(".sig"):
                        got += f.stat().st_size
                except OSError:                   # moved or renamed as we looked
                    pass
            if total:
                emit(event="progress", phase="download", done=min(got, total), total=total, item=f"{mb(min(got, total))} of {mb(total)}")

    t = threading.Thread(target=watch, daemon=True)
    t.start()
    rc = stream(["pacman", "-Sw", "--noconfirm", *opts, *pk], "download")
    stop.set()
    t.join()
    if rc != 0:
        fail("Downloading Starchaser failed (the details are below). Check the internet connection and try again.")


def pacstrap(cpu: str, repo: Path | None = None, extra: list | None = None, *, channel="release", lookup: bool = True, live=None) -> None:
    complete = installer_media.MEDIA.exists() or (Path("/etc/pacman.conf").is_file() and "[complete]" in Path("/etc/pacman.conf").read_text())
    if not complete:
        rank_mirrors(lookup=lookup)
    pk = list(dict.fromkeys(BASE + [f"{cpu}-ucode", "mesa"] + gpu_packages() +
                            hardware.packages(hardware.detect(cards=gpus()), channel=channel) + list(extra or [])))
    download(pk, repo if repo and (repo / "installer/starchaser-desktop-setup.sh").is_file() else None, live)
    emit(event="phase", phase="base", label="Installing the base system")
    total = len(subprocess.run(["pacman", "-Sp", "--print-format", "%n", *pk], capture_output=True, text=True).stdout.split())
    if stream(["pacstrap", "-K", str(MNT), *pk], "base", total) != 0:
        fail("Installing the base system failed (the details are below). Check the internet connection and try again.")
    sh("sh", "-c", f"genfstab -U {MNT} >> {MNT}/etc/fstab")


def chroot(script: str, check=True, input=None) -> subprocess.CompletedProcess:
    return sh("arch-chroot", MNT, "bash", "-euo", "pipefail", "-c", script, check=check, input=input)


def as_account(user: str, command: str) -> str:
    """A chroot script that runs `command` in `user`'s login shell with a private runtime folder of its own, and
    passes on the command's exit code.

    runuser in the new system starts no login session (logind isn't running there), so XDG_RUNTIME_DIR is unset. A
    program that uses GIO then starts a session bus, which starts gvfs's daemon, and with no runtime folder that
    daemon mounts its file bridge at ~/.gvfs. Each arch-chroot ends its own process namespace when the command ends:
    that kills the daemon but leaves the mount behind, so a Home folder could not be deleted (userdel -r stopped the
    "Someone else, later" install) and every new owner found an empty ~/.gvfs. Here the bridge is off and the
    runtime folder is private; anything mounted under that folder anyway is detached before the folder goes."""
    # $d is mktemp's own name (letters and digits), safe inside the double quotes; the command keeps its own quoting
    return (f'd=$(mktemp -d /tmp/starchaser-run.XXXXXX) && chown {user}: "$d" && chmod 700 "$d"; rc=0; '
            f'runuser -l {user} -c "export XDG_RUNTIME_DIR=$d GVFS_DISABLE_FUSE=1; "{shlex.quote(command)} || rc=$?; '
            # one mount point per line, deepest first: word splitting on newlines is the point
            f'for m in $(awk -v d="$d/" \'index($5, d) == 1 {{print $5}}\' /proc/self/mountinfo | sort -r); '
            f'do umount -l "$m" || true; done; '
            f'rm -rf --one-file-system "$d" || true; exit "$rc"')


# --------------------------------------------------------------------------------------------- Wi-Fi carried over
# The networks joined on the live system (the installer's Wi-Fi step) are copied to the new system, so it is online
# at the sign-in screen after the restart. A profile as the live system saved it can be unusable there:
#   permissions=user:live       only the live user may use it, and that user doesn't exist on the new system
#   psk-flags=1 (agent-owned)   the password is kept by whoever typed it, not in the file: nothing can answer for it
#                               at the sign-in screen
#   interface-name=wlp...       bound to the live system's name for the Wi-Fi card (a USB adapter in another port,
#                               or a different name, never matches)
# Profiles NetworkManager keeps only in memory are in /run, not /etc, and are lost unless they are copied too.
# (folder, kept only in memory)
NM_LIVE_DIRS = ((Path("/etc/NetworkManager/system-connections"), False), (Path("/run/NetworkManager/system-connections"), True))
_WIFI_TYPES = ("wifi", "802-11-wireless")
_BINDABLE_TYPES = _WIFI_TYPES + ("ethernet", "802-3-ethernet")


def _keyfile_sections(text: str) -> dict:
    """{section: {key: value}} of an NM keyfile (the last value wins, as NetworkManager reads it). Like GLib, only the
    space before a value is dropped: a password may end with a space, and that space is part of it."""
    out, sec = {}, ""
    for line in text.splitlines():
        t = line.strip()
        if not t or t.startswith(("#", ";")):
            continue
        if t.startswith("[") and t.endswith("]"):
            sec = t[1:-1]
            out.setdefault(sec, {})
        elif "=" in t:
            k, v = line.lstrip().split("=", 1)
            out.setdefault(sec, {})[k.strip()] = v.lstrip()
    return out


def _keyfile_escape(v: str) -> str:
    """A value as a keyfile stores it (GLib's escapes: a backslash doubled, a leading space as \\s)."""
    v = v.replace("\\", "\\\\").replace("\t", "\\t")
    return "\\s" + v[1:] if v.startswith(" ") else v


def installed_keyfile(text: str, read_secret=None) -> tuple:
    """A live system's keyfile made usable on the installed one: (new text, notes for the install log).
    No user permissions, no binding to the live interface name (Wi-Fi and cable only: a VPN's interface name is
    its own), and the Wi-Fi password in the file itself (psk-flags=0). A password the file doesn't hold is asked of
    read_secret(uuid) (nmcli -s on the live system); without it the profile still comes along and says so, since
    NetworkManager then asks for the password again. Everything else is kept line for line."""
    cur = _keyfile_sections(text)
    kind = cur.get("connection", {}).get("type", "").strip()
    uuid = cur.get("connection", {}).get("uuid", "").strip()
    sec = cur.get("wifi-security", {})
    notes = []
    psk = sec.get("psk", "")
    if "wifi-security" in cur and sec.get("key-mgmt", "").strip() in ("wpa-psk", "sae") and not psk and read_secret:
        psk = _keyfile_escape(read_secret(uuid) or "")
        if psk:
            notes.append("its Wi-Fi password was kept outside the file; written into it")
    out, section, wrote_psk = [], "", False
    for line in text.splitlines():
        t = line.strip()
        if t.startswith("[") and t.endswith("]"):
            if section == "wifi-security" and psk and not wrote_psk:
                out.append("psk=" + psk)
                wrote_psk = True
            section = t[1:-1]
            out.append(line)
            continue
        key = t.split("=", 1)[0].strip() if "=" in t and not t.startswith(("#", ";")) else ""
        if section == "connection" and key == "permissions":
            if t.split("=", 1)[1].strip():
                notes.append("it was limited to the live system's user; now any user can use it")
            continue
        if section == "connection" and key == "interface-name" and kind in _BINDABLE_TYPES:
            notes.append("no longer tied to the live system's name for the network card")
            continue
        if section == "wifi-security" and key == "psk-flags":
            if t.split("=", 1)[1].strip() != "0":
                out.append("psk-flags=0")
            continue
        if section == "wifi-security" and key == "psk":
            if psk and not wrote_psk:
                out.append("psk=" + psk)
                wrote_psk = True
            continue
        out.append(line)
    if section == "wifi-security" and psk and not wrote_psk:
        out.append("psk=" + psk)
    if "wifi-security" in cur and sec.get("key-mgmt", "").strip() in ("wpa-psk", "sae") and not psk:
        notes.append("WARNING: no Wi-Fi password saved; the new system asks for it again")
    return "\n".join(out) + "\n", notes


def _live_secret(uuid: str) -> str:
    """The Wi-Fi password NetworkManager holds for a live profile (best-effort: "" when it can't say)."""
    if not uuid:
        return ""
    try:
        # -e no: terse output otherwise escapes ':' and '\' (a password "a:b" would come back as "a\:b"); only the
        # trailing newline is removed, since a passphrase may start or end with a space
        r = subprocess.run(["nmcli", "-s", "-e", "no", "-g", "802-11-wireless-security.psk", "connection", "show", "uuid", uuid],
                           capture_output=True, text=True, timeout=15)
    except (OSError, subprocess.TimeoutExpired):
        return ""
    return r.stdout.rstrip("\r\n") if r.returncode == 0 else ""


def carry_network_profiles(dirs=NM_LIVE_DIRS, target=None, read_secret=_live_secret) -> list:
    """Copy the live system's saved networks to the new system (see the block comment above). Returns what was
    carried as (file name, connection name, type), and logs it; never a password."""
    dst_dir = (target or MNT / "etc/NetworkManager/system-connections")
    carried, seen = [], set()
    for d, in_run in dirs:
        for f in sorted(Path(d).glob("*.nmconnection")) if Path(d).is_dir() else []:
            try:
                text = f.read_text()
            except OSError as e:
                log(f"network: couldn't read {f.name}: {e}")
                continue
            kf = _keyfile_sections(text)
            c = kf.get("connection", {})
            kind, uuid, name = c.get("type", "").strip(), c.get("uuid", "").strip(), c.get("id", f.stem).strip()
            # NetworkManager's own in-memory profiles (the automatic "Wired connection 1") are made again on the
            # new system; only Wi-Fi someone joined is worth keeping from /run
            if kf.get(".nmmeta", {}).get("nm-generated", "").strip() == "true" or (in_run and kind not in _WIFI_TYPES):
                continue
            if uuid and uuid in seen:
                continue
            seen.add(uuid)
            new, notes = installed_keyfile(text, read_secret)
            dst_dir.mkdir(parents=True, exist_ok=True)
            dst = dst_dir / f.name
            tmp = dst_dir / f".{f.name}.{os.getpid()}.tmp"
            fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
            with os.fdopen(fd, "w") as fh:
                fh.write(new)
                fh.flush()
                os.fsync(fh.fileno())
            os.replace(tmp, dst)
            os.chmod(dst, 0o600)
            carried.append((f.name, name, kind))
            log(f"network: carried {name!r} ({kind or 'unknown type'})" + ("; " + "; ".join(notes) if notes else ""))
    if not any(k in _WIFI_TYPES for _, _, k in carried):
        log("network: no Wi-Fi saved on the live system (installed over a cable?); the welcome asks for Wi-Fi on first start")
    return carried


# ------------------------------------------------------------------------------------- the network installed on
# With trust_network (and ssh), the one network this install ran on counts as a network you trust on the new system
# (decided 2026-11-05 #4), so SSH and the fleet reach it from the first start. Everyone else keeps the welcome's
# question for every network (decided 2026-10-07: ask once, never trust by itself). The firewall's first policy
# (starchaser-admin firewall-default-on, in the desktop setup) reads this file and removes it (firewall.py
# INSTALL_NETWORK).
INSTALL_NETWORK = Path("etc/starchaser/firewall-install-network.json")
NM_UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")


def install_network() -> dict:
    """The connection the live system is online through now: the one on the default route's adapter with the lowest
    metric (a cable before a Wi-Fi joined beside it). {"uuid", "name", "type", "device"}, or {} when there is none
    or it is neither a cable nor a Wi-Fi."""
    try:
        routes = json.loads(subprocess.run(["ip", "-j", "route", "show", "default"], capture_output=True, text=True,
                                           timeout=10).stdout or "[]")
        active = subprocess.run(["nmcli", "-t", "-f", "UUID,NAME,TYPE,DEVICE", "connection", "show", "--active"],
                                capture_output=True, text=True, timeout=15).stdout
    except (OSError, ValueError, subprocess.SubprocessError):
        return {}
    conns = {}
    for line in active.splitlines():
        f = terse(line)
        if len(f) >= 4 and f[2] in _BINDABLE_TYPES and NM_UUID.fullmatch(f[0]) and f[3]:
            conns.setdefault(f[3], {"uuid": f[0], "name": f[1][:80], "type": f[2], "device": f[3]})
    for r in sorted((r for r in routes if isinstance(r, dict)), key=lambda r: r.get("metric") or 0):
        if r.get("dev") in conns:
            return conns[r["dev"]]
    return {}


def wired_router(dev: str) -> dict:
    """The router a cable is plugged into, as the firewall records a cable network (firewall.py wired_identity: the
    router's hardware address and the address range), or {} when it can't be read."""
    def ip_json(*args):
        return json.loads(subprocess.run(["ip", "-j", *args], capture_output=True, text=True, timeout=10).stdout or "[]")
    try:
        gw = next((r.get("gateway") for r in ip_json("-4", "route", "show", "default", "dev", dev) if r.get("gateway")), "")
        addr = next((x for i in ip_json("-4", "addr", "show", "dev", dev) for x in i.get("addr_info") or []
                     if x.get("local")), {})
        if not gw or not addr:
            return {}
        subnet = str(ipaddress.ip_interface(f"{addr['local']}/{addr['prefixlen']}").network)
        mac = ""
        for attempt in range(2):
            mac = next((n.get("lladdr") for n in ip_json("neigh", "show", gw, "dev", dev) if n.get("lladdr")), "")
            if mac or attempt:
                break
            subprocess.run(["ping", "-c", "1", "-W", "1", gw], capture_output=True, timeout=5)   # fills the neighbor table
    except (OSError, ValueError, KeyError, subprocess.SubprocessError):
        return {}
    return {"kind": "wired", "gw": mac.lower(), "subnet": subnet} if mac else {}


def carried_uuids(target=None) -> set:
    """The connection ids of the networks carry_network_profiles() wrote into the new system."""
    d = target or MNT / "etc/NetworkManager/system-connections"
    out = set()
    for f in sorted(Path(d).glob("*.nmconnection")) if Path(d).is_dir() else []:
        try:
            out.add(_keyfile_sections(f.read_text()).get("connection", {}).get("uuid", "").strip())
        except OSError:
            continue
    return out


def trust_install_network(a: dict) -> str:
    """With trust_network (and ssh): write down the network this install runs on for the firewall's first policy.
    A Wi-Fi is its carried profile (the same connection id on the new system). A cable is also its router: the
    new system makes its automatic cable connection again with a new id, and the firewall knows it is the same
    network by the router (any other cable network stays Public until the welcome asks). -> a note for the
    finished screen when no network could be written down, else ""."""
    if not (a.get("ssh") and a.get("trust_network")):
        return ""
    net = install_network()
    rec = {"uuid": net["uuid"], "name": net["name"]} if net else {}
    why = "it wasn't connected to a network"
    if net and net["type"] in _WIFI_TYPES and net["uuid"] not in carried_uuids():
        rec, why = {}, f"{net['name']} wasn't saved for the new system"
    elif net and net["type"] not in _WIFI_TYPES:
        ident = wired_router(net["device"])
        rec = dict(rec, identity=ident) if ident else {}
        why = why if ident else f"the router of {net['name']} couldn't be read"
    if not rec:
        log(f"network: nothing marked as a network you trust (trust_network): {why}")
        return ("No network was marked as trusted (" + why + "), so the welcome asks about this network after the "
                "restart.")
    dst = MNT / INSTALL_NETWORK
    dst.parent.mkdir(parents=True, exist_ok=True)
    tmp = dst.parent / f".{dst.name}.{os.getpid()}.tmp"
    with open(tmp, "w") as fh:
        json.dump(rec, fh)
        fh.write("\n")
        fh.flush()
        os.fsync(fh.fileno())
    os.chmod(tmp, 0o644)
    os.replace(tmp, dst)
    log(f"network: {rec['name']!r} will count as a network you trust (trust_network"
        + (", known by its router)" if "identity" in rec else ")"))
    return ""


def configure_restart(root_part: str, recovery=Path('/run/starchaser-recovery-key.txt'), runtime=Path('/run')) -> None:
    # The restart key is enrolled only after the encrypted target is mounted.
    # It never enters the normal startup image or the unencrypted boot drive.
    with tempfile.TemporaryDirectory(prefix='starchaser-restart-enroll-', dir=runtime) as tmp:
        current = Path(tmp) / 'current'
        fd = os.open(current, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, 'wb') as out:
            out.write(recovery.read_bytes().rstrip(b'\n'))
        planned_restart.provision(root_part, MNT, current, sh)


def configure(a: dict, root_part: str, enc: str, dual: bool, rtc_local: bool = False, root_fs: str = "btrfs") -> None:
    emit(event="phase", phase="configure", label="Setting up the system")
    u = a["user"]
    tz, keymap, locale = a["timezone"], a.get("keymap", "us"), a.get("locale", "en_US.UTF-8")
    lg = MNT / "etc/locale.gen"                                  # the chosen locale, and US English as a fallback
    want = {f"{locale} UTF-8", "en_US.UTF-8 UTF-8"}
    lines = [l[1:] if l.startswith("#") and l[1:].strip() in want else l for l in lg.read_text().splitlines()]
    lines += [w for w in want if w not in lines]
    lg.write_text("\n".join(lines) + "\n")
    # every answer is checked by plan(); written as files, not pasted into the script
    host = a["hostname"]
    (MNT / "etc/locale.conf").write_text(f"LANG={locale}\n")
    (MNT / "etc/vconsole.conf").write_text(f"KEYMAP={keymap}\nFONT=ter-132b\n")
    (MNT / "etc/hostname").write_text(host + "\n")
    (MNT / "etc/hosts").write_text(f"127.0.0.1   localhost\n::1         localhost\n127.0.1.1   {host}.localdomain {host}\n")
    (MNT / "etc/systemd").mkdir(parents=True, exist_ok=True)
    (MNT / "etc/systemd/zram-generator.conf").write_text("[zram0]\nzram-size = min(ram / 2, 8192)\ncompression-algorithm = zstd\n")
    chroot(f"""
ln -sf {shlex.quote('/usr/share/zoneinfo/' + tz)} /etc/localtime
hwclock --systohc{' --localtime' if rtc_local else ''} || true
locale-gen
""")
    # the user: the full name as its own argument (no shell: accents, apostrophes and $ stay as typed); the
    # password from stdin, never on a command line or in the log
    for f in ("etc/passwd", "etc/group"):
        if any(l.split(":")[0] == u["username"] for l in (MNT / f).read_text().splitlines()):
            fail(f"The username {u['username']!r} is already used by the system. Pick another and try again.")
    sh("arch-chroot", MNT, "useradd", "-m", "-G", "wheel", "-c", u.get("name", ""), "-s", "/bin/bash", u["username"])
    chroot("chpasswd", input=f"{u['username']}:{u['password']}\n")
    global PASSWORD_CODE
    PASSWORD_CODE = "" if a.get("account_setup") == "later" else password_code(u["username"])
    if a.get("account_setup") == "later":
        chroot("passwd -l starchaser-setup")
    chroot("passwd -l root")
    keys = a.get("authorized_keys") or []
    if keys == "live":
        keys = Path("/root/.ssh/authorized_keys").read_text().splitlines() if Path("/root/.ssh/authorized_keys").exists() else []
    elif isinstance(keys, str):                           # one key per line, as a single string, works too
        keys = keys.splitlines()
    if keys:
        ak = MNT / f"home/{u['username']}/.ssh/authorized_keys"
        ak.parent.mkdir(parents=True, exist_ok=True)
        ak.write_text("\n".join(k.strip() for k in keys if k.strip()) + "\n")
        chroot(f"chown -R {u['username']}:{u['username']} /home/{u['username']}/.ssh && chmod 700 /home/{u['username']}/.ssh "
               f"&& chmod 600 /home/{u['username']}/.ssh/authorized_keys")
    # sudo: during the install the desktop setup needs it without a password; afterwards it asks unless chosen.
    # 05-starchaser-defaults turns off sudo's pam_silent (on by default since 1.9.16), which hid pam_faillock's
    # "The account is locked due to 3 failed logins" note: a paused account looked like a wrong password ("Sorry, try
    # again."). It is its own file so the access rule in 10-wheel is never rewritten for it
    chroot("""printf 'Defaults lecture=never\\n%%wheel ALL=(ALL:ALL) ALL\\n' > /etc/sudoers.d/10-wheel
chmod 440 /etc/sudoers.d/10-wheel
printf 'Defaults !pam_silent\\n' > /etc/sudoers.d/05-starchaser-defaults
chmod 440 /etc/sudoers.d/05-starchaser-defaults
echo '%wheel ALL=(ALL:ALL) NOPASSWD: ALL' > /etc/sudoers.d/99-starchaser-installing
chmod 440 /etc/sudoers.d/99-starchaser-installing
visudo -c""")
    carry_network_profiles()
    # SSH's host keys now, written and synced with the install: left to the first boot, a power cut right after
    # leaves them empty and sshd refuses to start ("no hostkeys available") from then on
    chroot("ssh-keygen -A")
    # The new system uses NetworkManager. First-boot presets enable networkd again even if desktop setup
    # disabled its wait: with no managed links it then times out for two minutes. Mask it in the target,
    # including socket activation, so those presets cannot undo the choice. Never change the live network.
    chroot("""systemctl disable systemd-networkd.service systemd-networkd.socket systemd-networkd-wait-online.service
systemctl mask systemd-networkd.service systemd-networkd.socket systemd-networkd-wait-online.service""")
    services = "NetworkManager NetworkManager-wait-online systemd-timesyncd fstrim.timer" + (" sshd" if a.get("ssh") or a.get("fleet_profile") else "")
    # NVIDIA's driver keeps the picture across sleep only with its own suspend/resume services and video memory
    # saved: without them a laptop whose lid sleeps it (the default on battery) wakes to a black screen
    if (MNT / "usr/lib/systemd/system/nvidia-suspend.service").exists():
        services += " nvidia-suspend nvidia-resume nvidia-hibernate"
        (MNT / "etc/modprobe.d").mkdir(parents=True, exist_ok=True)
        (MNT / "etc/modprobe.d/starchaser-nvidia-sleep.conf").write_text(
            "# written by the Starchaser installer: keep video memory across sleep (nvidia-suspend.service)\n"
            "options nvidia NVreg_PreserveVideoMemoryAllocations=1\n")
        hybrid = hardware.nvidia_options(gpus())
        if hybrid:          # read by the start-up image too (modconf), so it holds from the first moment
            (MNT / "etc/modprobe.d/starchaser-nvidia-hybrid.conf").write_text(hybrid)
    chroot(f"systemctl enable {services}")
    # A first boot with no network (Wi-Fi not set up yet) must reach the sign-in screen without waiting on time or
    # the network: systemd-time-wait-sync would wait forever, so it stays off (timesyncd syncs when a network
    # appears), and NetworkManager's wait for the network gives up after 15 seconds instead of 60.
    chroot("systemctl disable systemd-time-wait-sync.service 2>/dev/null || true")
    wait_dir = MNT / "etc/systemd/system/NetworkManager-wait-online.service.d"
    wait_dir.mkdir(parents=True, exist_ok=True)
    (wait_dir / "starchaser-offline.conf").write_text(
        "# written by the Starchaser installer: no network must not hold up the first boot\n"
        "[Service]\nExecStart=\nExecStart=/usr/bin/nm-online -s -q --timeout=15\n")

    # boot: the Starchaser boot screen (Plymouth: the animated Starchaser mark, and the passphrase box for a locked drive),
    # initramfs (systemd; keyboard and font before the unlock prompt) and systemd-boot
    emit(event="phase", phase="boot", label="Setting up startup")
    theme = Path(a.get("repo") or "/usr/share/starchaser/repo") / "system/usr/share/plymouth/themes/starchaser"
    if theme.is_dir():
        sh("cp", "-r", theme, MNT / "usr/share/plymouth/themes/")
        (MNT / "etc/plymouth").mkdir(parents=True, exist_ok=True)
        (MNT / "etc/plymouth/plymouthd.conf").write_text("[Daemon]\nTheme=starchaser\nShowDelay=0\nDeviceTimeout=8\n")
    hooks = "base systemd plymouth autodetect microcode modconf kms keyboard sd-vconsole block " + \
            ("sd-encrypt " if enc != "none" else "") + "filesystems fsck"
    # Arch's preset makes only the default image now: the boot menu's fallback entry ("if the normal start fails",
    # in plain words: the same kernel with every driver in its start-up image) needs the fallback one too
    chroot(f"sed -i 's/^HOOKS=.*/HOOKS=({hooks})/' /etc/mkinitcpio.conf")
    # NVIDIA's driver in the start-up image: loaded later, its render node came a moment after the login screen's
    # Hyprland had looked for it (a desktop, RTX 4080 beside the processor's graphics: "No matching render node",
    # dmabuf import failures and a black login screen). Early, the boot screen shows on its screens too.
    if chroot("pacman -Q nvidia-open >/dev/null 2>&1", check=False).returncode == 0:
        (MNT / "etc/mkinitcpio.conf.d").mkdir(parents=True, exist_ok=True)
        (MNT / NVIDIA_INITRAMFS).write_text(
            "# written by the Starchaser installer: NVIDIA's driver starts with the system, before the login screen\n"
            "MODULES+=(nvidia nvidia_modeset nvidia_uvm nvidia_drm)\n")
    if enc != "none":
        dropin = MNT / "etc/systemd/system/systemd-cryptsetup@.service.d"
        dropin.mkdir(parents=True, exist_ok=True)
        (dropin / "starchaser.conf").write_text("[Service]\nEnvironment=SYSTEMD_LOG_LEVEL=debug\n")
        confdir = MNT / "etc/mkinitcpio.conf.d"
        confdir.mkdir(parents=True, exist_ok=True)
        (confdir / "starchaser-drive-unlock.conf").write_text("FILES+=(/etc/systemd/system/systemd-cryptsetup@.service.d/starchaser.conf)\n")
        # a keyboard on the I2C bus (some thin laptops and 2-in-1s) types the passphrase only with its drivers in
        # the start-up image: the keyboard hook takes USB and PS/2 keyboards only
        keys = hardware.initramfs_input_modules()
        if keys:
            (confdir / "starchaser-keyboard.conf").write_text(
                "# written by the Starchaser installer: this computer's I2C keyboard types the drive's passphrase\n"
                f"MODULES+=({' '.join(keys)})\n")
    # No start-up image yet: the kernels arrive with the desktop's package repo (install_kernel_packages), and their
    # images are built then, from the settings written here.
    rflags = " rootflags=subvol=@" if root_fs == "btrfs" else ""          # Advanced may put / on ext4 or xfs
    if enc != "none":
        uuid = sh("cryptsetup", "luksUUID", root_part).stdout.strip()
        if enc == "tpm-pin":
            configure_restart(root_part)
        lopt = "tpm2-device=auto,discard" if enc in ("tpm", "tpm-pin") else "discard"
        options = f"rd.luks.name={uuid}={MAPPER} rd.luks.options={lopt} root=/dev/mapper/{MAPPER}{rflags} rw"
    else:
        uuid = sh("blkid", "-s", "UUID", "-o", "value", root_part).stdout.strip()
        options = f"root=UUID={uuid}{rflags} rw"
    options += " quiet splash loglevel=3 rd.udev.log_level=3 vt.global_cursor_default=0"   # the boot screen, not text
    # Reused by package upgrades for the native kernels and the saved LTS fallback.
    cmdline = MNT / "etc/kernel/cmdline"
    cmdline.parent.mkdir(parents=True, exist_ok=True)
    cmdline.write_text(options + "\n")
    # The boot entries are written with the kernels (install_kernel_packages); the boot menu itself (bootctl install)
    # comes last, in finish(): see boot_menu()
    if live_safegfx():
        # The stick was started with "safe graphics" because this computer froze with its graphics driver. The
        # installed system gets the right driver, but its first start, and a fallback entry for later, use the same
        # safe options; Settings > Hardware offers to try the full driver (safegfx.py).
        safegfx.mark(MNT)
        log("started with safe graphics: the installed system starts with safe graphics until Settings > Hardware tries the full driver")


# The boot step copies the boot-screen theme in before the desktop package arrives (the start-up image is built
# with it), so the package that owns those files may replace them.
# Files the install writes before the desktop package arrives, which the package then owns: pacman stops on "exists
# in filesystem" without these. The drive-unlock drop-ins are written at the startup step (an encrypted install's
# first startup image needs them) and starchaser-desktop ships them too (since 2026-11-10; every encrypted install
# of a desktop package built after that stopped there, seen on the full image in a VM on 2026-11-16).
OVERWRITE = ("--overwrite", "/usr/share/plymouth/themes/starchaser/*",
             "--overwrite", "/etc/systemd/system/systemd-cryptsetup@.service.d/starchaser.conf",
             "--overwrite", "/etc/mkinitcpio.conf.d/starchaser-drive-unlock.conf")


@contextlib.contextmanager
def desktop_from_package(a: dict):
    """Bootstrap one keyring, enable the real signed repo, then install the desktop in the new system.

    Temporary repos have unique names, so removing their sync databases cannot delete an existing real repo.
    The installed local package database is always the system's own, never a disposable --dbpath.
    """
    if a.get("_complete_media"):
        cache = MNT / "var/cache/pacman/pkg"
        shutil.copytree(a["_complete_media"], cache, dirs_exist_ok=True)
        conf = MNT / "etc/pacman.conf"
        # pacstrap inherited the live install source. Restore ordinary update sources before setup, which
        # enables multilib and protects the OS name there. Every install transaction uses its separate config.
        original = a.get("_updates_conf") or conf.read_text()
        conf.write_text(original)
        local = MNT / "var/cache/pacman/installer.conf"
        local.write_text(installer_media.config(Path("/var/cache/pacman/pkg"), live=live_packages.has_live(cache)))
        try:
            args = ["arch-chroot", MNT, "pacman", "--config", "/var/cache/pacman/installer.conf"]
            boot = MNT / "var/cache/pacman/bootstrap.conf"
            boot.write_text(pkgrepo.bootstrap_conf(local=True))
            keyring = pkgrepo.find_keyring(cache)
            sh("arch-chroot", MNT, "pacman", "--config", "/var/cache/pacman/bootstrap.conf", "-U", "--noconfirm", "/var/cache/pacman/pkg/" + keyring.name)
            boot.unlink()
            sh("arch-chroot", MNT, "pacman-key", "--populate", "starchaser")
            sh(*args, "-Syu", "--needed", "--noconfirm", *OVERWRITE, *pkgrepo.PACKAGES, *(["sunshine"] if a.get("remote_desktop") else []))
            install_kernel_packages("/var/cache/pacman/installer.conf")
            yield "/var/cache/pacman/installer.conf"
        finally:
            local.unlink(missing_ok=True)
        return
    channel = pkgrepo.channel_name(a.get("channel", "release"))
    server = pkgrepo.server_url(a.get("repo_url"))
    offline = Path(a.get("pkgrepo_dir") or pkgrepo.OFFLINE_REPO)
    # /var/tmp, not /tmp: arch-chroot mounts a fresh tmpfs over the new system's /tmp, which hides anything put there
    # from outside, so pacman inside could not read the config or the offline repo.
    parent = MNT / "var/tmp"
    parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix="starchaser-pkgrepo-", dir=parent) as tmp:
        work = Path(tmp)
        # pacman 7 downloads as its own unprivileged user (DownloadUser = alpm), also from file:// repos: the folder
        # TemporaryDirectory makes is root-only (0700). Nothing secret is in it (a config and signed packages).
        os.chmod(work, 0o755)
        inside = "/var/tmp/" + work.name
        keyring = None
        if offline.is_dir():
            copied = work / "repo"
            shutil.copytree(offline, copied)
            keyring = inside + "/repo/" + pkgrepo.find_keyring(copied).name
            # ISO repos use starchaser.db. A unique temp section avoids leaving an offline sync db behind.
            db = copied / (channel + ".db")
            if not db.is_file():
                db = copied / "starchaser.db"
            if not db.is_file():
                fail(f"The offline package repo has no database at {offline}.")
            shutil.copy2(db, copied / "starchaser-offline.db")
            sig = Path(str(db) + ".sig")
            if sig.is_file():
                shutil.copy2(sig, copied / "starchaser-offline.db.sig")
        if not keyring:
            downloaded = pkgrepo.fetch_keyring(work, channel, server)
            keyring = inside + "/" + downloaded.name
        boot = work / "bootstrap.conf"
        boot.write_text(pkgrepo.bootstrap_conf(channel, server, local=True))
        conf = MNT / "etc/pacman.conf"
        try:
            args = ["pacman", "--config", inside + "/bootstrap.conf", "--noconfirm"]
            sh("arch-chroot", MNT, *args, *(["-U", keyring] if keyring else ["-Sy", "starchaser-keyring"]))
            if not keyring:      # the database fetched without a signature check is not kept: the next -Syu fetches the checked one
                for suffix in ("db", "db.sig", "files", "files.sig"):
                    (MNT / f"var/lib/pacman/sync/{channel}.{suffix}").unlink(missing_ok=True)
            # A failed .install is only a note. Explicitly populate before requiring trusted package signatures.
            sh("arch-chroot", MNT, "pacman-key", "--populate", "starchaser")
            conf.write_text(installer_repo_conf(conf.read_text(), a.get("channel", "release"), server))
            if offline.is_dir() and not (a["_package_online"] if "_package_online" in a else pkgrepo.repo_reachable(channel, server)):
                # Keep the new system's Arch repos for dependencies; the temporary repo is signed and comes first.
                local = work / "offline.conf"
                text = conf.read_text()
                text = re.sub(r"(?ms)^\[starchaser(?:-testing)?\][^\n]*\n.*?(?=^\[|\Z)", "", text)
                block = ("[starchaser-offline]\nSigLevel = Required DatabaseOptional\n"
                         f"Server = file://{inside}/repo\n\n")
                local.write_text(text.replace("[core]", block + "[core]", 1) if "[core]" in text else text + "\n" + block)
                targets = pkgrepo.offline_targets(copied)
                if "hyprland" not in targets:
                    log("desktop: the offline package repo has no hyprland; Arch's stock Hyprland is installed (a test ISO)")
                sh("arch-chroot", MNT, "pacman", "--config", inside + "/offline.conf", "-Syu", "--needed", "--noconfirm", *OVERWRITE, *targets)
                install_kernel_packages(inside + "/offline.conf")
                yield inside + "/offline.conf"  # setup also installs dependencies; keep this signed offline repo until it finishes
            else:
                sh("arch-chroot", MNT, "pacman", "-Syu", "--needed", "--noconfirm", *OVERWRITE, *pkgrepo.PACKAGES)
                install_kernel_packages()
                yield None
        finally:
            for name in ("starchaser-offline",):
                for suffix in ("db", "db.sig", "files", "files.sig"):
                    (MNT / f"var/lib/pacman/sync/{name}.{suffix}").unlink(missing_ok=True)


def screen_layout(a: dict) -> None:
    """The screen the graphical installer ran on, and any screen turned on its side there: the new account's monitor
    layout (~/.config/hypr/monitors.lua, written by starchaser displays' own code, as Settings > Displays writes it),
    so the first sign-in opens on that screen (the cockpit's main screen) with the same turns. Written before the
    desktop setup, whose login-screen sync gives the sign-in screen the same layout. Never fatal: without it every
    screen keeps the default layout."""
    layout = a.get("displays")
    if not layout:
        return
    u = a["user"]["username"]
    tool = Path(a.get("repo") or "/usr/share/starchaser/repo") / "bin/starchaser-displays"
    try:
        loader = importlib.machinery.SourceFileLoader("starchaser_displays", str(tool))
        mod = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
        loader.exec_module(mod)
        text = mod.render(layout)
    except Exception as e:
        log(f"the screen layout couldn't be written ({e}); every screen starts with the default layout")
        return
    if chroot(f"install -d -o {u} -g {u} /home/{u}/.config /home/{u}/.config/hypr", check=False).returncode != 0:
        log("the screen layout couldn't be written (no ~/.config/hypr); every screen starts with the default layout")
        return
    dst = MNT / f"home/{u}/.config/hypr/monitors.lua"
    dst.write_text(text)
    dst.chmod(0o644)
    chroot(f"chown {u}:{u} /home/{u}/.config/hypr/monitors.lua", check=False)
    log("screen layout: " + ", ".join(m.get("name") or m["desc"] for m in layout)
        + "; main " + next((m.get("name") or m["desc"] for m in layout if m.get("primary")), "none"))


def desktop(a: dict) -> str:
    """-> a warning for the finished screen: something the desktop setup couldn't add ("" when all went well)."""
    emit(event="phase", phase="desktop", label="Installing the Starchaser desktop")
    u = a["user"]["username"]
    screen_layout(a)
    source = a.get("_desktop_source") or pkgrepo.desktop_source(a)
    if source == "package" and "_package_online" not in a and pkgrepo.tries_online(a):
        # nothing asked for this repo, so an unreachable one (no network yet, the server down) is not worth failing
        # the install over: the checkout this installer carries installs the same desktop
        if pkgrepo.repo_reachable():
            log(f"desktop: installing from the online Starchaser repo {pkgrepo.server_url()} (no offline package repo on this installer)")
        else:
            source = "checkout"
            log(f"desktop: the online Starchaser repo {pkgrepo.server_url()} can't be reached; using the checkout on this installer")
    with contextlib.ExitStack() as stack:
        if source == "package":
            offline_conf = stack.enter_context(desktop_from_package(a))
            env = (f"STARCHASER_INSTALLER=1 REPO=/usr/share/starchaser LOGIN=greeter "
                   f"AUTOLOGIN={'yes' if a.get('autologin') else 'no'} "
                   f"REMOTE_DESKTOP={'yes' if a.get('remote_desktop') else 'no'}")
            if offline_conf:
                env += " STARCHASER_PACMAN_CONF=" + shlex.quote(offline_conf)
            cmd = ["arch-chroot", str(MNT), "bash", "-euo", "pipefail", "-c",
                   as_account(u, f"{env} bash /usr/share/starchaser/installer/starchaser-desktop-setup.sh")]
        else:
            if a.get("desktop_source", "auto") == "auto" and not pkgrepo.AUTO_TRIES_ONLINE_REPO:
                log("desktop: using the checkout because no offline package repo or repo_url was supplied")
            src = Path(a.get("repo") or "/usr/share/starchaser/repo")
            if not (src / "config/hypr/hyprland.lua").exists():
                fail(f"The Starchaser files this installer needs aren't at {src}.")
            install_kernel_packages()    # no Starchaser package repo here, so no Starchaser kernels: the stock one
            dst = MNT / f"home/{u}/.local/share/starchaser/repo"
            dst.parent.mkdir(parents=True, exist_ok=True)
            sh("cp", "-a", f"{src}/.", dst) if dst.exists() else sh("cp", "-a", src, dst)
            chroot(f"chown -R {u}:{u} /home/{u}/.local")
            # archiso drops file modes when it builds the live system (every tool lost its execute bit): git knows them.
            # A copy without git (an answers file's own "repo") has nothing to reset from: its modes are taken as they are,
            # instead of the whole install stopping at this last step
            if (dst / ".git").exists():
                chroot(f"runuser -u {u} -- git -C /home/{u}/.local/share/starchaser/repo reset -q --hard")
            else:
                log(f"desktop: {src} has no .git; file modes copied as they are")
            shutil.rmtree(dst / "hardware", ignore_errors=True)   # personal setup for the maintainer's own computers; the reset above restores it
            env = (f"STARCHASER_INSTALLER=1 REPO=/home/{u}/.local/share/starchaser/repo LOGIN=greeter "
                   f"AUTOLOGIN={'yes' if a.get('autologin') else 'no'} "
                   f"REMOTE_DESKTOP={'yes' if a.get('remote_desktop') else 'no'}")
            cmd = ["arch-chroot", str(MNT), "bash", "-euo", "pipefail", "-c",
                   as_account(u, f"{env} bash /home/{u}/.local/share/starchaser/repo/installer/starchaser-desktop-setup.sh")]
        missing = []                     # "STARCHASER-WARNING: ..." lines: a part that didn't install, the rest did
        if stream(cmd, "desktop", on_line=lambda l: missing.append(l.split(":", 1)[1].strip())
                  if l.startswith("STARCHASER-WARNING:") else None) != 0:
            fail("The Starchaser desktop didn't finish installing (the details are below).")
    try:
        if install_language.seed_input_method(MNT / f"home/{u}", a.get("locale", "en_US.UTF-8")):
            if chroot(f"chown -R {u}:{u} /home/{u}/.config/fcitx5 /home/{u}/.config/starchaser/input-methods.json", check=False).returncode:
                missing.append("The input method could not be set up. Add it in Settings > Keyboard.")
    except OSError:
        missing.append("The input method could not be saved. Add it in Settings > Keyboard.")
    # the keyboard chosen in the installer, for the desktop too (Settings > Keyboard's input.lua, below)
    xkb = a.get("xkb_layout") or "us"
    m = re.fullmatch(r"([a-z0-9_]+)(?:\(([A-Za-z0-9_-]+)\))?", xkb)           # checked against the list by plan()
    if not m:
        fail(f"Unknown keyboard layout {xkb!r}.")
    lay, var = m.group(1), m.group(2) or ""
    # and for the login screen, which runs before anyone's home is open and never reads a user's Lua: plain values in
    # a root-owned file (greeter/hyprland.lua checks them again before using them)
    kb = MNT / "etc/starchaser/keyboard"
    kb.parent.mkdir(parents=True, exist_ok=True)
    kb.write_text(f"layout={lay}\nvariant={var}\n")
    kb.chmod(0o644)
    if xkb != "us":
        # into Settings > Keyboard's own file (input.lua), so a later change there wins: a line in user.lua (loaded
        # last) put the installer's layout back over every change made in Settings
        tool = "/usr/lib/starchaser/bin/starchaser-input" if source == "package" else f"/home/{u}/.local/share/starchaser/repo/bin/starchaser-input"
        r = chroot(as_account(u, f'python3 {tool} set layouts {lay}' + (f':{var}' if var else '')), check=False)
        if r.returncode != 0:
            log("the keyboard layout couldn't go into input.lua; it goes into user.lua instead")
            ul = MNT / f"home/{u}/.config/hypr/user.lua"
            ul.parent.mkdir(parents=True, exist_ok=True)
            with open(ul, "a") as f:
                f.write(f'\n-- keyboard chosen in the installer\nhl.config({{ input = {{ kb_layout = "{lay}", kb_variant = "{var}" }} }})\n')
            chroot(f"chown {u}:{u} /home/{u}/.config/hypr/user.lua")
    # the screen locks after 15 minutes away, plugged in and on battery (decided 2026-10-10): for a NEW install only,
    # so it's written here and not in starchaser power's defaults, where computers set up before would change too
    # (they keep Never). Settings > Power changes it like any other choice. Never fatal
    lock = " && ".join(f"starchaser power set {src}.lock 15" for src in ("ac", "battery"))
    r = chroot(as_account(u, 'PATH=$HOME/.local/bin:$PATH; ' + lock), check=False)
    if r.returncode != 0:
        log("the 15-minute screen lock couldn't be set; the screen never locks by itself until it's set in Settings > Power")
    return " ".join(missing)


def login_keyring(a: dict) -> None:
    """Saved sign-ins: the "login" keyring, made now with the account password, so the first app that wants to save
    a password never opens "Choose password for new keyring". The sign-in screen unlocks it the same way later (the
    desktop setup's pam line). After an automatic login nothing could unlock it, so there it is made
    without encryption (below). The password goes in on stdin, never on a command line or in the log. Never fatal.

    A computer that signs in by itself (fpreimp-look P2-13) has no password to unlock it with at sign-in, so a keyring
    locked with the account password raises the stock "Authentication required" prompt in front of the first app
    after every restart. (A keyring made with an empty password is no answer: it stays locked and asks all the same;
    QA VM check.) Leaving it unencrypted is its own choice (keyring_unencrypted, off by default; decided 2026-11-16):
    only when the person ticked it is the keyring made as above and then turned into saved passwords that need no
    unlock, with the one command Settings > Security uses (starchaser keyring enable-passwordless-storage). Nothing is
    saved in it yet. Settings > Security shows it as on and the person can
    lock it again there, which is when apps start asking."""
    name = a["user"]["username"]
    home = f"/home/{name}"
    # nobody is logged in here, so this does what the sign-in does: a private session bus and runtime folder, the
    # daemon started in login mode with the password on stdin (kept in a shell variable, never in a command line),
    # then the daemon the desktop would start discovers it and the login keyring is made. Only the one daemon this
    # script started is stopped, by its own process number: the live system's other processes are never matched
    # automatic sign-in: the same password, as one JSON string on the tool's stdin (never in an argument), takes the
    # encryption off while the daemon this script started is still running
    unlock = ('printf %s "$pw" | python3 -c "import json,sys;print(json.dumps(sys.stdin.read()))" | '
              'starchaser keyring enable-passwordless-storage >/dev/null; ') if (a.get("autologin") and a.get("keyring_unencrypted")) else ''
    inner = ('IFS= read -r pw; printf %s "$pw" | gnome-keyring-daemon --foreground --login --components=secrets & kp=$!; '
             'sleep 1; gnome-keyring-daemon --start --components=secrets >/dev/null; sleep 1; ' + unlock + 'kill $kp')
    script = (f'd=$(mktemp -d /tmp/keyring.XXXXXX) && chown {name}:{name} "$d" && chmod 700 "$d" && '
              f'install -d -o {name} -g {name} -m 700 {home}/.local {home}/.local/share {home}/.local/share/keyrings && '
              f'timeout 20 runuser -u {name} -- env HOME={home} XDG_RUNTIME_DIR="$d" XDG_DATA_HOME={home}/.local/share '
              f'dbus-run-session -- bash -c {shlex.quote(inner)}; rm -rf "$d"')
    chroot(script, check=False, input=a["user"]["password"] + "\n")
    ring = MNT / f"home/{name}/.local/share/keyrings"
    if not (ring / "login.keyring").exists():
        log("the login keyring couldn't be made; the first app that saves a password will ask for a new keyring password")
        return
    if not (ring / "default").exists():
        (ring / "default").write_text("login")
    chroot(f"chown -R {name}:{name} {home}/.local/share/keyrings", check=False)


def baseline() -> str:
    """Settings > Recovery's first snapshot: the finished system, taken only now that the installer's no-password sudo
    rule is gone. The snapshots snap-pac took during the desktop setup hold a half-built system (no login screen yet)
    with that rule still in place, so going back to one would leave no login screen and a password-free root: they
    are deleted. The baseline has no cleanup rule (never deleted by itself) and is tagged starchaser=setup, which
    starchaser recovery and starchaser-admin read: nothing older than it is offered. Never fatal."""
    if not (MNT / "etc/snapper/configs/root").exists():
        return ""
    r = chroot("mountpoint -q /.snapshots || mount /.snapshots; snapper --no-dbus --jsonout -c root list", check=False)
    try:
        old = [s["number"] for s in json.loads(r.stdout[r.stdout.index("{"):])["root"] if s.get("number")]
    except (ValueError, KeyError, TypeError):
        return "The first recovery snapshot could not be made safely. Older snapshots may restore unfinished setup and unsafe password settings. Open Settings > Recovery, delete installation snapshots, and make a new snapshot."
    if old:
        if chroot("snapper --no-dbus -c root delete " + " ".join(str(n) for n in old), check=False).returncode:
            return "Some installation snapshots could not be removed. Open Settings > Recovery before using older snapshots."
    result = chroot("snapper --no-dbus -c root create -t single -d 'When Starchaser was set up' "
           "--userdata 'important=yes,starchaser=setup'", check=False)

    return "The first recovery snapshot could not be made. Open Settings > Recovery to make one." if result.returncode else ""


def boot_menu(dual: bool) -> None:
    """systemd-boot onto the EFI partition, its firmware boot entry (first in the boot order) and loader.conf.
    Done as late as possible: on a dual-boot drive the EFI partition is the one Windows (or another system) already
    starts from, and a failed attempt only removes the partitions it made, so nothing that fails after this point
    should be likely. Everything before it (the desktop setup most of all) changes only Starchaser's own partitions."""
    esp_dir = "/efi" if dual else "/boot"
    esp = MNT / esp_dir.lstrip("/")
    if signed_boot.configuration(MNT) is not None:
        STATE["signed_boot_files"] = signed_boot.loader_snapshot(MNT, esp_dir)
        signed_boot.install_loader(MNT, esp_dir)
        if live_safegfx() and (MNT / "boot/loader/entries" / f"{safegfx.ENTRY}.conf").is_file():
            safegfx.set_default(esp, safegfx.ENTRY)
        firmware_entry(esp_dir, loader=r"\EFI\Starchaser\shimx64.efi", required=True)
        return
    # bootctl install also writes systemd-boot over the drive's fallback loader (EFI/BOOT/BOOTX64.EFI). Sharing a
    # drive, that file may be the only way another Linux (GRUB) starts: kept, put back after, and listed in the
    # Starchaser menu. Windows is listed by systemd-boot by itself, and its own loader is never touched.
    kept = None
    if dual:
        fb = next((f for f in esp.glob("EFI/*/*") if f.parent.name.upper() == "BOOT" and f.name.upper() == "BOOTX64.EFI"), None)
        if fb and fb.is_file():
            data = fb.read_bytes()
            ms = next((f for f in esp.glob("EFI/*/Boot/bootmgfw.efi")), None)
            if b"systemd-boot" not in data:
                kept = (fb, data, not (ms and ms.is_file() and ms.read_bytes() == data))
    chroot(f"bootctl --esp-path={esp_dir}" + (" --boot-path=/boot" if dual else "") + " install")
    if kept:
        fb, data, other = kept
        fb.write_bytes(data)
        log(f"put back the fallback loader {fb.relative_to(esp)} that was there before")
        if other:
            # on the ESP itself: an entry's paths are read on the partition the entry is on
            ent = esp / "loader/entries"
            ent.mkdir(parents=True, exist_ok=True)
            (ent / "previous-system.conf").write_text(
                "title   The system that was here before\nefi     /" + str(fb.relative_to(esp)) + "\n")
    firmware_entry(esp_dir)
    (MNT / esp_dir.lstrip("/") / "loader").mkdir(parents=True, exist_ok=True)
    # a dual-boot menu stays up long enough to pick Windows; systemd-boot lists Windows Boot Manager by itself
    (MNT / esp_dir.lstrip("/") / "loader/loader.conf").write_text(
        f"default  {default_entry()}.conf\ntimeout  {5 if dual else 3}\nconsole-mode keep\neditor   no\n")


def firmware_entry(esp_dir: str, loader=r"\EFI\systemd\systemd-bootx64.efi", required=False) -> None:
    """The firmware's own boot entry for Starchaser, first in its boot order. bootctl inside arch-chroot skips EFI
    variables (systemd 262: "Not booted with EFI"), and with --variables=yes there it writes a bogus device path, so
    it is made from the live side. Without it the computer starts whatever its boot order already names: with
    several drives (an older system on another one, Windows) that is not Starchaser. Never fatal: the fallback
    loader (EFI/BOOT/BOOTX64.EFI) still starts Starchaser when its drive is the one the firmware tries."""
    if not Path("/sys/firmware/efi/efivars").is_dir():
        if required:
            fail("The firmware startup entry could not be made. Restart the signed installer in UEFI mode.")
        return
    src = subprocess.run(["findmnt", "-no", "SOURCE", str(MNT / esp_dir.lstrip("/"))], capture_output=True, text=True).stdout.strip()
    part = Path(src).name
    try:
        num = (Path("/sys/class/block") / part / "partition").read_text().strip()
        disk = "/dev/" + Path(os.path.realpath(Path("/sys/class/block") / part / "..")).name
        partuuid = subprocess.run(["blkid", "-s", "PARTUUID", "-o", "value", src], capture_output=True,
                                  text=True).stdout.strip().lower()
    except OSError:
        if required:
            fail("The firmware startup entry could not be made safely. Keep the installer stick and try again.")
        log(f"firmware entry: couldn't tell which drive {src!r} is on; leaving the boot order as it is")
        return
    label = "Starchaser Linux"
    # Legacy setup replaces its old entry. A signed install keeps earlier firmware choices available.
    for l in sh("efibootmgr", "-v", check=False).stdout.splitlines():
        m = re.match(r"Boot([0-9A-Fa-f]{4})\*?\s+(.*)", l)
        if not required and m and m.group(2).startswith(label) and partuuid and partuuid in l.lower():
            sh("efibootmgr", "-q", "-b", m.group(1), "-B", check=False)
    if sh("efibootmgr", "-q", "--create", "--disk", disk, "--part", num, "--label", label,
          "--loader", loader, check=False).returncode != 0:
        if required:
            fail("The firmware could not save the signed Starchaser startup entry. Keep the installer stick and try again.")
        log("firmware entry: efibootmgr failed; the computer starts Starchaser only from its fallback loader")


def stop_account_processes(uid: int) -> None:
    """End what account `uid` left running inside the new system: only processes whose root is the new system, so
    the live system's own account with the same number (the installer's session) is never touched."""
    def mine():
        found = []
        for proc in Path("/proc").glob("[0-9]*"):
            try:
                root = os.readlink(proc / "root")
                real = int(next(l.split()[1] for l in (proc / "status").read_text().splitlines() if l.startswith("Uid:")))
            except (OSError, ValueError, StopIteration):
                continue
            if real == uid and (root == str(MNT) or root.startswith(str(MNT) + "/")):
                found.append(int(proc.name))
        return found
    for sig in (signal.SIGTERM, signal.SIGKILL):
        pids = mine()
        for pid in pids:
            log(f"stopping {pid} ({'TERM' if sig == signal.SIGTERM else 'KILL'}): left running by the setup account")
            with contextlib.suppress(OSError):
                os.kill(pid, sig)
        for _ in range(30 if pids else 0):
            if not mine():
                return
            time.sleep(0.1)


def unmount_under(folder: Path) -> None:
    """Detach every mount at or inside `folder`, deepest first (never fatal: the caller checks what is left)."""
    points = []
    with contextlib.suppress(OSError):
        for line in Path("/proc/self/mountinfo").read_text().splitlines():
            mp = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), line.split()[4])
            if mp == str(folder) or mp.startswith(str(folder) + "/"):
                points.append(mp)
    for mp in sorted(set(points), key=lambda m: -m.count("/")):
        if sh("umount", mp, check=False).returncode:
            sh("umount", "-l", mp, check=False)


def remove_setup_account(name: str = "starchaser-setup") -> None:
    """Remove the staging account that ran the desktop setup for "Someone else, later", and its Home folder.
    Only an account still there stops the install (the first start would offer no account to make); a folder that
    survives is a logged warning: nobody can sign in to it, and the first person's account gets a Home of its own."""
    passwd = MNT / "etc/passwd"
    def entry():
        return next((l.split(":") for l in passwd.read_text().splitlines() if l.split(":")[0] == name), None)
    home = MNT / "home" / name
    found = entry()
    if found:
        stop_account_processes(int(found[2]))
    unmount_under(home)
    # userdel says "mail spool ... not found" (no mail spool is made: only a warning) and exits 12 when the Home
    # folder can't be deleted, after the account itself is already gone
    if chroot(f"userdel --force -r {name}", check=False).returncode and entry():
        chroot(f"userdel --force {name}", check=False)
    if entry():
        fail("Starchaser couldn't finish setting up the first start: the account it used while installing couldn't "
             "be removed. The details are below.")
    if os.path.lexists(home):
        unmount_under(home)
        sh("rm", "-rf", "--one-file-system", home, check=False)
    if os.path.lexists(home):
        log(f"warning: {home} couldn't be removed entirely; nobody can sign in to it, and it holds nothing personal")


def prepare_first_start(a):
    """Leave the shared desktop and greeter, with no inherited personal account or saved credential."""
    remove_setup_account()
    import recovery_code
    recovery_code.forget(MNT, "starchaser-setup")
    conf = MNT / "etc/greetd/config.toml"
    text = conf.read_text()
    text = re.sub(r"(?ms)^\[initial_session\]\n.*?(?=^\[|\Z)", "", text)
    conf.write_text(text)
    marker = MNT / "var/lib/starchaser/first-start.json"
    marker.parent.mkdir(parents=True, exist_ok=True)
    marker.write_text(json.dumps({"version": 1}) + "\n")
    marker.chmod(0o644)
    if a.get("fleet_profile"):
        profile = marker.with_name("fleet-install.json")
        profile.write_text(json.dumps(a["fleet_profile"]))
        profile.chmod(0o600)
    write_firstboot(a, MNT)


def write_firstboot(a: dict, root: Path) -> None:
    """Fleet rules 16.9 and 25.2: a `fleet_token` (and a `fleet_name`) in the answers go to the new system's
    /etc/starchaser/firstboot.json, root-only, and are never printed or logged. A file with only a fleet_name (after
    `starchaser fleet reset`) starts no join; Join a fleet then offers that name."""
    keep = {k: a[k] for k in ("fleet_token", "fleet_name") if isinstance(a.get(k), str) and a[k].strip()}
    if not keep:
        return
    path = root / "etc/starchaser/firstboot.json"
    path.parent.mkdir(parents=True, exist_ok=True)
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, "w") as out:
        os.fchmod(out.fileno(), 0o600)
        out.write(json.dumps(keep, sort_keys=True) + "\n")


TESTED_RELEASE_MARKER = "# Starchaser tested release: "


def drop_refused_lists(repos: list) -> None:
    """After the refresh, every list left must be one pacman accepts. When the server's list is older than the
    stick's, pacman keeps the stick's list but takes the server's signature: a list from one place and a signature
    from another, so every pacman command printed two errors, Software lost its official packages and the welcome
    took its apps from Flathub (Fable final review 2026-11-19 P1-1). Such a list and its signature are downloaded
    again together, once; one still refused is left out (the first check for updates downloads it)."""
    sync = MNT / "var/lib/pacman/sync"

    def refused():
        return [r for r in repos if (sync / f"{r}.db").is_file()
                and sh("arch-chroot", MNT, "pacman", "-Sl", r, check=False).returncode]
    bad = refused()
    if not bad:
        return
    log("package lists: refused after the refresh, downloading again: " + ", ".join(bad))
    for r in bad:
        for suffix in ("", ".sig"):
            (sync / f"{r}.db{suffix}").unlink(missing_ok=True)
    sh("arch-chroot", MNT, "timeout", "180", "pacman", "-Sy", "--noconfirm", check=False)
    for r in refused():
        log(f"package lists: the {r} list is still refused; left out")
        for suffix in ("", ".sig"):
            (sync / f"{r}.db{suffix}").unlink(missing_ok=True)


def leave_package_lists(a: dict) -> None:
    """Give the new system a package list for every source its pacman.conf names. A full-stick install used to leave
    only the stick's own [complete] list, so pacman called all 970 packages foreign: the welcome's setup failed
    "check your internet connection", Updates warned, and Software labeled every app Community recipes (Fable final
    review 2026-11-16 P1-1). The stick's build-day lists go in first (they match what was just installed, and work with
    no network); then, when online, the lists are refreshed in the new system. Never fatal."""
    sync = MNT / "var/lib/pacman/sync"
    sync.mkdir(parents=True, exist_ok=True)
    for f in [*sync.glob("complete.*"), *sync.glob(live_packages.REPO + ".*")]:
        f.unlink()                                   # the install source's lists: no longer sources of this system
    cache = MNT / "var/cache/pacman/pkg"
    for f in [*cache.glob(installer_media.LIST_PREFIX + "*.db"), *cache.glob(installer_media.LIST_PREFIX + "*.db.sig")]:
        f.unlink()                                   # copied into the cache with the stick's packages
    # the packages written out of the live system (P2-10): plain and unsigned, several GB, and only for this install
    for name in [*a.get("_live_files", []), live_packages.REPO + ".db", live_packages.META]:
        (cache / name).unlink(missing_ok=True)
    repos = sh("arch-chroot", MNT, "pacman-conf", "--repo-list", check=False).stdout.split()
    media = a.get("_complete_media")
    carried = installer_media.lists(Path(media)) if media else {}
    copied = []
    for repo in repos:
        if (sync / f"{repo}.db").is_file():
            continue
        # the stick's [starchaser] list stands for the chosen channel's until the first refresh: those packages are
        # the ones installed
        src = carried.get(repo) or (carried.get("starchaser") if repo.startswith("starchaser") else None)
        if not src:
            continue
        for suffix in ("", ".sig"):
            if Path(str(src) + suffix).is_file():
                shutil.copy2(Path(str(src) + suffix), sync / f"{repo}.db{suffix}")
                os.chmod(sync / f"{repo}.db{suffix}", 0o644)
        # a list pacman refuses (a signature it requires and can't check) is worse than none: every pacman command
        # would say so. Only lists the new system accepts stay.
        if sh("arch-chroot", MNT, "pacman", "-Sl", repo, check=False).returncode:
            log(f"package lists: the installer's {repo} list isn't accepted here; left out")
            for suffix in ("", ".sig"):
                (sync / f"{repo}.db{suffix}").unlink(missing_ok=True)
            continue
        copied.append(repo)
    if copied:
        log("package lists from the installer: " + ", ".join(copied))
    missing = [r for r in repos if not (sync / f"{r}.db").is_file()]
    if not (copied or missing):
        return
    conf = MNT / "etc/pacman.conf"
    if conf.is_file() and TESTED_RELEASE_MARKER in conf.read_text():
        log("package lists: not refreshed here, this system follows tested releases")
    elif online():
        if sh("arch-chroot", MNT, "timeout", "180", "pacman", "-Sy", "--noconfirm", check=False).returncode:
            log("package lists: couldn't refresh them now; the first check for updates does")
        drop_refused_lists(repos)
    missing = [r for r in repos if not (sync / f"{r}.db").is_file()]
    if missing:
        log("package lists: none yet for " + ", ".join(missing) + "; the first check for updates downloads them")


def finish(a: dict, enc: str, dual: bool) -> str:
    """-> a warning for the finished install's screen ("" when all went well)."""
    emit(event="phase", phase="finish", label="Finishing")
    if a.get("sudo_nopasswd"):
        chroot("echo '%wheel ALL=(ALL:ALL) NOPASSWD: ALL' > /etc/sudoers.d/10-wheel-nopasswd && chmod 440 /etc/sudoers.d/10-wheel-nopasswd")
    chroot("rm -f /etc/sudoers.d/99-starchaser-installing && visudo -c")
    if a.get("account_setup") == "later":
        prepare_first_start(a)
    leave_package_lists(a)
    recovery_warning = baseline()
    log("copying this log onto the new system")
    shutil.copy2(LOG, MNT / "var/log/starchaser-install.log")
    os.chmod(MNT / "var/log/starchaser-install.log", 0o600)
    sh("sync")
    queue_secure_boot()
    if not release_mnt():
        # the install itself is finished: this is a success with one thing to know, not a failure
        return " ".join(w for w in (recovery_warning, "Starchaser is installed, but the installer couldn't let go of the new drive. Restart before using it.") if w)
    for name in reversed(list(STATE["opened"])):
        close_crypt(name)                 # if one stays open, nothing is lost: restarting closes it
    shred_keys()                          # the extra drives' keyfiles are on the new system now
    return recovery_warning


def release_mnt() -> bool:
    """Stop what still uses the new system's files and unmount it. -> unmounted."""
    # anything still using the new system's files must stop before unmounting, or umount says "target is busy":
    # pacstrap leaves a gpg-agent for the new keyring running on the LIVE system (not in the chroot), and the
    # desktop setup can leave others
    # Only processes with a file, working directory or root actually under /mnt: `fuser -k -m /mnt` matched far
    # more (it stopped the live system's NetworkManager and dropped the installer's screen).
    if (MNT / "etc/pacman.d/gnupg").is_dir():
        sh("gpgconf", "--homedir", MNT / "etc/pacman.d/gnupg", "--kill", "all", check=False)
    mine = {os.getpid(), os.getppid()}
    for proc in Path("/proc").glob("[0-9]*"):
        pid = int(proc.name)
        if pid in mine or pid == 1:
            continue
        try:
            links = [os.readlink(proc / "cwd"), os.readlink(proc / "root")]
            links += [os.readlink(f) for f in (proc / "fd").iterdir()]
            # gpg-agent holds the disk through a socket and inotify watches (no paths to see); its command line
            # names its home there: --homedir /mnt//etc/pacman.d/gnupg
            links += (proc / "cmdline").read_bytes().decode(errors="replace").split("\0")
        except OSError:
            continue
        if any(l == str(MNT) or l.startswith(str(MNT) + "/") for l in links):
            log(f"stopping {pid} ({(proc / 'comm').read_text().strip()}): uses the new disk")
            try:
                os.kill(pid, 15)
            except OSError:
                pass
    time.sleep(1)
    for attempt in range(10):
        if subprocess.run(["findmnt", str(MNT)], capture_output=True).returncode != 0:
            STATE["mounted"] = False
            return True
        sh("umount", "-R", MNT, check=False)
        time.sleep(1 if attempt else 0)
    return False


def close_crypt(name: str = MAPPER) -> bool:
    """Close an encrypted volume this attempt opened. -> closed."""
    # systemd-nsresourced's workers on the live system keep private copies of the mount table that still hold
    # the new disk ("Device cryptroot is still in use"): stop them (systemd starts fresh ones on demand)
    # ONLY systemd's short-lived workers: long-running services (logind, D-Bus, NetworkManager, ...) also keep
    # copies of the mount table, and stopping them ended the installer's session.
    workers = ("systemd-nsresou", "systemd-userwor", "systemd-mountfs")
    for proc in Path("/proc").glob("[0-9]*"):
        try:
            if (proc / "comm").read_text().strip().startswith(workers) \
                    and f"/dev/mapper/{name}" in (proc / "mountinfo").read_text():
                log(f"stopping {proc.name} ({(proc / 'comm').read_text().strip()}): holds the new disk")
                os.kill(int(proc.name), 15)
        except OSError:
            pass
    # long-running services (resolved, udevd, dbus, ...) can keep a copy too: a mount made under /run while the
    # install ran (a login creating /run/user/N, a USB stick) propagates into their copy of the chroot's /mnt/run,
    # and that copy is then left behind by the unmount. Detach the copy inside their own mount namespace (nothing
    # else in it changes, and the service keeps running)
    time.sleep(1)
    seen = {os.readlink("/proc/self/ns/mnt")}
    for proc in Path("/proc").glob("[0-9]*"):
        try:
            ns = os.readlink(proc / "ns/mnt")
            if ns in seen:
                continue
            seen.add(ns)
            mps = [l.split(" - ", 1)[0].split()[4] for l in (proc / "mountinfo").read_text().splitlines()
                   if " - " in l and l.split(" - ", 1)[1].split()[1:2] == [f"/dev/mapper/{name}"]]
            comm = (proc / "comm").read_text().strip()
        except (OSError, IndexError):
            continue
        for mp in sorted(set(mps), key=lambda m: -m.count("/")):
            mp = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), mp)    # mountinfo escapes spaces as \040
            log(f"detaching {mp} in {proc.name}'s copy of the mounts ({comm})")
            sh("nsenter", "-t", proc.name, "-m", "--", "umount", "-l", mp, check=False)
    for _attempt in range(10):             # the device can stay busy for a moment after the unmount
        if not Path(f"/dev/mapper/{name}").exists() or sh("cryptsetup", "close", name, check=False).returncode == 0:
            if name in STATE["opened"]:
                STATE["opened"].remove(name)
            return True
        time.sleep(1)
    return False


def shred_keys() -> None:
    """The extra drives' keyfiles on the live system (copies of what's on the new, encrypted system)."""
    if KEYS_DIR.is_dir():
        for f in KEYS_DIR.iterdir():
            sh("shred", "-u", f, check=False)
        try:
            KEYS_DIR.rmdir()
        except OSError:
            pass
    STATE["keys_dir"] = False


def restore_secure_boot() -> bool:
    snapshot = STATE.get("signed_boot_files") or {}
    if not snapshot:
        return True
    if not STATE["mounted"]:
        log("cleanup: the startup partition is no longer mounted; its files were left alone")
        return False
    try:
        signed_boot.restore_loader(snapshot)
        STATE["signed_boot_files"] = {}
        return True
    except (OSError, ValueError) as error:
        log("cleanup: signed startup files could not be restored: " + str(error))
        return False


def undo_attempt() -> bool:
    """After a failure: undo what this attempt set up, and only that, so the next try starts clean without a
    restart. Never raises (a cleanup problem must not hide the real one). -> everything was undone."""
    clean = True
    try:
        clean = restore_secure_boot()
        if STATE["mounted"]:
            # the half-built system must not keep the installer's no-password sudo rule
            leftover = MNT / "etc/sudoers.d/99-starchaser-installing"
            if leftover.exists():
                leftover.unlink()
                log("removed the installer's temporary sudo rule from the unfinished system")
            if not release_mnt():
                log(f"cleanup: {MNT} stayed busy")
                return False
        pdir, mp = PEEK_DIR / str(os.getpid()), f"{PEEK_MAPPER}-{os.getpid()}"
        if subprocess.run(["findmnt", str(pdir)], capture_output=True).returncode == 0:
            sh("umount", pdir, check=False)
        for name in reversed(list(STATE["opened"])):          # newest first
            if not close_crypt(name):
                log(f"cleanup: the encrypted volume {name} stayed open")
                return False
        if mapper_exists(mp):
            sh("cryptsetup", "close", mp, check=False)
        # kept encrypted partitions: remove exactly the key this attempt added (the one its own keyfile opens); the
        # person's passphrase is never touched
        for dev, key in reversed(list(STATE["keyslots"])):
            if sh("cryptsetup", "luksRemoveKey", dev, key, check=False).returncode == 0:
                STATE["keyslots"].remove((dev, key))
            else:
                clean = False
        for f in ("/run/starchaser-tmpkey",):
            if Path(f).exists():
                sh("shred", "-u", f, check=False)
        if STATE["new_parts"]:
            by_disk = {}
            for disk, node, uid in STATE["new_parts"]:
                by_disk.setdefault(disk, []).append((node, uid))
            for disk, made in by_disk.items():
                now = partition_ids(disk)
                for node, uid in made:
                    if now.get(node) != uid:             # not the partition this attempt made: leave it alone
                        continue
                    n = re.search(r"(\d+)$", node).group(1)
                    if sh("sgdisk", "-d", n, disk, check=False).returncode != 0:
                        clean = False
                sh("partprobe", disk, check=False)
            sh("udevadm", "settle", check=False)
            STATE["new_parts"] = []
        # this attempt's disk key is no use now: with a new partition, the encrypted volume went with it; erasing
        # the whole drive, the volume stays on disk but holds only a half-built system the next try wipes anyway
        if clean and Path("/run/starchaser-recovery-key.txt").exists():
            sh("shred", "-u", "/run/starchaser-recovery-key.txt", check=False)
        if clean:
            shred_keys()
    except Exception:
        log("cleanup failed:\n" + traceback.format_exc())
        return False
    return clean


# --------------------------------------------------------------------------------------------- other drives (run)
def new_keyfile(name: str) -> Path:
    """A random 64-byte key for an extra encrypted volume, on the live system's tmpfs (0600 in a 0700 folder)."""
    old = os.umask(0o077)
    try:
        KEYS_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
        STATE["keys_dir"] = True
        k = KEYS_DIR / f"{name}.key"
        k.write_bytes(os.urandom(64))
        os.chmod(k, 0o600)
    finally:
        os.umask(old)
    return k


def install_keyfile(name: str) -> str:
    """Copy a volume's keyfile into the new system (/etc/cryptsetup-keys.d, root only), where systemd-cryptsetup
    reads it once the encrypted system is open: nothing goes into the initramfs. -> its path there."""
    dst = MNT / "etc/cryptsetup-keys.d"
    old = os.umask(0o077)
    try:
        dst.mkdir(mode=0o700, parents=True, exist_ok=True)
        os.chmod(dst, 0o700)
        shutil.copyfile(KEYS_DIR / f"{name}.key", dst / f"{name}.key")
        os.chmod(dst / f"{name}.key", 0o600)
        if os.geteuid() == 0:
            os.chown(dst, 0, 0)
            os.chown(dst / f"{name}.key", 0, 0)
    finally:
        os.umask(old)
    return f"/etc/cryptsetup-keys.d/{name}.key"


def current_id(path: str) -> str:
    """A drive's id as disks() makes it, read again now (drive_identity)."""
    for d in _lsblk().get("blockdevices", []):
        if d.get("path") == path and d.get("type") == "disk":
            return drive_identity(d)
    return ""


def recheck_drive(path: str, want_id: str, whole: bool = False) -> None:
    """Just before a drive is written: it is still the drive the plan was made for (a USB drive unplugged and
    another plugged in during the minutes before can take over its name) and not the installer's own USB stick.
    whole: the whole drive is about to be wiped, so nothing on the live system may use it either (mounted, active
    swap, opened); a drive that only gains or loses some partitions may keep others in use, and plan() checks
    those one by one. Fails before anything on it changes."""
    if path in live_disks():
        fail(f"{path} is now the installer's own USB stick, so nothing on it was changed. Look again on the Drive step.")
    if want_id and current_id(path) != want_id:
        fail(f"The drive at {path} isn't the one chosen (it may have been unplugged), so nothing on it was changed. "
             "Look again on the Drive step.")
    node = next((d for d in _lsblk().get("blockdevices", []) if d.get("path") == path), None)
    if node is None:
        fail(f"{path} isn't here any more, so nothing on it was changed. Look again on the Drive step.")
    if whole and _in_use(node, active_swaps()):
        fail(f"Something on {path} is in use right now (mounted, swap or opened), so nothing on it was changed. "
             "Restart the computer and try again.")


def apply_tables(tables: list, vols: list) -> None:
    """The partition changes on other drives (files/home drives: a fresh table and one partition; Advanced: start
    over, delete, retype, create), each drive's table saved first. Every partition made is recorded by its unique
    id, so a failure removes exactly those."""
    for t in tables:
        disk = t["disk"]
        recheck_drive(disk, t.get("id", ""), whole=bool(t["new_table"]))
        TABLES_DIR.mkdir(parents=True, exist_ok=True)
        dump = subprocess.run(["sfdisk", "--dump", disk], capture_output=True, text=True).stdout
        (TABLES_DIR / (Path(disk).name + ".sfdisk")).write_text(dump)
        log(f"partition table of {disk} before any change:\n" + dump)
        before = partition_table(disk)
        if t["new_table"]:
            STATE["lost"] = STATE["lost"] or ("manual" if any(v.get("role") in ("root", "esp", "boot", "system", "swap")
                                                               for v in vols) else "drives")
            for p in before.get("partitions", []):
                if p.get("node"):
                    sh("wipefs", "-af", p["node"], check=False)
            sh("wipefs", "-af", disk)
            sh("sgdisk", "--zap-all", disk)
            old_ids = set()
        else:
            ids = partition_ids(disk, before)
            if not before or "" in ids.values():
                fail(f"Couldn't read the list of partitions on {disk}, so nothing on it was changed. Try again.")
            for dl in t["delete"]:
                if not _same_uuid(dl["uuid"], ids.get(dl["partition"], "")):
                    fail(f"Partition {dl['number']} on {disk} changed since the plan was made, so it wasn't deleted.")
                STATE["lost"] = "manual"
                sh("sgdisk", "-d", str(dl["number"]), disk)
            for rt in t.get("retype", []):
                if not _same_uuid(rt["uuid"], ids.get(rt["partition"], "")):
                    fail(f"Partition {rt['number']} on {disk} changed since the plan was made, so it wasn't changed.")
                sh("sgdisk", "-t", f"{rt['number']}:{rt['code']}", disk)
            old_ids = {u.upper() for u in ids.values()}
        for c in t["create"]:
            n = c["number"]
            try:
                sh("sgdisk", "-n", f"{n}:{c['start'] or 0}:{c['end'] or 0}", "-t", f"{n}:{c['code']}",
                   "-c", f"{n}:{c['name']}", disk)
            finally:
                now = partition_table(disk).get("partitions", [])
                known = {u for _, _, u in STATE["new_parts"]}
                for p in now:
                    if p.get("node") and p.get("uuid") and p["uuid"].upper() not in old_ids and p["uuid"] not in known:
                        STATE["new_parts"].append((disk, p["node"], p["uuid"]))
            node = part_path(disk, n)
            v = vols[c["vol"]]
            v["partition"] = v["dev"] = node
            v["uuid"] = next((p["uuid"] for p in partition_table(disk).get("partitions", []) if p.get("node") == node), "")
        sh("partprobe", disk, check=False)
        sh("udevadm", "settle")
        time.sleep(2)
        for c in t["create"]:
            if not dev_exists(vols[c["vol"]]["partition"]):
                fail(f"The new partitions on {disk} didn't appear.")


def open_volumes(vols: list, enc: str, passphrase: str) -> None:
    """New encrypted volumes other than / (a files or home drive, Advanced partitions): a random keyfile opens each
    (it goes into the encrypted system later), plus a second key so the drive can be opened even without this
    system: the passphrase, or in TPM mode the same disk key the system got."""
    for v in vols:
        v.setdefault("dev", v["partition"])
    todo = [v for v in vols if v["kind"] in ("new", "format") and v.get("encrypt") and v.get("role") not in ("root", "swap")]
    if not todo:
        return
    emit(event="phase", phase="encrypt", label="Locking your other drives")
    second = passphrase if enc == "passphrase" else ""
    if enc in ("tpm", "tpm-pin"):
        try:
            second = Path("/run/starchaser-recovery-key.txt").read_text().strip()
        except OSError:
            second = ""
    for v in todo:
        key = new_keyfile(v["mapper"])
        sh("cryptsetup", "luksFormat", "--type", "luks2", "--batch-mode", *KEYFILE_PBKDF, "--key-file", key, v["partition"])
        if second:
            extra = KEYS_DIR / f"{v['mapper']}.second"
            old = os.umask(0o077)
            extra.write_text(second)                   # as typed: no newline (a key file is read whole)
            os.umask(old)
            try:
                sh("cryptsetup", "luksAddKey", "--key-file", key, v["partition"], extra)
            finally:
                sh("shred", "-u", extra, check=False)
        sh("cryptsetup", "open", "--key-file", key, v["partition"], v["mapper"])
        STATE["opened"].append(v["mapper"])
        v["dev"] = f"/dev/mapper/{v['mapper']}"


def format_volumes(vols: list) -> None:
    """File systems on the new and reformatted volumes (except /, which the system's own setup makes)."""
    todo = [v for v in vols if v["kind"] in ("new", "format") and v.get("role") != "root"]
    if not todo:
        return
    emit(event="phase", phase="format", label="Making the file systems")
    for v in todo:
        dev, fs, label = v["dev"], v["fs"], v.get("label") or ""
        if v["kind"] == "format":
            STATE["lost"] = "manual"
        if fs == "fat32":
            sh("mkfs.fat", "-F32", "-n", "ESP" if v.get("esp") else "SCBOOT", dev)
        elif fs == "btrfs":
            sh("mkfs.btrfs", "-f", *(["-L", label] if label else []), dev)
            if v.get("subvol"):
                tmp = NEWVOL_DIR
                tmp.mkdir(parents=True, exist_ok=True)
                sh("mount", dev, tmp)
                try:
                    sh("btrfs", "subvolume", "create", tmp / v["subvol"])
                finally:
                    sh("umount", tmp, check=False)
        elif fs == "ext4":
            sh("mkfs.ext4", "-F", *(["-m", "0"] if v.get("role") == "data" else []), *(["-L", label[:16]] if label else []), dev)
        elif fs == "xfs":
            sh("mkfs.xfs", "-f", *(["-L", label[:12]] if label else []), dev)
        elif fs == "swap":
            if v.get("encrypt"):
                sh("wipefs", "-af", dev)                 # a new random key each start makes it (crypttab "swap")
            else:
                sh("mkswap", dev)


def mount_manual(vols: list, root_dev: str) -> None:
    """Advanced: / (btrfs gets the usual subvolumes, minus the ones a separate partition replaces), then the other
    system mount points, parents first. Data partitions are mounted later (their fstab lines are the engine's)."""
    root = next(v for v in vols if v.get("role") == "root")
    emit(event="phase", phase="format", label="Making the file system")
    o = "noatime,compress=zstd:3,space_cache=v2"
    if root["fs"] == "btrfs":
        sh("mkfs.btrfs", "-f", "-L", "starchaser", root_dev)
    elif root["fs"] == "ext4":
        sh("mkfs.ext4", "-F", "-L", "starchaser", root_dev)
    else:
        sh("mkfs.xfs", "-f", "-L", "starchaser", root_dev)
    if root["kind"] == "format":
        STATE["lost"] = "manual"
    STATE["mounted"] = True
    sep = {v["mount"] for v in vols if v["mount"]}
    if root["fs"] == "btrfs":
        subs = [("", "@"), (".snapshots", "@snapshots")]
        if "/home" not in sep:
            subs.append(("home", "@home"))
        if "/var" not in sep:
            subs += [("var/log", "@log"), ("var/cache/pacman/pkg", "@pkg")]
        subs += [(sub, sv) for sub, sv in BULK_SUBVOLUMES
                 if not any('/' + sub == p or ('/' + sub).startswith(p + '/') for p in sep if p != '/')]
        sh("mount", root_dev, MNT)
        for _, sv in subs:
            sh("btrfs", "subvolume", "create", MNT / sv)
        sh("umount", MNT)
        sh("mount", "-o", f"{o},subvol=@", root_dev, MNT)
        for sub, sv in subs[1:]:
            (MNT / sub).mkdir(parents=True, exist_ok=True)
            sh("mount", "-o", f"{o},subvol={sv}", root_dev, MNT / sub)
    else:
        sh("mount", root_dev, MNT)
    later = [v for v in vols if v["mount"] and v["mount"] != "/" and v.get("role") in ("esp", "boot", "system")]
    for v in sorted(later, key=lambda v: (v["mount"].count("/"), v["mount"])):
        target = MNT / v["mount"].lstrip("/")
        target.mkdir(parents=True, exist_ok=True)
        dev = v.get("dev") or v["partition"]
        if v["fs"] == "fat32":
            sh("mount", "-o", "fmask=0077,dmask=0077", dev, target)
        elif v["fs"] == "btrfs" and v.get("subvol"):
            sh("mount", "-o", f"subvol={v['subvol']}", dev, target)
        else:
            sh("mount", dev, target)


def drives_phase(a: dict, vols: list, enc: str) -> None:
    """After the base system: kept encrypted partitions get a key that opens them with the system (added, never
    replacing their passphrase), every extra volume's keyfile goes into the encrypted system with a crypttab line,
    and new data volumes are mounted so the account can be given them once it exists."""
    todo = [v for v in vols if v.get("role") not in ("root", "esp", "boot")]
    if not todo:
        return
    emit(event="phase", phase="drives", label="Setting up your other drives")
    secrets = {e.get("partition"): e.get("passphrase", "") for e in a.get("keep") or []}
    for md in (a.get("manual") or {}).get("drives") or []:
        for e in md.get("existing") or []:
            secrets[e.get("partition")] = e.get("passphrase", "")
    tab = []
    for v in todo:
        m = v["mapper"]
        if v["kind"] == "keep" and v.get("luks"):
            if v.get("keyfile"):
                pw = secrets.get(v["partition"], "")
                if sh("cryptsetup", "open", "--test-passphrase", "--key-file=-", v["partition"], input=pw,
                      check=False).returncode != 0:
                    fail(f"The disk key for {v['name'] or v['mount']} didn't open it this time. Nothing on it was changed.")
                key = new_keyfile(m)
                # ADD a key (the passphrase on stdin proves the right to); never luksChangeKey/KillSlot/RemoveKey
                sh("cryptsetup", "luksAddKey", *KEYFILE_PBKDF, "--key-file=-", v["partition"], key, input=pw)
                STATE["keyslots"].append((v["partition"], str(key)))
                tab.append(f"{m} UUID={v['luks_uuid']} {install_keyfile(m)} luks,nofail")
            else:
                tab.append(f"{m} UUID={v['luks_uuid']} none luks,nofail")
        elif v["fs"] == "swap" and v.get("encrypt"):
            tab.append(f"{m} PARTUUID={v['uuid'].lower()} /dev/urandom swap,cipher=aes-xts-plain64,size=512")
        elif v["kind"] != "keep" and v.get("encrypt"):
            luks_uuid = sh("cryptsetup", "luksUUID", v["partition"]).stdout.strip()
            tab.append(f"{m} UUID={luks_uuid} {install_keyfile(m)} luks,discard" + (",nofail" if v.get("nofail") else ""))
        if v.get("role") == "data" and v["mount"]:
            target = MNT / v["mount"].lstrip("/")
            target.mkdir(parents=True, exist_ok=True)
            if v["kind"] != "keep":                       # kept ones are never mounted during the install
                sh("mount", v["dev"], target)
    if tab:
        with open(MNT / "etc/crypttab", "a") as f:
            f.write("\n# Starchaser installer: other drives (keyfiles in /etc/cryptsetup-keys.d, read after the system "
                    "is unlocked)\n" + "\n".join(tab) + "\n")


def fstab_line(v: dict, uuid: str, uid: int, gid: int) -> str:
    """A data or kept volume's fstab line: nofail (Starchaser starts without it), a wait for it, and for exFAT/NTFS
    the account's own ids (they have no owners of their own). The wait: 10 s for a plain partition (an unplugged
    drive gives up soon); a locked one shows up only once it's unlocked, which takes longer (several drives opening
    at once), and one without a keyfile waits for its passphrase to be typed at startup. nofail mounts don't hold up
    the start either way."""
    wait = "10s" if not v.get("mapper") else "90s" if v.get("keyfile") else "infinity"
    base = f"nofail,x-systemd.device-timeout={wait}"
    fs = v["fs"]
    if fs == "exfat":
        return f"UUID={uuid} {v['mount']} exfat uid={uid},gid={gid},umask=022,{base} 0 0"
    if fs == "ntfs":
        return f"UUID={uuid} {v['mount']} ntfs3 uid={uid},gid={gid},umask=022,windows_names,{base} 0 0"
    opts = f"noatime,{base}" if v.get("nofail", True) else "noatime"
    return f"UUID={uuid} {v['mount']} {fs} {opts} 0 {2 if fs == 'ext4' else 0}"


def drives_config(a: dict, vols: list) -> None:
    """After the account exists: data and kept volumes' fstab lines (written here, not by genfstab, for nofail and
    the account's ids), swap, and new data volumes given to the account."""
    todo = [v for v in vols if v.get("role") in ("data", "swap")]
    u = a["user"]["username"]
    if any(v.get("role") == "system" and v["mount"] == "/home" and v["kind"] == "keep" for v in vols):
        # a kept /home with this person's folder already in it: its files stay and become theirs. The desktop
        # setup replaces its own folders there (.config/quickshell/<cockpit, settings, ...>, .config/keybinds):
        # copies of what was there go to .local/share/starchaser/before-install first
        if (MNT / "home" / u).is_dir():
            chroot(f"""cd /home/{u}
for p in .config/quickshell .config/keybinds; do
  if [ -e "$p" ]; then mkdir -p .local/share/starchaser/before-install && cp -a "$p" .local/share/starchaser/before-install/; fi
done
chown -R {u}:{u} /home/{u}""")
    if not todo:
        return
    ids = chroot(f"id -u {u}; id -g {u}").stdout.split()
    uid, gid = (int(ids[0]), int(ids[1])) if len(ids) >= 2 else (1000, 1000)
    lines = []
    for v in todo:
        if v["fs"] == "swap":
            dev = f"/dev/mapper/{v['mapper']}" if v.get("encrypt") else \
                "UUID=" + sh("blkid", "-s", "UUID", "-o", "value", v["dev"]).stdout.strip()
            lines.append(f"{dev} none swap defaults 0 0")
            continue
        uuid = v.get("fs_uuid") if v["kind"] == "keep" else sh("blkid", "-s", "UUID", "-o", "value", v["dev"]).stdout.strip()
        if not uuid:
            fail(f"Couldn't read the id of {v['name'] or v['mount']}, so it can't be set up to open at startup.")
        lines.append(fstab_line(v, uuid, uid, gid))
        if v.get("owner"):
            chroot(f"chown {u}:{u} {shlex.quote(v['mount'])}")
    with open(MNT / "etc/fstab", "a") as f:
        f.write("\n# Starchaser installer: other drives (nofail: Starchaser starts without them)\n" + "\n".join(lines) + "\n")


def bookmarks(a: dict, vols: list) -> None:
    """A bookmark in Files for each data drive and kept partition (after the desktop setup, which could otherwise
    replace the file)."""
    marks = [v for v in vols if v.get("bookmark") and v["mount"]]
    if not marks:
        return
    import urllib.parse
    u = a["user"]["username"]
    f = MNT / f"home/{u}/.config/gtk-3.0/bookmarks"
    f.parent.mkdir(parents=True, exist_ok=True)
    have = f.read_text().splitlines() if f.exists() else []
    for v in marks:
        line = f"file://{urllib.parse.quote(v['mount'])} {v['name'] or v['mount'].rsplit('/', 1)[-1]}"
        if line not in have:
            have.append(line)
    f.write_text("\n".join(have) + "\n")
    chroot(f"chown {u}:{u} /home/{u}/.config /home/{u}/.config/gtk-3.0 /home/{u}/.config/gtk-3.0/bookmarks")


ATTEMPT = "==================== install attempt"


def log_tail(n: int = 30) -> list:
    """The last lines of this attempt's log (already free of the disk key), for the details on screen."""
    try:
        lines = LOG.read_text(errors="replace").splitlines()
    except OSError:
        return []
    start = max((i for i, l in enumerate(lines) if ATTEMPT in l), default=0)      # this attempt only
    return [l for l in lines[start + 1:] if not l[9:].startswith("@@")][-n:]


PHASE_WORDS = {"": "getting ready", "prepare": "getting ready", "shrink": "making room on the drive",
               "partition": "partitioning", "encrypt": "encrypting", "format": "making the file system",
               "mirrors": "finding download servers", "download": "downloading", "base": "installing the base system",
               "drives": "setting up your other drives", "configure": "setting up the system",
               "boot": "setting up startup", "desktop": "installing the desktop",
               "finish": "finishing"}


def keyring_ready() -> None:
    """Wait for the carried keyrings before any drive change. The live clock need not come from the internet."""
    st = subprocess.run(["systemctl", "show", "-p", "LoadState,ActiveState", "pacman-init.service"],
                        capture_output=True, text=True).stdout
    if "LoadState=loaded" not in st:
        return                                           # not the live ISO's unit (a test run elsewhere)
    deadline = time.monotonic() + 90
    said = False
    while "ActiveState=active" not in st:
        if "ActiveState=failed" in st or time.monotonic() > deadline:
            fail("The package keys could not be prepared. Check the date in firmware settings or make a new installer stick. Nothing on the drive was changed.")
        if not said:
            emit(event="phase", phase="prepare", label="Getting the package keys ready")
            said = True
        time.sleep(2)
        st = subprocess.run(["systemctl", "show", "-p", "LoadState,ActiveState", "pacman-init.service"],
                            capture_output=True, text=True).stdout


def password_code(username: str) -> str:
    """The new account's password recovery code (decided 2026-11-07 #20: shown at setup, accepted by the lock screen
    to set a new password): only its hash goes onto the new system, the code itself to the screen once. Not having
    one never stops the install; Settings > Users makes one later."""
    try:
        import recovery_code
        uid = next(int(f[2]) for f in (l.split(":") for l in (MNT / "etc/passwd").read_text().splitlines()) if f[0] == username)
        code = recovery_code.new_code()
        recovery_code.save(MNT, username, uid, code)
        log("  (password recovery code made; shown on screen, not logged)")
        return code
    except Exception as e:                                   # (a missing module on an older ISO, a write error)
        log(f"  no password recovery code: {e}")
        return ""


def terminate_install_children():
    """Stop commands before releasing their mounts; a child must not keep writing during undo."""
    def children(pid):
        try:
            ids = [int(n) for n in Path(f"/proc/{pid}/task/{pid}/children").read_text().split()]
        except (OSError, ValueError):
            return []
        return [child for n in ids for child in children(n)] + ids
    pids = children(os.getpid())
    for pid in pids:
        try:
            os.kill(pid, signal.SIGTERM)
        except ProcessLookupError:
            pass
    if pids:
        time.sleep(0.5)
    for pid in pids:
        try:
            os.kill(pid, signal.SIGKILL)
        except ProcessLookupError:
            pass
    for pid in pids:
        try:
            os.waitpid(pid, 0)
        except ChildProcessError:
            pass


def install_signal(signum, frame):
    # Ignore repeated termination while undo is releasing mounts and keys.
    for sig in (signal.SIGTERM, signal.SIGHUP):
        signal.signal(sig, signal.SIG_IGN)
    terminate_install_children()
    clean = undo_attempt()
    emit(event="done", ok=False, error="The install was stopped. Mounts and keys from this attempt were cleaned up. Erased or formatted files can't be restored." if clean
         else "The install was stopped. Restart before trying again.", retry=clean)
    raise SystemExit(128 + signum)


def install_signals():
    for sig in (signal.SIGTERM, signal.SIGHUP):
        signal.signal(sig, install_signal)


def run(path: str) -> None:
    """The install, from an answers file. Whatever happens, it ends with one "done" event: on a failure, after
    undoing what this attempt set up (so the next try needs no restart), with the log's last lines to show."""
    if os.geteuid() != 0:                    # before the answers file or the log are touched
        sys.exit("Run it as root: sudo starchaser-install run <answers.json>")
    LOG.parent.mkdir(parents=True, exist_ok=True)
    LOG.touch(mode=0o600)
    os.chmod(LOG, 0o600)
    log(f"{ATTEMPT} {time.strftime('%Y-%m-%d')} " + "=" * 20)            # earlier attempts stay above it
    global _lock
    try:
        p = Path(path)
        try:
            a = with_site(json.loads(p.read_text()))
        finally:
            try:
                p.unlink()                                   # it holds passwords: read once, then gone
            except OSError:
                pass
        # one install at a time, from before the plan is checked to the end: two runs could both find /mnt free and
        # then partition the same drive, or mount over each other. Held until this process ends.
        _lock = open(LOCK, "w")
        try:
            fcntl.flock(_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            _lock.close()
            _lock = None
            raise Busy("Another install is already running on this computer. Wait for it to finish.") from None
        Path("/run/starchaser-installer-success").unlink(missing_ok=True)
        install_signals()
        warning = install(a)
    except Busy as e:
        # nothing of this attempt to undo, and the other install's work must not be touched
        log("stopped: " + str(e))
        emit(event="done", ok=False, error=str(e), log=str(LOG), retry=True)   # "Try again" once it ends; a restart would stop it
        sys.exit(1)
    except CommandFailed as e:
        log(str(e))
        error = f"Something went wrong while {PHASE_WORDS.get(PHASE, 'installing')}. The details are below."
    except Stop as e:
        error = str(e)
    except Exception:
        log(traceback.format_exc())
        error = f"Something went wrong while {PHASE_WORDS.get(PHASE, 'installing')}. The details are below."
    else:
        Path("/run/starchaser-installer-success").touch(mode=0o644)
        log("finished" + (": " + warning if warning else ""))
        if PASSWORD_CODE:
            emit(event="password-code", code=PASSWORD_CODE)
        if SECURE_BOOT_CODE:
            emit(event="secure-boot-code", code=SECURE_BOOT_CODE)
        emit(event="done", ok=True, error="", warning=warning, hardware=HARDWARE_REPORT, log=str(LOG), recovery=a.get("encrypt") != "none")
        return
    log("stopped: " + error)
    clean = undo_attempt()
    if clean and STATE["lost"] == "manual":
        error += " Partitions you chose to delete or format stay that way; everything else was undone."
    elif clean and STATE["lost"] == "drives":
        error += " Drives you chose to erase stay empty; everything else was undone."
    error += " You can try again." if clean else " Restart the computer, then try again."
    emit(event="log", lines=log_tail())
    emit(event="done", ok=False, error=error, log=str(LOG), retry=clean)
    sys.exit(1)


def recovery_environment():
    """An undersized boot partition leaves the stick as the recovery path."""
    tool = Path('/usr/lib/starchaser/bin/starchaser-rescue')
    if not tool.is_file():
        return
    result = subprocess.run([str(tool), '--install-environment', str(MNT / 'boot'),
                             '--installed-root', str(MNT)], capture_output=True, text=True)
    if result.returncode:
        emit(event='log', lines=['On-disk recovery was not added: ' + (result.stderr or result.stdout).strip(),
                                 'Keep the recovery stick. It provides the same recovery tools.'])


def prepare_secure_boot():
    """Only a new installation made with enforcement on opts into managed signed startup."""
    if not secure_boot():
        return
    problem = signed_boot.installer_ready()
    if problem:
        fail(problem)
    signed_boot.initialize(MNT)
    chroot("systemctl mask systemd-boot-update.service")
    chroot("python3 /usr/local/lib/starchaser/secure_boot.py refresh")


def queue_secure_boot():
    global SECURE_BOOT_CODE
    if signed_boot.configuration(MNT) is not None:
        SECURE_BOOT_CODE = signed_boot.request_enrollment(MNT)


@live_package_source()
def install(a: dict) -> str:
    """-> a warning for the finished screen ("" when there's none)."""
    if not Path("/run/archiso").is_dir() and not os.environ.get("STARCHASER_INSTALL_ANYWHERE"):
        fail("This isn't the Starchaser installer's own system: refusing to touch drives.")
    a.setdefault("encrypt", default_encryption(disks()))
    pl = plan(a)
    log("plan: " + json.dumps({k: v for k, v in pl.items() if k != "layout"}))
    if not pl["ok"]:
        fail(" ".join(pl["errors"]))
    lay = pl["layout"]
    if a.get("account_setup") == "later":
        # A random, locked staging account runs desktop setup in the target only. It never survives the install.
        a = {**a, "user": {"name": "Setup", "username": "starchaser-setup", "password": secrets.token_urlsafe(48)}, "autologin": False}
    emit(event="plan", steps=pl["steps"])
    # the live system's writable layer is RAM (archiso's default 256 MB fills up): give it room
    if Path("/run/archiso/cowspace").is_dir():
        sh("mount", "-o", "remount,size=2G", "/run/archiso/cowspace", check=False)
    if subprocess.run(["findmnt", str(MNT)], capture_output=True).returncode == 0:
        fail(f"{MNT} is already in use by something else. Restart the computer and try again.")
    if a.get("fleet_profile"):
        fleet_wifi(a["fleet_profile"])
    keyring_ready()
    mode, enc = a.get("mode", "erase"), a.get("encrypt", "tpm")       # plan() reads a missing mode as erase too
    vols = lay.get("volumes") or []
    repo = Path(a.get("repo") or "/usr/share/starchaser/repo")
    preflight_packages(a, repo, lay.get("extra_pkgs") or [])
    if enc != "none":
        mapper_free()                    # checked again right before encrypting; here, before any drive is touched
    if mode == "manual":
        return install_manual(a, lay, enc, repo)
    disk = a["disk"]
    recheck_drive(disk, a.get("disk_id", ""), whole=mode == "erase")
    if mode == "shrink":
        shrink_partition(disk, lay["shrink"])
    esp, xb, root_part = new_partitions(disk, mode, lay)
    if lay.get("tables"):
        apply_tables(lay["tables"], vols)           # files and home drives: a fresh table, one partition each
    root = encrypt(root_part, enc, a.get("passphrase", ""), a.get("pin", ""))
    open_volumes(vols, enc, a.get("passphrase", ""))
    format_volumes(vols)
    home = next((v["dev"] for v in vols if v.get("role") == "home"), "")
    filesystems(root, esp, xb, mode, home=home)
    pacstrap(cpu_vendor(), repo, lay.get("extra_pkgs"), channel=a.get("channel", "release"), live=a.get("_live_files"), lookup=not a.get("no_lookup"))
    drives_phase(a, vols, enc)
    configure(a, root_part, enc, dual=bool(xb), rtc_local=bool(lay.get("rtc_local")))
    drives_config(a, vols)
    trusted = trust_install_network({**a, "ssh": True, "trust_network": True} if a.get("fleet_profile") else a)          # before the desktop setup, which makes the firewall's first policy
    later = desktop(a)
    prepare_secure_boot()
    boot_menu(bool(xb))
    recovery_environment()
    hardware_warning = hardware_setup()
    login_keyring(a)
    bookmarks(a, vols)
    return " ".join(w for w in (finish(a, enc, dual=bool(xb)), later, trusted, hardware_warning) if w)


def install_manual(a: dict, lay: dict, enc: str, repo: Path) -> str:
    """Advanced: the partition plan exactly as checked, then the same system setup."""
    vols = lay["volumes"]
    emit(event="phase", phase="partition", label="Partitioning")
    apply_tables(lay["tables"], vols)
    # partitions to be reformatted on drives whose table doesn't change: still the same drive and partition
    changed = {t["disk"] for t in lay["tables"]}
    for path, want in {v["disk"]: next((md.get("id", "") for md in (a.get("manual") or {}).get("drives") or []
                                        if md.get("disk") == v["disk"]), "")
                       for v in vols if v["kind"] == "format" and v["disk"] not in changed}.items():
        recheck_drive(path, want)
    for v in vols:
        if v["kind"] == "format" and not _same_uuid(v["uuid"], partition_ids(v["disk"]).get(v["partition"], "")):
            fail(f"Partition {v['number']} on {v['disk']} changed since the plan was made, so it wasn't formatted.")
    root = next(v for v in vols if v.get("role") == "root")
    root_dev = encrypt(root["partition"], enc, a.get("passphrase", ""), a.get("pin", "")) if root.get("encrypt") else root["partition"]
    root["dev"] = root_dev
    open_volumes(vols, enc, a.get("passphrase", ""))
    format_volumes(vols)
    mount_manual(vols, root_dev)
    pacstrap(cpu_vendor(), repo, lay.get("extra_pkgs"), channel=a.get("channel", "release"), live=a.get("_live_files"), lookup=not a.get("no_lookup"))
    drives_phase(a, vols, enc)
    configure(a, root["partition"], enc, dual=bool(lay.get("dual")), rtc_local=bool(lay.get("rtc_local")),
              root_fs=root["fs"])
    drives_config(a, vols)
    trusted = trust_install_network({**a, "ssh": True, "trust_network": True} if a.get("fleet_profile") else a)
    later = desktop(a)
    prepare_secure_boot()
    boot_menu(bool(lay.get("dual")))
    recovery_environment()
    hardware_warning = hardware_setup()
    login_keyring(a)
    bookmarks(a, vols)
    return " ".join(w for w in (finish(a, enc, dual=bool(lay.get("dual"))), later, trusted, hardware_warning) if w)


# --------------------------------------------------------------------------------------------- the text installer
KEYBOARDS = [(row["label"], row["xkb"], row["console"]) for row in install_language.keyboards()]
LOCALES = [("English (United States)", "en_US.UTF-8"), ("English (United Kingdom)", "en_GB.UTF-8"),
           ("English (Canada)", "en_CA.UTF-8"), ("English (Australia)", "en_AU.UTF-8"), ("Deutsch", "de_DE.UTF-8"),
           ("Français", "fr_FR.UTF-8"), ("Español", "es_ES.UTF-8"), ("Italiano", "it_IT.UTF-8"),
           ("Português (Brasil)", "pt_BR.UTF-8"), ("Nederlands", "nl_NL.UTF-8"), ("Svenska", "sv_SE.UTF-8"),
           ("Polski", "pl_PL.UTF-8"), ("Chinese (Simplified)", "zh_CN.UTF-8"), ("Chinese (Traditional)", "zh_TW.UTF-8"),
           ("Japanese", "ja_JP.UTF-8"), ("Korean", "ko_KR.UTF-8")]


def _speech() -> bool:
    """Started from the boot menu's "with speech" entry: a screen reader reads the console aloud."""
    try:
        return "accessibility=on" in Path("/proc/cmdline").read_text()
    except OSError:
        return False


# with speech: plain text only (no colors, no line drawing, no progress bar redrawn in place: a screen reader
# would read every redraw)
SPEECH = _speech()
P, M, E, B, R = ("",) * 5 if SPEECH else \
    ("\033[38;2;157;124;255m", "\033[38;2;106;98;144m", "\033[38;2;255;107;139m", "\033[1m", "\033[0m")


def title(t: str) -> None:
    if SPEECH:
        print(f"\n{t}.")
        return
    print(f"\n{P}{B}── {t} {'─' * max(0, 60 - len(t))}{R}")


def note(t: str) -> None:
    import textwrap
    print(M + textwrap.fill(t, 76) + R)


def ask(prompt: str, default: str = "") -> str:
    v = input(f"{prompt}{f' [{default}]' if default else ''}: ").strip()
    return v or default


def choose(items: list, default: int = 0) -> int:
    """items: labels. Returns the index picked (1-based on screen)."""
    for i, t in enumerate(items, 1):
        print(f"  {P}{i:>2}{R}  {t}")
    while True:
        v = ask("Number", str(default + 1))
        if v.isdigit() and 1 <= int(v) <= len(items):
            return int(v) - 1
        print(f"{E}Pick a number from 1 to {len(items)}.{R}")


def yes(prompt: str, default: bool) -> bool:
    v = ask(prompt + (" (Y/n)" if default else " (y/N)")).lower()
    return default if not v else v.startswith("y")


def secret(prompt: str, minimum: int) -> str:
    import getpass
    while True:
        a1 = getpass.getpass(f"{prompt}: ")
        if len(a1) < minimum:
            print(f"{E}At least {minimum} characters.{R}")
            continue
        if getpass.getpass("Again: ") == a1:
            return a1
        print(f"{E}Those didn't match. Once more.{R}")


def shrink_range(p: dict) -> tuple:
    """(least, most, suggested) whole GB a partition being shrunk can keep, each one plan() accepts once turned
    into MiB by keep_mib(); () when there's no such number."""
    lo_b = -(-(p["shrink"]["min"] + GIB) // MIB) * MIB          # rounded up and down to whole MiB, as sent
    hi_b = (p["size"] - required_free()) // MIB * MIB
    lo, hi = math.ceil(lo_b / 1e9), math.floor(hi_b / 1e9)
    if lo > hi:
        return ()
    # a sensible start: Starchaser gets half of what's free in it, at least 60 GB when possible
    want = (p["size"] - max(60e9, (p["size"] - p["shrink"]["min"]) / 2)) / 1e9
    return lo, hi, min(hi, max(lo, round(want)))


def keep_mib(p: dict, keep_gb: int) -> int:
    lo_b = -(-(p["shrink"]["min"] + GIB) // MIB) * MIB
    hi_b = (p["size"] - required_free()) // MIB * MIB
    return max(lo_b // MIB, min(hi_b // MIB, round(keep_gb * 1e9 / MIB)))


def online() -> bool:
    return any(subprocess.run(["curl", "-fsS", "--max-time", "5", "-o", "/dev/null", u], capture_output=True).returncode == 0
               for u in CHECK_URLS)


def terse(line: str) -> list:
    """nmcli -t fields: ":" separates them; a backslash escapes the next character (\\: and \\\\ in a name)."""
    out, cur, i = [], "", 0
    while i < len(line):
        c = line[i]
        if c == "\\" and i + 1 < len(line):
            cur += line[i + 1]
            i += 2
            continue
        if c == ":":
            out.append(cur)
            cur = ""
        else:
            cur += c
        i += 1
    return out + [cur]


WIZARD_FINISHED = False
WIZARD_INSTALLING = False                # the install itself has started (its own process): it may have changed drives


def repair_answers(a, step):
    """Keep all other answers when a plan names the step that needs a correction."""
    title("Change " + step)
    if step == "time":
        a["timezone"] = ask("Time zone", a.get("timezone", ""))
    elif step == "you" and a.get("account_setup") == "later":
        a["hostname"] = ask("Computer name", a.get("hostname", "starchaser-pc"))
    elif step == "you":
        u = a.setdefault("user", {})
        u["name"] = ask("Full name", u.get("name", ""))
        u["username"] = ask("Username", u.get("username", ""))
        u["password"] = secret("Password", 8 if a.get("ssh") else 4)
        a["hostname"] = ask("Computer name", a.get("hostname", ""))
    elif step == "encrypt":
        a["encrypt"] = ("tpm-pin", "tpm", "passphrase", "none")[choose(["Chip and PIN", "Chip only", "Passphrase", "Don't encrypt"], 0 if has_battery() else 1)]
        if a["encrypt"] == "tpm-pin":
            a["pin"] = secret("Startup PIN", 8)
        if a["encrypt"] == "passphrase":
            a["passphrase"] = secret("Drive passphrase", 8)
    elif step == "disk":
        info = disks()
        choices = [d for d in info["disks"] if d.get("system_ok", True) and not d.get("in_use")]
        if not choices:
            ask("No available drive. Connect one, then press Enter")
            return
        d = choices[choose([drive_name(d) for d in choices])]
        a.update(disk=d["path"], disk_id=d.get("id", ""))
        a["mode"] = ("erase", "free", "shrink")[choose(["Erase", "Use free space", "Shrink a partition"])]
        if a["mode"] == "shrink":
            parts = [p for p in d["partitions"] if p.get("shrink") and not p["shrink"].get("blocked")]
            if parts:
                p = parts[choose([p["path"] for p in parts])]
                try:
                    size = int(ask("Size to keep (MiB)", str(p["size"] // MIB)))
                except ValueError:
                    note("Enter a whole number for the size.")
                    return
                a["shrink"] = {"partition": p["path"], "size_mib": size}
        a.pop("manual", None)
        a.pop("drives", None)
    else:
        keyboard = choose_keyboard()
        a["xkb_layout"], a["keymap"] = keyboard[1], keyboard[2]
        a["locale"] = LOCALES[choose([x[0] for x in LOCALES])][1]


def choose_keyboard():
    while True:
        query = ask("Search keyboards by language, country, or layout (type * to list all)", "us").casefold()
        if query == "*":
            query = ""
        exact = [row for row in KEYBOARDS if row[1].casefold() == query]
        matches = exact or [row for row in KEYBOARDS if query in (row[0] + " " + row[1]).casefold()]
        if matches:
            selected = matches[choose([row[0] + " · " + row[1] for row in matches])]
            subprocess.run(["loadkeys", selected[2]], capture_output=True)
            ask("Type here to test your keyboard, then press Enter")
            return selected
        note("No keyboards match. Try another name.")


PRINTK = Path("/proc/sys/kernel/printk")


def quiet_console() -> None:
    """Kernel messages printed on the console (kauditd's "callbacks suppressed" and the like) would land among the
    questions; only the kernel's emergencies still show while the text installer runs."""
    try:
        PRINTK.write_text("3")
    except OSError:
        pass


def wizard() -> None:
    """The same questions as the graphical installer, in the console; the same install (run)."""
    if os.geteuid() != 0:
        sys.exit("Run it as root: sudo starchaser-install wizard")
    quiet_console()
    print(f"\n{P}{B}  Starchaser Linux{R}  installer (text)\n")
    if SPEECH:
        note("Speech is on. Each question lists numbered choices; type a number and press Enter. Press Enter alone "
             "to take the choice in brackets.")
    note("This puts Starchaser Linux on this computer, in a few minutes. Nothing changes on your drives until the "
         "last step, where you'll see exactly what will happen first. Ctrl+C stops at any point before that.")
    if online_edition():
        note("This is the online installer: it needs an internet connection, and downloads Starchaser during the "
             "install.")

    if iso_age_note():
        note(iso_age_note())
    a = {}
    title("Keyboard")
    keyboard = choose_keyboard()
    a["xkb_layout"], a["keymap"] = keyboard[1], keyboard[2]
    title("Language and formats (dates, numbers)")
    a["locale"] = LOCALES[choose([x[0] for x in LOCALES])][1]

    if online_edition():
        title("Connect to the internet (needed)")
        note("This installer downloads Starchaser while it installs"
             + (f", about {edition_download_text()} for most computers" if edition_download_text() else "")
             + ". Nothing on your drives changes until the whole download has arrived and been checked.")
    else:
        title("Optional: connect to get the latest updates")
    while not online():
        if installer_media.MEDIA.is_dir() and not yes("Connect now? You can install everything from the stick", False):
            break
        note("Not online. Starchaser downloads everything while it installs: plug in a network cable, or pick a Wi-Fi network.")
        # NetworkManager can turn a fresh scan down right after another ("Scanning not allowed immediately
        # following previous scan"): the list then comes back empty, so fall back to the networks it already
        # knows (--rescan auto) before saying none were found, the same as the graphical installer
        nets = []
        for rescan in ("yes", "auto"):
            r = subprocess.run(["nmcli", "-t", "-f", "SSID,SECURITY", "dev", "wifi", "list", "--rescan", rescan],
                               capture_output=True, text=True)
            nets = [l for l in r.stdout.splitlines() if l.strip()]
            if r.returncode == 0 and nets:
                break
        fields = [terse(l) + ["", ""] for l in nets]
        work = {f[0] for f in fields if "802.1X" in f[1]}           # work or school networks: a sign-in name too
        ssids = list(dict.fromkeys(f[0] for f in fields if f[0]))
        if not ssids:
            ask("No Wi-Fi networks found. Plug in a cable, then press Enter to look again")
            continue
        i = choose(ssids + ["Look again"])
        if i == len(ssids):
            continue
        if ssids[i] in work:
            # nmcli's one-line join can't set these up; the network tool asks for the sign-in name and the rest
            # "Activate a connection" can't ask for the sign-in details (it just fails): the profile is made by hand
            note(f"{ssids[i]} is a work or school network that needs its own sign-in name. The network tool opens "
                 f"next. In it, choose Edit a connection, then Add, then Wi-Fi. Type {ssids[i]} as the SSID (the "
                 "network's name), set Security to WPA & WPA2 Enterprise, fill in the sign-in details your work or "
                 "school gave you, and choose OK. Then choose Back and Quit: the installer connects and checks again.")
            ask("Press Enter to open the network tool")
            subprocess.run(["nmtui"])
            continue
        import getpass
        pw = getpass.getpass(f"Password for {ssids[i]} (Enter if none): ")
        # the same join as the graphical installer (starchaser network wifi-join, from the repo on the live system):
        # the password goes in through stdin and a pipe to nmcli, never on a command line, where any program on the
        # live system could read it (ps, /proc), nor in the environment; a wrong password is caught in seconds, and
        # the profile a failed join made is deleted, so it is never kept or carried over to the new system
        tool = Path("/usr/share/starchaser/repo/bin/starchaser-network")
        if tool.exists():
            r = subprocess.run([sys.executable, str(tool), "wifi-join", "--password-stdin", "--", ssids[i]],
                               input=pw + "\n", capture_output=True, text=True)
            if r.returncode:
                try:
                    msg = json.loads(r.stdout)["errors"]
                except (ValueError, KeyError, TypeError):
                    msg = f"Couldn't connect to {ssids[i]}. Try again, or pick another network."
                print(f"{E}{msg}{R}")
        else:
            r = subprocess.run(["nmcli", "--ask", "dev", "wifi", "connect", ssids[i]], input=pw + "\n",
                               capture_output=True, text=True)
            if r.returncode:
                print(f"{E}{(r.stderr or r.stdout).strip().replace('Error: ', '')}{R}")
    print("Network step complete.")

    while True:
        title("Drive")
        info = disks()
        if not info["uefi"]:
            note("This computer started the installer in legacy BIOS mode. Starchaser needs UEFI: restart, open the "
                 "firmware setup, and choose the USB stick's UEFI entry.")
            sys.exit(1)
        ds = [x for x in info["disks"] if x.get("system_ok", True)]
        if info.get("hiddenDrives"):
            note(info["hiddenDrives"])
        if not ds:
            sys.exit(f"No drive here can take Starchaser (it needs at least {size_text(required_drive())}, and the USB stick "
                     "it runs from doesn't count).")
        pick = next((i for i, x in enumerate(ds) if x["path"] == info.get("suggested")), 0)
        d = ds[choose([f"{x['model']}  {size_text(x['size'])}  {x.get('speed', {}).get('kind', '')}  {x['path']}  "
                       + (("has " + " and ".join(x["oses"])) if x["oses"] else ("has files on it" if x["partitions"] else "empty"))
                       for x in ds], pick)]
        a["disk"] = d["path"]
        a["disk_id"] = d.get("id", "")
        try:
            report = drive_safety(a["disk"], a["disk_id"])
        except Stop as error:                    # back to the Drive step with the reason; the answers so far stay
            print(f"{E}{error}{R}")
            ask("Press Enter to look at the drives again")
            continue
        note(report["words"])
        note(report["health"])
        modes, labels = [], []
        free = max(d["free"], key=lambda f: f["bytes"], default=None)
        if d["table"] == "gpt" and d["esp"] and free and free["bytes"] >= required_free():
            modes.append("free"); labels.append(f"Install next to {' and '.join(d['oses']) or 'what is there'} in the {size_text(free['bytes'])} of free space")
        shrinkable = [p for p in d["partitions"] if p.get("shrink")] if d["table"] == "gpt" and d["esp"] else []
        if shrinkable:
            modes.append("shrink"); labels.append("Make room by shrinking a partition (its files stay)")
        modes.append("erase"); labels.append(f"{E}Erase this drive{R} and install (removes everything on it)")
        a["mode"] = modes[choose(labels)]
        if a["mode"] == "erase" and d["partitions"]:
            if yes("Copy your files to an external backup drive first?", True):
                targets = [(drive, p) for drive in info["disks"] if drive["path"] != d["path"] and (drive.get("removable") or drive.get("transport") == "usb") for p in drive["partitions"] if p["fs"] in PEEK_MOUNT and not p.get("in_use")]
                if not targets:
                    note("Connect an external backup drive, then choose this drive again.")
                    continue
                dest, part = targets[choose([drive_name(drive) + " " + p["path"] for drive, p in targets])]
                try:
                    copied = locked_backup(dict(a, target=part["path"], target_id=dest["id"], target_uuid=part["uuid"]))
                    note(copied["message"])
                except Stop as error:
                    note(str(error))
                continue
            if not yes("Have you backed up everything you need? Erasing removes all files", False):
                continue
        if a["mode"] == "shrink":
            ok = [p for p in shrinkable if not p["shrink"].get("blocked")]
            for p in shrinkable:
                if p["shrink"].get("blocked"):
                    note(f"{p.get('role', p['path'])} ({p['path']}): {p['shrink']['blocked']}")
            ok = [p for p in ok if shrink_range(p)]
            if not ok:
                note("None of these partitions can be shrunk. Pick another drive or another way.")
                continue
            i = choose([f"{x.get('role', x['fs'])}  {size_text(x['size'])}  {x['path']}  (holds {size_text(x['shrink']['min'])})"
                        for x in ok] + ["Go back"])
            if i == len(ok):
                continue
            p = ok[i]
            lo, hi, default = shrink_range(p)
            while True:
                v = ask(f"Keep how many GB for {p.get('role', p['path'])}? ({lo} to {hi}; Starchaser gets the rest)", str(default))
                try:
                    keep = round(float(v))
                except (ValueError, OverflowError):
                    print(f"{E}Type a number from {lo} to {hi}.{R}")
                    continue
                if lo <= keep <= hi:
                    break
                print(f"{E}Between {lo} and {hi}.{R}")
            a["shrink"] = {"partition": p["path"], "size_mib": keep_mib(p, keep)}
        if len(info["disks"]) > 1:
            note("Your other drives are left alone. To use them for files, for your home folder, or to keep what's on "
                 "them, use the graphical installer.")
        break

    title("Encryption")
    opts, labels = [], []
    if info["tpm2"]:
        opts.append("tpm-pin"); labels.append("Encrypt with this computer and a startup PIN" + (" (recommended)" if info.get("battery") else ""))
        opts.append("tpm"); labels.append("Encrypt, and let this computer unlock it" + (" (recommended)" if not info.get("battery") else "") + ". "
                                          "Protects your files if the drive is taken out of the computer")
    opts.append("passphrase"); labels.append("Encrypt, with a disk key at every start")
    opts.append("none"); labels.append("Don't encrypt (anyone with the drive can read it)")
    a["encrypt"] = opts[choose(labels, opts.index(default_encryption(info)))]
    if a["encrypt"] == "tpm-pin":
        a["pin"] = secret("Startup PIN (8 or more characters)", 8)
    if a["encrypt"] == "passphrase":
        a["passphrase"] = secret("Disk key (8 or more characters)", 8)

    title("Who will use this?")
    a["account_setup"] = "later" if choose(["Me", "Someone else, later"]) else "me"
    while True:
        host = ask("Computer name", "starchaser-pc")
        if re.fullmatch(r"[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?", host):
            break
        print(f"{E}Letters, digits and - (not at the start or end).{R}")
    a["hostname"] = host
    if a["account_setup"] == "me":
        while True:
            name = ask("Your name")
            problem = full_name_problem(name)
            if not problem:
                break
            print(f"{E}{problem}{R}")
        first = re.sub(r"[^a-z0-9_-]", "", (name.split() or [""])[0].lower()).lstrip("0123456789-") or "user"
        while True:
            user = ask("Username", first)
            if not re.fullmatch(r"[a-z_][a-z0-9_-]{0,31}", user):
                print(f"{E}Lowercase letters, digits, - or _, starting with a letter.{R}")
            elif user in info["reserved"]:
                print(f"{E}That name is already used by the system. Pick another.{R}")
            else:
                break
        note("Use several words for a stronger password. Remote login needs at least 8 characters.")
        password = secret("Password", 4)
        a["user"] = {"name": name, "username": user, "password": password}
        a["autologin"] = yes("Log in automatically when the computer starts?", False)
        if a["autologin"]:
            a["keyring_unencrypted"] = yes("Also keep saved passwords unencrypted, so apps never ask to unlock them? "
                                           "Anyone who can use this computer could then read them.", False)
        a["ssh"] = yes("Allow remote login (SSH) from your other computers (needed to join your fleet)?", False)
        if a["ssh"]:
            if len(password) < 8:
                note("Remote login needs at least 8 characters. A longer password with several words is stronger.")
                a["user"]["password"] = secret("Password", 8)
            a["trust_network"] = yes("Trust the network you're installing on, so SSH and your fleet can reach this computer "
                                     "right after the install? (Only this network; leave it off on one you don't control)", False)
        a["remote_desktop"] = yes("Remote desktop: see and use this computer from your other computers (Moonlight)?", False)

    title("Time zone")
    note("To suggest a time zone and nearby download servers, the installer asks ipinfo.io and ipapi.co. They see your internet address.")
    a["no_lookup"] = not yes("Look up my time zone and nearby download servers from my internet address? "
                             "(No: nothing is looked up, you pick the time zone, and downloads use the worldwide server list)", True)
    import zone_lookup        # the same lookup as the graphical installer and the live session's clock
    guess = "" if a["no_lookup"] else zone_lookup.guess()
    zones = subprocess.run(["timedatectl", "list-timezones"], capture_output=True, text=True).stdout.split()
    tz = guess if guess in zones else ""
    while True:
        v = ask("Time zone (or a city to search for)", tz)
        if v in zones:
            a["timezone"] = v
            break
        hits = [z for z in zones if v.lower().replace(" ", "_") in z.lower()][:15]
        if not hits:
            print(f"{E}Nothing matches {v!r}.{R}")
            continue
        a["timezone"] = hits[choose(hits)]
        break

    title("Ready to install")
    pl = plan(a)
    while not pl["ok"]:
        for problem in pl["errors"]:
            print(f"{E}• {problem}{R}")
        step = next((b for b in pl.get("back", []) if b), "welcome")
        repair_answers(a, step)
        pl = plan(a)
    note("Here's exactly what happens:")
    for i, st in enumerate(pl["steps"], 1):
        print(f"  {P}{i}.{R} {st}")
    for n in pl.get("notes", []):
        print()
        note(n)
    word = "erase" if pl.get("destructive", a["mode"] == "erase") else "install"
    if ask(f"\nType {B}{word}{R} to go ahead, anything else to stop").lower() != word:
        sys.exit("Stopped. Nothing was changed.")

    # the install itself: the same engine run as the graphical installer, its progress drawn as a bar
    req = Path("/run/starchaser-answers.json")
    old = os.umask(0o077)
    req.write_text(json.dumps(a))
    os.umask(old)
    import signal
    signal.signal(signal.SIGINT, signal.SIG_IGN)           # past this point, Ctrl+C would stop it half-done
    print(f"{M}Installing. This takes a few minutes; Ctrl+C no longer stops it.{R}")
    global WIZARD_INSTALLING
    WIZARD_INSTALLING = True
    p = subprocess.Popen([sys.executable, os.path.realpath(__file__), "run", str(req)], stdout=subprocess.PIPE, text=True, bufsize=1)
    weights = {"prepare": 0, "shrink": 3, "partition": 2, "encrypt": 3, "format": 2, "mirrors": 1, "download": 22, "base": 10, "drives": 2, "configure": 3, "boot": 2, "desktop": 46, "finish": 4}
    order = list(weights)
    phase, label, done, total, result, key, tail, spoken = "", "Starting", 0, 0, {}, "", [], -1
    code, boot_code = "", ""
    for line in p.stdout:
        if not line.startswith("@@"):
            continue
        try:
            e = json.loads(line[2:])
        except ValueError:
            continue
        if e["event"] == "phase":
            phase, label, done, total = e["phase"], e["label"], 0, 0
            if SPEECH:
                print(f"{label}.", flush=True)
        elif e["event"] == "progress":
            done, total = e["done"], e["total"]
        elif e["event"] == "recovery-key":
            key = e["key"]
        elif e["event"] == "password-code":
            code = e["code"]
        elif e["event"] == "secure-boot-code":
            boot_code = e["code"]
        elif e["event"] == "log":
            tail = e.get("lines", [])
        elif e["event"] == "done":
            result = e
        if SPEECH:                                 # a short line every quarter of the way, nothing redrawn
            if phase in weights:
                q = int((sum(weights[x] for x in order[:order.index(phase)]) + weights[phase] * (min(1, done / total) if total else 0)) / 25)
                if q > spoken:
                    spoken = q
                    if q:
                        print(f"{q * 25} percent done.", flush=True)
            continue
        if phase in weights:
            pct = (sum(weights[x] for x in order[:order.index(phase)]) + weights[phase] * (min(1, done / total) if total else 0.3)) / 100
            bar = "█" * int(pct * 30) + "░" * (30 - int(pct * 30))
            print(f"\r{P}{bar}{R} {pct * 100:3.0f}%  {label:<36}", end="", flush=True)
    p.wait()
    global WIZARD_FINISHED
    WIZARD_FINISHED = bool(result.get("ok"))
    if result.get("ok") and not SPEECH:
        print(f"\r{P}{'█' * 30}{R} 100%  {'Done':<36}", end="")
    print()
    if not result.get("ok"):
        if tail:
            print(f"{M}The last lines of the log:{R}")
            for l in tail:
                print("  " + l)
        print(f"\n{E}The install stopped: {result.get('error') or 'it ended unexpectedly.'}{R}")
        sys.exit(f"The whole log: {LOG}" + ("\nTo try again: sudo starchaser-install wizard" if result.get("retry") else ""))
    print(f"\n{P}{B}Starchaser is installed.{R}")
    for row in result.get("hardware", []):
        if not row.get("detected") and not row.get("needsFix"):
            continue
        note(row["title"] + ": " + row["detail"])
    if result.get("warning"):
        note(result["warning"])
    if boot_code:
        title("Your Secure Boot enrollment code")
        print(f"\n    {B}{boot_code}{R}\n")
        note("Write down this one-time code. At the blue startup screen choose Enroll MOK, Continue, Yes. Type this code, then choose Reboot. Keep the drive recovery key ready for the first start. After signing in, open Settings > Security to relink chip unlock if needed.")
        while ask("Type saved once you have written down the enrollment code").lower() != "saved":
            pass
    if key:
        title("Your disk key")
        print(f"\n    {B}{key}{R}\n")
        note("Write it down or take a photo of it, and keep it away from this computer. It's the only way into your files "
             "if this computer can't unlock the drive by itself (after a motherboard repair or a firmware reset).")
        while ask("Type saved once you have it").lower() != "saved":
            pass
    if code:
        title("Your password recovery code")
        print(f"\n    {B}{code}{R}\n")
        note(PASSWORD_CODE_WORDS)
        while ask("Type saved once you have written it down").lower() != "saved":
            pass
    if yes("\nRestart now? Take out the USB stick once the screen goes dark", True):
        subprocess.run(["systemctl", "reboot"])


SITE = Path("/usr/share/starchaser/site.json")
SITE_KEYS = ("hostname", "timezone", "ssh", "trust_network", "authorized_keys", "sudo_nopasswd", "remote_desktop",
             "channel")


def with_site(a: dict) -> dict:
    """A machine-specific ISO may carry site.json ({"set": {...}}): its few keys replace the answers' own, so a
    private build installs a known computer (its name, SSH keys, fleet sudo) while the screens stay the same. The
    plan lists each of them, so nothing changes unseen. Public ISOs have no site.json."""
    profile_path = Path("/run/archiso/bootmnt/starchaser-site.json")
    if profile_path.is_file():
        import fleet_media
        profile = fleet_media.validate(json.loads(profile_path.read_text()))
        identity = next((p.read_text().strip() for p in (Path("/sys/class/dmi/id/product_uuid"), Path("/etc/machine-id")) if p.is_file()), "")
        return {**a, **fleet_media.answers(profile, identity, disks()), "mode": a.get("mode") or "erase", "timezone": profile.get("timezone", "America/Los_Angeles"), "fleet_profile": profile}
    if not SITE.is_file():
        return a
    site = json.loads(SITE.read_text()).get("set", {})
    return {**a, **{k: v for k, v in site.items() if k in SITE_KEYS}}


def fleet_wifi(profile, folder=None, runner=None):
    """Save and connect the provisioned network without putting its password in argv or the journal."""
    import configparser

    import fleet_media
    profile = fleet_media.validate(profile)
    import uuid
    runner = runner or sh
    config = configparser.ConfigParser(interpolation=None)
    config["connection"] = {"id": "Fleet install Wi-Fi", "uuid": str(uuid.uuid4()), "type": "wifi", "autoconnect": "true"}
    config["wifi"] = {"ssid": _keyfile_escape(profile["wifi"]["ssid"]), "mode": "infrastructure"}
    config["wifi-security"] = {"key-mgmt": "wpa-psk", "psk": _keyfile_escape(profile["wifi"]["password"])}
    config["ipv4"] = {"method": "auto"}
    config["ipv6"] = {"method": "auto", "addr-gen-mode": "stable-privacy"}
    folder = folder or Path("/run/NetworkManager/system-connections")
    folder.mkdir(parents=True, exist_ok=True)
    path = folder / "starchaser-fleet-install.nmconnection"
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, "w") as stream:
        config.write(stream, space_around_delimiters=False)
    runner("nmcli", "connection", "load", path)
    runner("nmcli", "connection", "up", "Fleet install Wi-Fi", check=False)
    return path


def main(argv: list) -> None:
    cmd = argv[0] if argv else ""
    if cmd in ("disks", "check") and len(argv) == (1 if cmd == "disks" else 2):
        # the graphical installer reads this JSON: a crash still answers in JSON, with a plain reason
        try:
            out = disks() if cmd == "disks" else plan(with_site(json.loads(Path(argv[1]).read_text())))
            if cmd == "disks" and Path("/run/archiso/bootmnt/starchaser-site.json").is_file():
                defaults = with_site({})
                out["fleetInstall"] = {k: defaults[k] for k in ("hostname", "account_setup", "encrypt", "timezone")}
        except Exception as e:
            traceback.print_exc()
            out = {"ok": False, "crashed": True, "steps": [], "notes": [], "disks": [], "uefi": Path("/sys/firmware/efi").is_dir(), "tpm2": False,
                   "errors": [f"The installer couldn't look at this computer's drives ({type(e).__name__}: {e})."
                              if cmd == "disks" else f"The installer couldn't check this ({type(e).__name__}: {e})."]}
        print(json.dumps(out, indent=1))
    elif cmd == "languages" and len(argv) == 1:
        print(json.dumps({"keyboards": install_language.keyboards()}))
    elif cmd == "iso-age":
        print(iso_age_note())
    elif cmd == "peek" and ((len(argv) == 2 and argv[1] != "--passphrase-stdin")
                            or (len(argv) == 3 and argv[1] == "--passphrase-stdin")):
        # the passphrase is one line on stdin, never the command line (anyone can read those) or the environment
        # (sudo --preserve-env writes the variables it keeps to the system journal); only its newline is taken off
        passphrase = ""
        if argv[1] == "--passphrase-stdin":
            passphrase = sys.stdin.readline()
            if passphrase.endswith("\n"):
                passphrase = passphrase[:-1]
        try:
            out = peek(argv[-1], passphrase)
        except Exception as e:
            out = {"ok": False, "error": f"The installer couldn't look inside it ({type(e).__name__}: {e})."}
        print(json.dumps(out, indent=1))
    elif cmd in ("safety", "backup"):
        try:
            out = drive_safety(argv[1], argv[2]) if cmd == "safety" and len(argv) == 3 else locked_backup(json.load(sys.stdin)) if cmd == "backup" and len(argv) == 1 else {"ok": False, "errors": "Invalid drive check request."}
        except Exception as error:
            out = {"ok": False, "errors": str(error)}
        print(json.dumps(out))
    elif cmd == "run" and len(argv) == 2:
        run(argv[1])
    elif cmd == "wizard":
        try:
            wizard()
        except (KeyboardInterrupt, EOFError):
            sys.exit("\nStarchaser is installed. You can restart when your recovery keys are saved." if WIZARD_FINISHED else "\nStopped. Nothing was changed.")
        except Exception as error:
            # never a traceback on the installer's screen: the reason in plain words, the details in the log
            if not isinstance(error, Stop):
                try:
                    log("text installer stopped:\n" + traceback.format_exc())
                except OSError:
                    pass
            reason = str(error) if isinstance(error, Stop) else (
                f"The installer ran into a problem it didn't expect ({type(error).__name__}: {error}). The details "
                f"are in {LOG}.")
            sys.exit(f"\n{E}{reason}{R}\n" + ("Starchaser is installed. You can restart when your recovery keys are saved."
                                             if WIZARD_FINISHED else
                                             f"The install stopped part way. The whole log: {LOG}" if WIZARD_INSTALLING
                                             else "Nothing on your drives was changed."))
    elif cmd in ("-h", "--help") and len(argv) == 1:
        print(__doc__)
    else:
        print(__doc__, file=sys.stderr)
        sys.exit(2)


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