Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

55.9 KB
Raw Blame
#!/usr/bin/env python3
"""Offline full-disk installer. Nothing is erased until the exact disk is confirmed."""
from __future__ import annotations
import argparse
from contextlib import contextmanager, ExitStack
import curses
from datetime import datetime, timezone
import hashlib
import importlib.util
import json
import os
import pwd
from pathlib import Path
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import textwrap
import time

MIN_DISK_BYTES = 12 * 1024**3
LIVE_PAYLOADS = (Path('/run/archiso/copytoram/airootfs.sfs'),
                 Path('/run/archiso/bootmnt/arch/x86_64/airootfs.sfs'))
LIVE_MEDIUM = Path('/run/archiso/bootmnt')
# The recovery: the USB's own system, kept at the end of the disk unencrypted, to install this computer
# again as it came when its power button asks (button.py, unlock/button): everything erased, a new
# disk key, and this password. Its GRUB entry (/etc/grub.d/42_harness-recovery) reads RECOVERY_CONF.
RECOVERY_LABEL = 'HN_RECOVERY'
RECOVERY_SIZE = '4GiB'
RECOVERY_MIN_DISK_BYTES = 24 * 1024**3
RECOVERY_ENTRY = 'harness-recovery'
RECOVERY_PASSWORD = '1234'
RECOVERY_CONF = '/etc/harness-os/recovery.conf'
GRUBENV_HEADER = '# GRUB Environment Block\n# WARNING: Do not edit this file by tools other than grub-editenv!!!\n'
WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
COMMAND_LOG = None
INSTALL_LOG = Path('/var/log/harness-install.log')
# On a USB built with HARNESS_OS_KEEP_LOGS: what it installs keeps its journal on disk.
KEEP_LOGS = Path('/etc/harness-os/keep-logs')
LAST_LOG = None


def hardware_module():
    # Load the root-owned packaged sibling, never a module from the working
    # directory.
    spec = importlib.util.spec_from_file_location('harness_os_hardware', Path(__file__).with_name('hardware.py'))
    hardware = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(hardware)
    return hardware


def boot_module():
    spec = importlib.util.spec_from_file_location('harness_boot_profile', Path(__file__).with_name('boot_profile.py'))
    value = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(value)
    return value


def require_install_platform(sysfs=Path('/sys')):
    blocker = hardware_module().installation_blocker(sysfs)
    if blocker:
        raise ValueError(blocker)


def installation_notice():
    if hardware_module().opencode_cpu_supported() is False:
        return 'This CPU cannot run bundled OpenCode (SSE4.2 required).'
    return ''


def encryption_memory(meminfo=Path('/proc/meminfo')):
    """Budget Argon2 against RAM, not zram advertised as additional swap."""
    try:
        values = {name: int(value) for name, value in re.findall(
            r'^(MemTotal|MemAvailable):\s+(\d+) kB$', meminfo.read_text(), re.M)}
        total, available = values['MemTotal'], values['MemAvailable']
        if not 0 < available <= total:
            raise ValueError('Invalid memory information')
    except (OSError, KeyError, ValueError) as error:
        raise ValueError('Cannot check available memory for encryption. No disk has been erased.') from error
    # Cryptsetup normally uses at most half of physical RAM, up to 1 GiB.
    # Its extra free-memory limit applies only without swap. Zram is RAM too:
    # leave half of available RAM and at least 128 MiB for the live session.
    budget = min(1024 * 1024, total // 2, available // 2, available - 128 * 1024)
    budget = budget // 1024 * 1024
    if budget < 64 * 1024:
        raise ValueError('Not enough free memory for encryption. Close other harnesses and browser windows, then try again. No disk has been erased.')
    return budget


@contextmanager
def command_log(path):
    """Keep command output off the form. Never record stdin (which may be a password)."""
    global COMMAND_LOG
    previous = COMMAND_LOG
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
    try:
        os.fchmod(fd, 0o600)
        with os.fdopen(fd, 'w') as output:
            fd = None
            COMMAND_LOG = output
            yield output
    finally:
        COMMAND_LOG = previous
        if fd is not None:
            os.close(fd)


def run(*args, input=None, capture=False, timeout=None):
    if COMMAND_LOG:
        COMMAND_LOG.write('\n$ ' + shlex.join(str(a) for a in args) + '\n')
        COMMAND_LOG.flush()
    result = subprocess.run([str(a) for a in args], input=input, check=True, timeout=timeout,
                            stdout=subprocess.PIPE if capture else COMMAND_LOG,
                            stderr=COMMAND_LOG if capture else subprocess.STDOUT if COMMAND_LOG else None)
    return result.stdout.decode().strip() if capture else None


def log_diagnostic(message):
    if COMMAND_LOG:
        try:
            COMMAND_LOG.write(message + '\n')
            COMMAND_LOG.flush()
        except OSError:
            # A failed diagnostic write must not replace the installation error.
            pass


def mapping_active(mapper):
    # /dev nodes can outlive a successful removal while udev is stalled. Ask
    # the kernel through sysfs, not the stale node which caused the timeout.
    root = Path('/sys/class/block')
    if not root.is_dir():
        raise OSError('Cannot inspect the installed disk mapping.')
    for device in root.iterdir():
        if not device.name.startswith('dm-'):
            continue
        try:
            if (device / 'dm/name').read_text().strip() == mapper:
                return True
        except FileNotFoundError:
            pass  # A concurrent last close removed this mapping.
    return False


def close_install_mapping(mapper, timeout=10):
    """After successful unmount, let the kernel close any remaining device reader."""
    try:
        # A filesystem probe may outlive unmount. Deferred removal is immediate
        # when unused, otherwise the kernel removes the device on its last close.
        # Never force removal, and never call this after a failed unmount.
        run('cryptsetup', 'close', '--deferred', mapper, timeout=timeout)
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
        if isinstance(error, subprocess.CalledProcessError) and error.returncode != 5:
            raise
        log_diagnostic(f'Device close is waiting for a reader or udev: {error}')
        if not mapping_active(mapper):
            return  # The ioctl completed before cryptsetup's udev wait timed out.
        # Do not wait for unrelated udev work again. This uses the same deferred
        # kernel removal, with no force, table replacement or skipped disk flush.
        try:
            run('dmsetup', 'remove', '--deferred', '--noudevsync', mapper, timeout=3)
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            if mapping_active(mapper):
                raise
            # The final reader can also leave between the check and removal.


def partitions(disk):
    separator = 'p' if disk[-1].isdigit() else ''
    return [f'{disk}{separator}{n}' for n in (1, 2, 3)]


def recovery_partition(disk):
    """The fourth, after the root: the root keeps its number, which everything else names."""
    return partitions(disk)[0][:-1] + '4'


def grubenv(next_entry=None):
    """GRUB's environment block: [next_entry] is started once, at the next start, then forgotten."""
    text = GRUBENV_HEADER + (f'next_entry={next_entry}\n' if next_entry else '')
    return text.encode().ljust(1024, b'#')


def validate_config(config):
    if not isinstance(config, dict) or any(not isinstance(config.get(key), str) for key in ['username', 'hostname', 'password', 'disk']):
        raise ValueError('Account, computer, password and disk fields must be text.')
    if not re.fullmatch(r'[a-z_][a-z0-9_-]{0,30}', config.get('username', '')):
        raise ValueError('Use a Linux username: lowercase letters, digits, underscores or hyphens.')
    if config['username'] == 'root':
        raise ValueError('Create a regular user, not root.')
    if not re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', config.get('hostname', '')):
        raise ValueError('Invalid hostname.')
    password = config.get('password', '')
    if not password:
        raise ValueError('Enter a password.')
    if any(c in password for c in '\r\n\0'):
        raise ValueError('The password cannot contain line breaks or null characters.')
    if type(config.get('encrypt')) is not bool:
        raise ValueError('encrypt must be true or false.')
    if not re.fullmatch(r'/dev/[a-zA-Z0-9_-]+', config.get('disk', '')):
        raise ValueError('Select a whole /dev disk.')


def validate_disk(device, expected_serial=None, recovery=False):
    if device.get('type') != 'disk' or device.get('ro'):
        raise ValueError('Target must be a writable whole disk.')
    if int(device.get('size') or 0) < MIN_DISK_BYTES:
        raise ValueError('The target needs at least 12 GiB.')
    def mounted(node):
        # The recovery installs from its own partition, which it keeps (install_image).
        if recovery and node.get('label') == RECOVERY_LABEL:
            return False
        return any(node.get('mountpoints') or []) or any(mounted(c) for c in node.get('children', []))
    if mounted(device):
        raise ValueError('The disk has mounted filesystems. The live USB and active disks cannot be erased.')
    def live_medium(node):
        return (node.get('fstype') == 'iso9660' and node.get('label') == 'HN_OS') or any(
            live_medium(c) for c in node.get('children', []))
    if live_medium(device):
        raise ValueError('The Harness USB cannot be an installation target, even when booted into RAM.')
    if expected_serial is not None and str(device.get('serial') or '').strip() != expected_serial:
        raise ValueError('Disk serial does not match the unattended installation configuration.')


def inventory():
    return json.loads(run('lsblk', '--json', '--bytes', '--paths', '--output',
                          'NAME,TYPE,SIZE,RO,RM,MOUNTPOINTS,MODEL,SERIAL,FSTYPE,LABEL', capture=True))['blockdevices']


def live_payload(source=None):
    # Archiso automatically copies USB media to RAM when enough memory is free,
    # then unmounts bootmnt. Prefer that running image over any removable copy.
    candidates = (source,) if source is not None else LIVE_PAYLOADS
    for candidate in candidates:
        if candidate.is_file():
            return candidate
    checked = ', '.join(str(path) for path in candidates)
    raise ValueError(f'Live system payload is missing (checked {checked}); boot the Harness USB.')


def selected_disk(config):
    devices = [d for d in inventory() if d['name'] == config['disk']]
    if len(devices) != 1:
        raise ValueError('Target disk was not found.')
    validate_disk(devices[0], config.get('expected_serial'), recovery=config.get('recovery') is True)
    return devices[0]


def write(root, path, text, mode=0o644):
    target = root / path.lstrip('/')
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(text)
    target.chmod(mode)


def chroot(root, *args, **kwargs):
    return run('arch-chroot', root, *args, **kwargs)


def validate_image_account(passwd, username):
    names = {line.split(':', 1)[0] for line in passwd.splitlines()}
    if username != 'me' and username in names:
        raise ValueError(f'The image reserves the username {username}; choose a different account name.')


def preflight(config, source):
    for command in ['sgdisk', 'udevadm', 'mkfs.fat', 'mkfs.btrfs', 'cryptsetup', 'dmsetup',
                    'mount', 'umount', 'btrfs', 'unsquashfs', 'arch-chroot', 'blkid']:
        if not shutil.which(command):
            raise ValueError(f'The installer is missing {command}. Boot an intact Harness image.')
    validate_image_account(run('unsquashfs', '-cat', source, 'etc/passwd', capture=True), config['username'])
    lock = json.loads(run('unsquashfs', '-cat', source, 'usr/share/harness-os/lock.json', capture=True))
    if lock.get('architecture') != 'x86_64' or not lock.get('version'):
        raise ValueError('The source is not a Harness x86_64 image.')
    kernel = json.loads(run('unsquashfs', '-cat', source, 'usr/share/harness-os/kernel.json', capture=True))
    if not re.fullmatch(r'usr/lib/modules/[a-zA-Z0-9._+-]+/vmlinuz', kernel.get('path', '')) or not re.fullmatch(r'[a-f0-9]{64}', kernel.get('sha256', '')):
        raise ValueError('The image has an invalid kernel manifest.')
    payload = subprocess.check_output(['unsquashfs', '-cat', str(source), kernel['path']], stderr=COMMAND_LOG)
    if hashlib.sha256(payload).hexdigest() != kernel['sha256']:
        raise ValueError('The installation kernel failed verification. No disk has been erased.')
    profile = boot_module().selected()
    if kernel.get('platform', 'pc') != profile['id']:
        raise ValueError('The installation image uses a different boot platform.')
    pkgbase = run('unsquashfs', '-cat', source, str(Path(kernel['path']).with_name('pkgbase')), capture=True)
    if pkgbase.strip() != profile['kernel']:
        raise ValueError('The installation image has the wrong platform kernel.')
    return kernel


def trial_command(action, source, account, destination_fd=None):
    # Project paths are user-controlled. Read and write them without installer
    # privileges; a symlink/race must never let the installer copy a root secret.
    command = ['/usr/bin/python3', '/usr/lib/harness-os/trial_projects.py', action, str(source)]
    descriptors = ()
    if destination_fd is not None:
        command += ['--destination-fd', str(destination_fd)]
        descriptors = (destination_fd,)
    result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=COMMAND_LOG,
                            user=account.pw_uid, group=account.pw_gid, extra_groups=[],
                            pass_fds=descriptors, env={'PATH': '/usr/bin', 'LANG': 'C.UTF-8'})
    return json.loads(result.stdout)


def trial_source(config):
    if not Path('/etc/harness-live').is_file():
        return None
    account = pwd.getpwnam('me')
    source = Path(account.pw_dir) / 'projects'
    if not source.exists():
        return None
    required = trial_command('size', source, account)['bytes']
    available = int(selected_disk(config)['size']) - 5 * 1024**3
    if required > available:
        raise ValueError('This disk needs more space for your trial projects. Choose a larger disk or save the projects elsewhere first.')
    return source, account


# The password as installed, for `harness factory-reset` to put back (setup.py restore_initial_password).
# Root's alone, on the installed root: inside the encrypted disk where there is one.
INITIAL_ACCOUNT = '/var/lib/harness-os/initial-account.json'


def save_initial_password(target, config):
    """The account's password hash, and on an encrypted disk the password itself: the disk's key
    slots can only be changed with a passphrase that opens one, and a reset puts back this one."""
    shadow = next((line.split(':')[1] for line in (target / 'etc/shadow').read_text().splitlines()
                   if line.split(':', 1)[0] == config['username']), None)
    record = {'username': config['username'], 'shadow': shadow}
    if config['encrypt']:
        record.update(initial=config['password'], current=config['password'])
    write(target, INITIAL_ACCOUNT, json.dumps(record) + '\n', 0o600)


def preserve_trial(trial, target, home):
    if trial is None:
        return None
    source, account = trial
    # A root-owned parent keeps other live processes from changing the destination.
    # Only this child receives the open writable directory, then drops privileges.
    with tempfile.TemporaryDirectory(prefix='.harness-trial-', dir=target / 'home') as temp:
        staging = Path(temp) / 'projects'
        staging.mkdir(mode=0o700)
        os.chown(staging, account.pw_uid, account.pw_gid)
        descriptor = os.open(staging, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
        try:
            receipt = trial_command('copy', source, account, descriptor)
        finally:
            os.close(descriptor)
        shutil.rmtree(home / 'projects')  # Only the new account's pristine skeleton.
        staging.rename(home / 'projects')
    detail = home / '.local/state/harness-os/trial-projects.json'
    detail.parent.mkdir(parents=True, exist_ok=True)
    detail.write_text(json.dumps(receipt, indent=2) + '\n')
    detail.chmod(0o600)
    return {key: value for key, value in receipt.items() if key != 'entries'}


def shared_broadcom_cache(source, bundle):
    """Use the live cache only when it belongs to this exact selected payload."""
    try:
        manifest = json.loads((bundle / 'manifest.json').read_text())
        embedded = json.loads(run('unsquashfs', '-cat', source,
                                  'usr/share/harness-os/hardware/broadcom/manifest.json', capture=True))
        if (not isinstance(manifest, dict) or manifest != embedded or not manifest.get('packages') or
                not isinstance(manifest.get('files'), dict) or not manifest['files'] or
                not (bundle / 'packages').is_dir()):
            return False
        # Avoid reading the entire archive cache on generic machines. Selected
        # radios still verify every hash and signature before pacman sees it.
        for name, expected in manifest['files'].items():
            path = bundle / name
            if (Path(name).is_absolute() or '..' in Path(name).parts or
                    path.is_symlink() or not path.resolve().is_relative_to(bundle.resolve()) or
                    not path.is_file() or path.stat().st_size != expected['bytes']):
                return False
        return True
    except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
        # An explicit --source can differ from the running USB. Keep its own
        # cache instead of requiring matching live files for that installation.
        return False


def copy_image(source, target, broadcom=Path('/usr/share/harness-os/hardware/broadcom')):
    # Bound extraction memory. Keep the Wi-Fi module/manifest from the selected
    # image; selected radios can read its matching signed archives from the USB.
    excluded = ['usr/share/harness-os/hardware/nvidia']
    if shared_broadcom_cache(source, broadcom):
        excluded.append('usr/share/harness-os/hardware/broadcom/packages')
    run('unsquashfs', '-mem', '64M', '-f', '-no-progress', '-excludes', '-d', target, source, *excluded)


def recovery_files(kernel):
    """What the recovery boots, as the USB keeps it: its kernel, its startup and its system."""
    return [f'arch/boot/x86_64/vmlinuz-{kernel}', f'arch/boot/x86_64/initramfs-{kernel}.img',
            'arch/x86_64/airootfs.sfs']


@contextmanager
def live_medium(kernel):
    """The Harness USB's files, for the recovery; None when they are not at hand (a --source install,
    another platform's boot). Copied to RAM, the USB is no longer mounted: mounted again, read-only."""
    if all((LIVE_MEDIUM / name).is_file() for name in recovery_files(kernel)):
        yield LIVE_MEDIUM
        return
    def find(nodes):
        for node in nodes:
            if node.get('fstype') == 'iso9660' and node.get('label') == 'HN_OS':
                return node['name']
            found = find(node.get('children', []))
            if found:
                return found
        return None
    try:
        device = find(inventory())
    except (ValueError, subprocess.SubprocessError):
        device = None
    if not device:
        yield None
        return
    with tempfile.TemporaryDirectory(prefix='harness-usb-') as folder:
        try:
            run('mount', '-o', 'ro', device, folder)
        except subprocess.CalledProcessError:
            yield None
            return
        try:
            yield Path(folder) if all((Path(folder) / name).is_file() for name in recovery_files(kernel)) else None
        finally:
            run('umount', folder)


def write_recovery(partition, medium, kernel):
    """The recovery partition made anew, with the USB's files."""
    run('mkfs.ext4', '-F', '-q', '-L', RECOVERY_LABEL, partition)
    with tempfile.TemporaryDirectory(prefix='harness-recovery-') as folder:
        run('mount', partition, folder)
        try:
            for name in recovery_files(kernel):
                destination = Path(folder) / name
                destination.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(medium / name, destination)
            run('sync')
        finally:
            run('umount', folder)


def recovery_conf(uuid, kernel, parameters):
    """For 42_harness-recovery, as shell assignments. archisolabel: the live system finds itself on the
    recovery partition; copytoram=n keeps it there, mounted, rather than in RAM (validate_disk)."""
    arguments = ' '.join(['archisobasedir=arch', f'archisolabel={RECOVERY_LABEL}', 'copytoram=n',
                          'harness.recovery', 'quiet', *parameters])
    return f"RECOVERY_UUID='{uuid}'\nRECOVERY_KERNEL='{kernel}'\nRECOVERY_PARAMETERS='{arguments}'\n"


def install(config, source, target, progress=None):
    # All preserved platform data must outlive disk erasure and be released only
    # after installation/cleanup completes. There is no user-supplied platform
    # override: the selected image determines its kernel and preservation needs.
    with ExitStack() as resources:
        return install_image(config, source, target, progress, resources)


def install_image(config, source, target, progress, resources):
    report = progress or (lambda message: print(message, flush=True))
    validate_config(config)
    require_install_platform()
    # Inspect again immediately before partitioning, rather than trusting the picker.
    selected_disk(config)
    if not source.is_file():
        raise ValueError('Live system payload is missing; boot the Harness USB.')
    if target.exists() and any(target.iterdir()):
        raise ValueError('Installation mountpoint is not empty.')
    if config.get('confirm_erase') != config['disk']:
        raise ValueError('Explicit confirmation of the exact disk is required.')
    report('Checking installation files…')
    kernel = preflight(config, source)
    platform = boot_module().selected()
    preserved = None
    if platform['id'] == 'apple-t2':
        report('Preserving this Mac’s wireless firmware…')
        preserved = resources.enter_context(boot_module().module('t2_install').preserve(config['disk']))
    recovering = config.get('recovery') is True
    trial = None if recovering else trial_source(config)
    selected_disk(config)
    pbkdf_memory = encryption_memory() if config['encrypt'] else None
    started = time.monotonic()
    disk = config['disk']
    _, boot, root_partition = partitions(disk)
    recovery = recovery_partition(disk)
    # A PC's installation keeps a recovery when the USB's files are at hand and the disk has room beside
    # the system; the recovery keeps its own.
    roomy = int(selected_disk(config).get('size') or 0) >= RECOVERY_MIN_DISK_BYTES
    medium = (resources.enter_context(live_medium(platform['kernel']))
              if not recovering and platform['id'] == 'pc' and roomy else None)
    target.mkdir(parents=True, exist_ok=True)
    mapper = f'hn-install-{os.getpid()}'
    opened = False
    mounted = False
    try:
        report('Preparing the disk…')
        if recovering:
            # The same partitions: the recovery's own stays, and so does GRUB on the boot partition
            # until it is installed again, so a start cut short comes back here (recover).
            run('wipefs', '-a', root_partition)
        else:
            run('sgdisk', '--zap-all', disk)
            layout = ['-n', '1:1MiB:+2MiB', '-t', '1:ef02', '-c', '1:HN BIOS',
                      '-n', '2:0:+1GiB', '-t', '2:ef00', '-c', '2:HN BOOT',
                      '-n', '3:0:' + (f'-{RECOVERY_SIZE}' if medium else '0'),
                      '-t', '3:8309' if config['encrypt'] else '3:8300', '-c', '3:HN ROOT']
            if medium:
                layout += ['-n', '4:0:0', '-t', '4:8300', '-c', '4:HN RECOVERY']
            run('sgdisk', *layout, disk)
        run('udevadm', 'settle')
        if not recovering:
            run('mkfs.fat', '-F', '32', '-n', 'HNBOOT', boot)
        if medium:
            report('Keeping a recovery…')
            write_recovery(recovery, medium, platform['kernel'])
        if preserved:
            # Make the validated firmware discoverable on a retry/reinstall,
            # before encryption or the larger root copy can fail.
            boot_module().module('t2_install').persist_boot(boot, preserved)
        root_device = root_partition
        luks_uuid = None
        if config['encrypt']:
            report('Setting up encryption…')
            secret = config['password'].encode()
            run('cryptsetup', 'luksFormat', '--type', 'luks2', '--batch-mode',
                '--pbkdf-memory', pbkdf_memory, '--key-file=-', root_partition, input=secret)
            run('cryptsetup', 'open', '--key-file=-', root_partition, mapper, input=secret)
            opened = True
            root_device = f'/dev/mapper/{mapper}'
            luks_uuid = run('blkid', '-s', 'UUID', '-o', 'value', root_partition, capture=True)
        run('mkfs.btrfs', '-f', '-L', 'HNROOT', root_device)
        run('mount', root_device, target)
        mounted = True
        for name in ('@', '@home', '@snapshots'):
            run('btrfs', 'subvolume', 'create', target / name)
        run('umount', target)
        mounted = False
        run('mount', '-o', 'subvol=@,compress=zstd:1,noatime', root_device, target)
        mounted = True
        for name, subvol in [('home', '@home'), ('.snapshots', '@snapshots')]:
            (target / name).mkdir()
            run('mount', '-o', f'subvol={subvol},compress=zstd:1,noatime', root_device, target / name)
        report('Copying Harness…')
        # Unsquashfs defaults to 512 MiB of caches. Bound them so installation
        # still fits on a 1 GiB machine after trying the bundled agent/browser.
        copy_image(source, target)
        # Extract on Btrfs first: FAT cannot represent the image's Unix metadata.
        # Copy boot contents without that metadata before regenerating initramfs.
        boot_staging = target / 'boot.from-image'
        (target / 'boot').rename(boot_staging)
        (target / 'boot').mkdir()
        run('mount', boot, target / 'boot')
        for path in boot_staging.rglob('*'):
            destination = target / 'boot' / path.relative_to(boot_staging)
            if path.is_dir():
                destination.mkdir(parents=True, exist_ok=True)
            elif path.is_file():
                destination.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(path, destination)
        shutil.rmtree(boot_staging)
        # mkarchiso moves the live /boot files out of SquashFS. Regenerate the
        # disk initramfs around this verified, package-owned kernel instead.
        shutil.copyfile(target / kernel['path'], target / ('boot/vmlinuz-' + platform['kernel']))
        apple_firmware = boot_module().module('t2_install').restore(target, preserved) if preserved else None
        report('Setting up your account…')
        # The live image is immutable. Only projects is transferred explicitly;
        # live account passwords, agent credentials, SSH keys and sessions stay out.
        for path in ['etc/sudoers.d/10-live', 'etc/mkinitcpio.conf.d/archiso.conf',
                     'etc/systemd/system/[email protected]/live.conf',
                     'etc/pacman.d/hooks/99-harness-live.hook', 'root/setup-live.sh',
                     'etc/systemd/system/harness-recovery.service',
                     'etc/systemd/system/multi-user.target.wants/harness-recovery.service']:
            (target / path).unlink(missing_ok=True)
        for path in ['etc/systemd/system/[email protected]', 'root/.ssh']:
            shutil.rmtree(target / path, ignore_errors=True)
        if (target / 'etc/passwd').read_text().find('\nme:') >= 0:
            chroot(target, 'userdel', '-r', 'me')
        chroot(target, 'useradd', '-m', '-G', 'wheel,video,audio', '-s', '/bin/bash', config['username'])
        chroot(target, 'chpasswd', input=f"{config['username']}:{config['password']}\n".encode())
        save_initial_password(target, config)
        chroot(target, 'passwd', '-l', 'root')
        (target / 'var/lib/systemd/linger/me').unlink(missing_ok=True)
        write(target, f'/var/lib/systemd/linger/{config["username"]}', '')
        home = target / 'home' / config['username']
        (home / 'projects').mkdir(exist_ok=True)
        if trial is not None:
            report('Keeping your trial projects…')
        trial_receipt = preserve_trial(trial, target, home)
        chroot(target, 'chown', '-Rh', f"{config['username']}:{config['username']}", f"/home/{config['username']}")
        write(target, '/etc/sudoers.d/10-harness', '%wheel ALL=(ALL:ALL) ALL\n', 0o440)
        write(target, '/etc/hostname', config['hostname'] + '\n')
        write(target, '/etc/hosts', f"127.0.0.1 localhost\n::1 localhost\n127.0.1.1 {config['hostname']}\n")
        write(target, '/etc/machine-id', '')
        # Encrypted: the setup hotspot comes up while the disk waits for its password, for a phone to
        # send it (harness-unlock), beside the screen's own prompt.
        write(target, '/etc/mkinitcpio.conf',
              'HOOKS=(base systemd autodetect microcode modconf kms keyboard sd-vconsole '
              + ('plymouth ' if config['encrypt'] else '')
              + 'block ' + ('harness-unlock ' if config['encrypt'] else '')
              + 'sd-encrypt filesystems fsck)\nCOMPRESSION="zstd"\n')
        if platform['modules']:
            write(target, '/etc/mkinitcpio.conf.d/20-harness-platform.conf',
                  'MODULES+=(' + ' '.join(platform['modules']) + ')\n')
        write(target, '/etc/vconsole.conf', 'KEYMAP=us\n')
        if config['encrypt']:
            write(target, '/etc/plymouth/plymouthd.conf',
                  '[Daemon]\nTheme=harness\nShowDelay=0\nDeviceTimeout=5\n')
        root_uuid = run('blkid', '-s', 'UUID', '-o', 'value', root_device, capture=True)
        boot_uuid = run('blkid', '-s', 'UUID', '-o', 'value', boot, capture=True)
        write(target, '/etc/fstab',
              f'UUID={root_uuid} / btrfs subvol=@,compress=zstd:1,noatime 0 0\n'
              f'UUID={root_uuid} /home btrfs subvol=@home,compress=zstd:1,noatime 0 0\n'
              f'UUID={root_uuid} /.snapshots btrfs subvol=@snapshots,compress=zstd:1,noatime 0 0\n'
              f'UUID={boot_uuid} /boot vfat umask=0077 0 2\n')
        # The disk-unlock password is the authentication step on encrypted installs.
        # Unencrypted installs require a normal console login instead of autologin.
        if config['encrypt']:
            write(target, '/etc/systemd/system/[email protected]/autologin.conf',
                  '[Service]\nExecStart=\n' + f'ExecStart=-/usr/bin/agetty --autologin {config["username"]} --noclear %I $TERM\n')
        else:
            # The one account is known: only its password is asked, as the disk's would be.
            write(target, '/etc/systemd/system/[email protected]/password.conf',
                  '[Service]\nExecStart=\n' + f"ExecStart=-/usr/bin/agetty --skip-login --login-options '-p -- {config['username']}' --noclear %I $TERM\n")
        # A USB built with HARNESS_OS_KEEP_LOGS (build.sh) installs computers that keep their logs
        # across restarts, to read what went wrong after one. For testing; not set for a release.
        if KEEP_LOGS.is_file():
            write(target, '/etc/systemd/journald.conf.d/90-harness-keep-logs.conf', '[Journal]\nStorage=persistent\n')
        # An encrypted root cannot appear until its owner returns to unlock it.
        # Do not send a person who paused at the prompt into emergency mode.
        root_flags ='subvol=@' + (',x-systemd.device-timeout=0' if config['encrypt'] else '')
        kernel_args = f'quiet loglevel=3 rootflags={root_flags}'
        if platform['parameters']:
            kernel_args += ' ' + ' '.join(platform['parameters'])
        if config.get('serial_console'):
            # Keep the screen as /dev/console, as on an ordinary installation.
            # Making the diagnostic serial port primary can introduce serial-TTY
            # setup delays before Plymouth can display its unlock prompt.
            kernel_args += ' console=ttyS0,115200 console=tty0 plymouth.ignore-serial-consoles'
        if luks_uuid:
            # tries=0: asked again however often it is wrong, as an open hotspot lets anyone try
            # (the page slows them down); three wrong ones used to stop the computer starting.
            kernel_args += f' rd.luks.name={luks_uuid}=cryptroot rd.luks.options={luks_uuid}=tries=0 splash'
        write(target, '/etc/default/grub',
              'GRUB_DEFAULT=0\nGRUB_TIMEOUT=1\nGRUB_DISTRIBUTOR="Harness"\n'
              'GRUB_DISABLE_OS_PROBER=true\n' + f'GRUB_CMDLINE_LINUX="{kernel_args}"\n')
        recovery_uuid = None
        if medium or recovering:
            recovery_uuid = run('blkid', '-s', 'UUID', '-o', 'value', recovery, capture=True)
            write(target, RECOVERY_CONF, recovery_conf(recovery_uuid, platform['kernel'], platform['parameters']))
        lock = json.loads((target / 'usr/share/harness-os/lock.json').read_text())
        snapshot = lock['arch_snapshot']
        # IgnorePkg: OpenCode stays the one this image brought (tools/opencode_package.py), newer than its
        # snapshot's; a system update to a later snapshot never changes it (owner, 2026-11-03).
        write(target, '/etc/pacman.conf',
              '[options]\nArchitecture = auto\nCheckSpace\nSigLevel = Required DatabaseOptional\nLocalFileSigLevel = Optional\n'
              'IgnorePkg = opencode\n'
              + ''.join(f'[{repo}]\nServer = https://archive.archlinux.org/repos/{snapshot}/$repo/os/$arch\n' for repo in ['core', 'extra']))
        # Retain network configuration explicitly, not the live user's home or credentials.
        networks = Path('/etc/NetworkManager/system-connections')
        if networks.exists():
            shutil.copytree(networks, target / 'etc/NetworkManager/system-connections', dirs_exist_ok=True)
        chroot(target, 'systemctl', 'enable', 'NetworkManager', 'systemd-resolved', 'systemd-timesyncd',
               'harness-setup.service', 'harness-button.service')
        chroot(target, 'systemctl', 'disable', 'sshd.service')
        # Its account's daemon from the start (the user lingers), not only with a session at the
        # screen: a computer set up and unlocked from a phone may have no screen, or nobody at it.
        chroot(target, 'systemctl', '--global', 'enable', 'harness-daemon.service')
        report('Preparing startup and recovery…')
        chroot(target, '/usr/lib/harness-os/init-keyring')
        # Keep the live marker through this initial optional package transaction,
        # so recovery hooks do not checkpoint an unfinished installation.
        if platform['id'] == 'pc':
            run('/usr/bin/python3', '/usr/lib/harness-os/hardware.py', 'configure-install', target)
        (target / 'etc/harness-live').unlink()
        chroot(target, 'mkinitcpio', '-P')
        chroot(target, 'grub-install', '--target=i386-pc', '--recheck', disk)
        chroot(target, 'grub-install', '--target=x86_64-efi', '--efi-directory=/boot', '--boot-directory=/boot', '--removable', '--no-nvram')
        chroot(target, 'grub-mkconfig', '-o', '/boot/grub/grub.cfg')
        receipt = {'version': lock['version'], 'installed_at': datetime.now(timezone.utc).isoformat(),
                   'duration_seconds': round(time.monotonic() - started, 3), 'encrypted': config['encrypt'],
                   'disk_bytes': selected_size(config), 'root_uuid': root_uuid, 'boot_uuid': boot_uuid,
                   'platform': platform['id'], 'recovery_uuid': recovery_uuid, 'from_recovery': recovering}
        if apple_firmware:
            receipt['apple_firmware'] = apple_firmware
        if pbkdf_memory is not None:
            receipt['pbkdf_memory_limit_kib'] = pbkdf_memory
        if trial_receipt is not None:
            receipt['trial_projects'] = trial_receipt
        write(target, '/var/lib/harness-os/install.json', json.dumps(receipt, indent=2) + '\n')
        report('Finishing installation…')
        run('sync')
    finally:
        original_error = sys.exception()
        if original_error is not None:
            log_diagnostic(f'\nInstallation failed: {original_error}')
        try:
            if mounted:
                run('umount', '-R', target)
            if opened:
                close_install_mapping(mapper)
        except (OSError, subprocess.SubprocessError) as cleanup_error:
            if original_error is None:
                cleanup_error.add_note('Harness was written and synced. Shut down normally before removing the USB, then try booting the installed disk.')
                raise
            # Keep the actual installation failure visible. Cleanup is still
            # attempted and its failure is retained as additional information.
            detail = f'Disk cleanup also failed: {cleanup_error}'
            original_error.add_note(detail)
            log_diagnostic(detail)
    if progress is None:
        print(f"Installed in {receipt['duration_seconds']:.1f}s. Shut down, remove the USB, and boot the disk.", flush=True)


def selected_size(config):
    # After installation the target is mounted, so this is not a safety check.
    return next(int(d['size']) for d in inventory() if d['name'] == config['disk'])


def display_text(value):
    # Device metadata must not inject terminal controls or extra form rows.
    return ''.join(c if c.isprintable() else '?' for c in str(value or '')).strip()


def disk_label(disk, width=None):
    size = f"{int(disk['size']) / 1_000_000_000:.1f}".removesuffix('.0')
    model = display_text(disk.get('model')) or 'Disk'
    suffix = f'  {size} GB'
    if width is not None and len(model) + len(suffix) > width:
        model = model[:max(1, width - len(suffix) - 1)] + '…'
    return model + suffix


class InstallForm:
    """Small keyboard form using the Python/ncurses already in the image."""
    def __init__(self, screen, candidates, username, hostname, encrypt, notice=''):
        self.screen, self.disks = screen, candidates
        self.username, self.hostname, self.encrypt = username, hostname, encrypt
        self.selected, self.focus = 0, 2
        self.passwords, self.positions = ['', ''], [0, 0]
        self.error = ''
        self.notice = notice
        self.title = None
        self.cursor_visible = None
        self.top, self.left, self.width = 0, 2, 60
        self.accent = curses.A_BOLD
        try:
            if curses.has_colors():
                curses.start_color()
                curses.use_default_colors()
                curses.init_pair(1, curses.COLOR_YELLOW, -1)
                self.accent = curses.color_pair(1) | curses.A_BOLD
        except curses.error:
            pass

    def line(self, row, text, active=False, bold=False, accent=False, offset=0, span=None):
        height, width = self.screen.getmaxyx()
        row += self.top
        length = min(self.width - offset, width - self.left - offset - 1)
        if span is not None:
            length = min(length, span)
        if not 0 <= row < height or length <= 0:
            return
        attr = (curses.A_REVERSE if active else self.accent if accent else curses.A_NORMAL) | (curses.A_BOLD if bold else 0)
        if active:
            text = text.ljust(length)
        self.screen.addnstr(row, self.left + offset, text, length, attr)

    def field(self, row, label, value, active=False):
        self.line(row, f'{label:18}', span=18)
        self.line(row, value, active=active, offset=18)

    def button(self, row, text, active=False):
        label = '[ ' + text + ' ]'
        self.line(row, label, active=active, offset=(self.width - len(label)) // 2, span=len(label))

    def cursor(self, visible):
        if visible == self.cursor_visible:
            return
        try:
            curses.curs_set(int(visible))
        except curses.error:
            pass  # Some serial terminals cannot change cursor visibility.
        self.cursor_visible = visible

    def begin(self, title):
        if title != self.title:
            self.screen.clear()
            self.title = title
        else:
            self.screen.erase()
        height, width = self.screen.getmaxyx()
        self.top, self.left, self.width = 0, 2, max(1, width - 4)
        if height < 18 or width < 54:
            self.cursor(False)
            self.line(0, 'Resize terminal to at least 54 columns and 18 rows.')
            self.line(2, 'Esc cancels. No disk has been changed.')
            self.screen.refresh()
            if self.key() == '\x1b':
                raise KeyboardInterrupt('Cancelled.')
            return False
        self.width = min(60, width - 4)
        self.left = (width - self.width) // 2
        self.top = max(0, (height - (22 if height >= 24 else 18)) // 2)
        if height >= 24:
            for row, word in enumerate(WORDMARK):
                self.line(row, word.center(self.width), accent=True)
            self.top += 4
        if title:
            self.line(1, title, bold=True)
        return True

    def key(self):
        key = self.screen.get_wch()
        if key == '\x03':
            raise KeyboardInterrupt('Cancelled.')
        return key

    @staticmethod
    def enter(key):
        return key in ('\n', '\r', curses.KEY_ENTER)

    def pick_disk(self):
        selected = self.selected
        while True:
            if not self.begin('Select disk'):
                continue
            height, _ = self.screen.getmaxyx()
            count = max(1, height - self.top - 7)
            start = (selected // count) * count
            for index in range(start, min(start + count, len(self.disks))):
                disk = self.disks[index]
                row = 4 + index - start
                name = display_text(disk['name'])
                label = disk_label(disk, self.width - len(name) - 4)
                self.line(row, ('> ' if index == selected else '  ') + label + '  ' + name, index == selected)
            self.cursor(False)
            self.screen.refresh()
            key = self.key()
            if key == '\x1b':
                return
            if self.enter(key):
                self.selected = selected
                return
            if key in (curses.KEY_UP, curses.KEY_BTAB):
                selected = (selected - 1) % len(self.disks)
            elif key in (curses.KEY_DOWN, '\t'):
                selected = (selected + 1) % len(self.disks)

    def edit_password(self, index, key):
        value, position = self.passwords[index], self.positions[index]
        if key in (curses.KEY_BACKSPACE, '\x7f', '\b') and position:
            value, position = value[:position - 1] + value[position:], position - 1
        elif key == curses.KEY_DC:
            value = value[:position] + value[position + 1:]
        elif key == '\x15':  # Ctrl+U clears a hidden field without revealing it.
            value, position = '', 0
        elif key == curses.KEY_LEFT:
            position = max(0, position - 1)
        elif key == curses.KEY_RIGHT:
            position = min(len(value), position + 1)
        elif key == curses.KEY_HOME:
            position = 0
        elif key == curses.KEY_END:
            position = len(value)
        elif isinstance(key, str) and key.isprintable() and len(value) < 4096:
            value, position = value[:position] + key + value[position:], position + len(key)
        self.passwords[index], self.positions[index] = value, position
        self.error = ''

    def run(self):
        self.screen.keypad(True)
        while True:
            if not self.begin(''):
                continue
            for row, line in enumerate(textwrap.wrap(self.notice, self.width)):
                self.line(1 + row, line, accent=True)
            disk = self.disks[self.selected]
            # Identical models/capacities need a visible discriminator after selection.
            duplicate = sum(disk_label(d) == disk_label(disk) for d in self.disks) > 1
            suffix = '  ' + Path(disk['name']).name if duplicate else ''
            label = disk_label(disk, self.width - 18 - len(suffix)) + suffix
            self.field(4, 'Disk', label, self.focus == 0)
            self.field(6, 'Encryption', f"[{'x' if self.encrypt else ' '}]", self.focus == 1)
            capacity = self.width - 20
            for index, label in enumerate(('Password', 'Repeat password')):
                position = self.positions[index]
                offset = max(0, position - capacity + 1)
                mask = '*' * len(self.passwords[index][offset:offset + capacity])
                self.field(8 + index * 2, label, f'[{mask:<{capacity}}]', self.focus == index + 2)
            self.line(12, self.error)
            self.line(14, 'Install Harness'.center(self.width), active=True, bold=self.focus == 4)
            self.cursor(self.focus in (2, 3))
            if self.focus in (2, 3):
                position = self.positions[self.focus - 2]
                self.screen.move(self.top + 8 + (self.focus - 2) * 2,
                                 self.left + 19 + min(position, capacity - 1))
            self.screen.refresh()
            key = self.key()
            if key == '\x1b':
                raise KeyboardInterrupt('Cancelled.')
            if key in ('\t', curses.KEY_DOWN):
                self.focus = (self.focus + 1) % 5
            elif key in (curses.KEY_BTAB, curses.KEY_UP):
                self.focus = (self.focus - 1) % 5
            elif key == ' ' and self.focus == 1:
                self.encrypt = not self.encrypt
            elif self.enter(key):
                if self.focus == 0:
                    self.pick_disk()
                elif self.focus == 1:
                    self.encrypt = not self.encrypt
                elif self.focus in (2, 3):
                    self.focus += 1
                else:
                    config = dict(disk=disk['name'], username=self.username, hostname=self.hostname,
                                  encrypt=self.encrypt, password=self.passwords[0],
                                  expected_serial=str(disk.get('serial') or '').strip())
                    try:
                        validate_config(config)
                        if self.passwords[0] != self.passwords[1]:
                            raise ValueError('Passwords do not match.')
                        selected_disk(config)
                    except ValueError as error:
                        self.error = str(error)
                        continue
                    config['confirm_erase'] = disk['name']
                    return config
            elif self.focus in (2, 3):
                self.edit_password(self.focus - 2, key)


def interactive(username='me', hostname='harness', encrypt=True):
    candidates = []
    for disk in inventory():
        try:
            validate_disk(disk)
        except ValueError:
            continue
        candidates.append(disk)
    if not candidates:
        raise ValueError('No unmounted, writable whole disk of at least 12 GiB is available.')
    validate_config(dict(username=username, hostname=hostname, encrypt=encrypt,
                         disk=candidates[0]['name'], password='validation-only'))
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        raise ValueError('Interactive installation needs a terminal. Use --config for unattended installation.')
    curses.set_escdelay(25)
    notice = installation_notice()
    return curses.wrapper(lambda screen: InstallForm(screen, candidates, username, hostname, encrypt, notice).run())


def completion(screen, boot=False):
    """Keep success visible when the installer owns an hn pane, then shut down on request."""
    screen.keypad(True)
    if boot:
        curses.raw()
    curses.flushinp()
    view = InstallForm(screen, [], 'me', 'harness', True)
    view.cursor(False)
    selected = 0
    while True:
        if not view.begin(''):
            continue
        paragraph = 'Harness is installed. Shut down, remove the USB, then turn on your computer.'
        for row, line in enumerate(textwrap.wrap(paragraph, min(48, view.width))):
            view.line(4 + row, line.center(view.width))
        view.button(8, 'Shut down', active=selected == 0)
        if not boot:
            view.button(10, 'Back to Harness', active=selected == 1)
        screen.refresh()
        key = screen.get_wch()
        if key in ('\x1b', '\x03') and not boot:
            return False
        if key in ('\t', curses.KEY_BTAB, curses.KEY_UP, curses.KEY_DOWN) and not boot:
            selected = 1 - selected
        elif InstallForm.enter(key):
            return selected == 0


def install_with_progress(screen, config, source, target):
    """A static text view: real stages, no invented percentage or extra process."""
    view = InstallForm(screen, [], config['username'], config['hostname'], config['encrypt'])
    view.cursor(False)

    def render(message):
        # A resize must never pause a disk operation waiting for keyboard input.
        screen.erase()
        height, width = screen.getmaxyx()
        if height > 0 and width > 1:
            middle = height // 2
            if height >= 8:
                for row, word in enumerate(WORDMARK):
                    screen.addnstr(middle - 3 + row, max(0, (width - len(word)) // 2), word,
                                   width - 1, view.accent)
            screen.addnstr(min(height - 1, middle + 1), max(0, (width - len(message)) // 2), message, width - 1)
        screen.refresh()

    def progress(message):
        if COMMAND_LOG:
            COMMAND_LOG.write('\n' + message + '\n')
            COMMAND_LOG.flush()
        try:
            render(message)
        except curses.error:
            # A display resize or lost terminal is not a reason to interrupt a
            # disk transaction. Its diagnostics and final status are retained.
            pass

    global LAST_LOG
    with command_log(INSTALL_LOG):
        LAST_LOG = INSTALL_LOG
        install(config, source, target, progress=progress)


def arguments():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--config', type=Path)
    parser.add_argument('--username', help='Override the default local account name (me)')
    parser.add_argument('--hostname', help='Override the default computer name (harness)')
    parser.add_argument('--no-encryption', action='store_true', help='Explicitly install without disk encryption')
    parser.add_argument('--yes-erase-disk', action='store_true')
    parser.add_argument('--source', type=Path, help='Override the automatically detected live system image')
    parser.add_argument('--boot', action='store_true', help=argparse.SUPPRESS)
    parser.add_argument('--recover', action='store_true', help=argparse.SUPPRESS)
    args = parser.parse_args()
    if args.boot and (args.config or not Path('/etc/harness-live').is_file()):
        parser.error('--boot is only for the interactive Harness USB installer.')
    if args.recover and (args.config or not Path('/etc/harness-live').is_file()):
        parser.error('--recover is only for the recovery partition (harness-recovery.service).')
    return args


def next_start(boot, entry):
    """What GRUB starts next, once (grubenv on the boot partition): [entry], or the system."""
    with tempfile.TemporaryDirectory(prefix='harness-boot-') as folder:
        run('mount', boot, folder)
        try:
            env = Path(folder) / 'grub/grubenv'
            if env.parent.is_dir():
                env.write_bytes(grubenv(entry))
            run('sync')
        finally:
            run('umount', folder)


def recover():
    """The recovery started (harness-recovery.service, at a power button's reset): this computer installed
    again from it, on the disk it is on, as it came — encrypted with a new key and RECOVERY_PASSWORD,
    nothing of the person kept — then started again. Its GRUB entry is asked for again first: a start cut
    short (the power went) comes back here, not to a half-written system."""
    partition = run('blkid', '-L', RECOVERY_LABEL, capture=True)
    disk = '/dev/' + run('lsblk', '-no', 'PKNAME', partition, capture=True).splitlines()[0].strip()
    if recovery_partition(disk) != partition:
        raise ValueError(f'The recovery is not where it belongs on {disk}.')
    device = next(d for d in inventory() if d['name'] == disk)
    boot = partitions(disk)[1]
    print('Resetting Harness to as it came. This takes a few minutes; do not turn it off.', flush=True)
    next_start(boot, RECOVERY_ENTRY)
    config = dict(username='me', hostname='harness', password=RECOVERY_PASSWORD, encrypt=True, disk=disk,
                  confirm_erase=disk, expected_serial=str(device.get('serial') or '').strip(), recovery=True)
    install(config, live_payload(), Path('/mnt/harness-os'), progress=lambda message: print(message, flush=True))
    next_start(boot, None)
    print('Reset. Starting again…', flush=True)
    run('systemctl', 'reboot')


def finish_installation(boot=False):
    # A failed poweroff must return to success, never restart disk installation.
    while curses.wrapper(lambda screen: completion(screen, boot=boot)):
        try:
            run('systemctl', 'poweroff')
            return
        except (OSError, subprocess.SubprocessError) as error:
            if not boot:
                raise
            print(f'Harness is installed. Could not shut down: {error}', file=sys.stderr)
            try:
                input('Press Enter to try shutting down again.')
            except (EOFError, KeyboardInterrupt):
                pass


def main(args=None):
    args = arguments() if args is None else args
    if os.geteuid() != 0:
        raise SystemExit('Run sudo harness install from the live USB.')
    require_install_platform()
    if getattr(args, 'recover', False):
        recover()
        return
    if args.config:
        if args.username is not None or args.hostname is not None or args.no_encryption:
            raise ValueError('With --config, set account names and encryption in that file instead of command-line overrides.')
        config = json.loads(args.config.read_text())
        if not args.yes_erase_disk or not config.get('expected_serial'):
            raise ValueError('Unattended installs require --yes-erase-disk and an exact expected_serial.')
        source = live_payload(args.source)
    else:
        if args.yes_erase_disk:
            raise ValueError('--yes-erase-disk requires a configuration file.')
        # Fail before collecting passwords if neither supported boot mode has
        # an image. An explicit missing --source never falls back silently.
        source = live_payload(args.source)
        config = interactive(username=args.username if args.username is not None else 'me',
                             hostname=args.hostname if args.hostname is not None else 'harness',
                             encrypt=not args.no_encryption)
    if args.config:
        install(config, source, Path('/mnt/harness-os'))
    else:
        curses.wrapper(lambda screen: install_with_progress(screen, config, source, Path('/mnt/harness-os')))
        finish_installation(boot=getattr(args, 'boot', False))


def entrypoint():
    args = arguments()
    boot = getattr(args, 'boot', False)
    while True:
        try:
            main(args)
            return 0
        except KeyboardInterrupt:
            if not boot:
                return 130
        except (ValueError, OSError, curses.error, subprocess.SubprocessError) as error:
            print(f'Installation stopped: {error}', file=sys.stderr, flush=True)
            for note in getattr(error, '__notes__', ()):
                print(note, file=sys.stderr, flush=True)
            if not args.config and LAST_LOG is not None:
                print(f'Details: {LAST_LOG}', file=sys.stderr, flush=True)
            # Interactive failures stay visible until acknowledged. On USB,
            # cancellation or failure returns to a fresh form, never a trial.
            if not args.config and sys.stdin.isatty() and sys.stderr.isatty():
                try:
                    input('Press Enter to try again.' if boot else 'Press Enter to return to Harness.')
                except (EOFError, KeyboardInterrupt):
                    pass
            if not boot:
                return 1


if __name__ == '__main__':
    sys.exit(entrypoint())