garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /xtask/src/main.rs

raw

//! `cargo xtask <command>`: building, booting and checking the kernel.
//!
//! - `build [board]`  build the kernel ELF for a board (default `qemu-virt`)
//! - `image [board]`  the same as a boot image, the format U-Boot and QEMU take
//! - `sdcard`         a directory for an RK3399 board's SD card (docs/hardware.md)
//! - `run`            boot the system in QEMU, the serial port on this terminal
//!   (its disks in `target/` kept between runs)
//! - `bundle [pc]`    the system to run elsewhere, in a window, with only QEMU:
//!   `target/pinnacle/` (and `target/pinnacle.tar.gz`), started by its `start`;
//!   with `pc` the x86-64 system, `target/pinnacle-pc/`, which runs on KVM
//!   on a Linux PC
//! - `disks`         make the system disk and the package source afresh
//! - `shot [png] [after]` boot it and photograph the screen once the serial
//!   port prints the line `after` (default "running")
//! - `lit-shot [png]` boot it as on a board whose loader lit the screen (a
//!   `simple-framebuffer` in the device tree) and photograph that screen's
//!   memory once its first screen is up
//! - `test`           boot it in QEMU at EL1 and at EL2, as an ELF, as an Image
//!   and as an Image it must move, and check each run passes the boot
//!   self-check (memory, interrupts, the scheduler, six cores, programs)
//! - `demo`           drive the system like a person, a screenshot each step,
//!   into `target/demo`
//! - `pc-demo`        the PC (x86-64) used: its apps opened, one installed
//!   from the Store, a screenshot each, into `target/demo-pc`
//! - `pair`           two devices messaging each other with no server, a
//!   screenshot each step, into `target/demo-pair`
//! - `gate`           what a landing must pass: formatting, lints, the boards'
//!   boot image, `test`
//! - `venus-gen`      Vulkan's types and Venus's encoders, generated from
//!   `venus/registry` into `venus/src/vk.rs` and `venus/src/encode.rs`, and
//!   the Vulkan driver's functions into `vulkan/src/commands.rs`
//! - `cartopolis <checkout>` Cartopolis's client built for Pinnacle, from a
//!   checkout of its repo, installed on the system disk and run
//! - `package-cartopolis <checkout> <out> <version>` the same client as a
//!   package source in `<out>`, unsigned, for the hosted Store
//!   (`docs/store.md`)
//! - `package-flitz <checkout> <out> <version>` Flitz, the web browser, as
//!   a package source in `<out>`, unsigned, for the hosted Store
//! - `package-apps <out> <version>` the Store's apps, ARM's and a PC's, as
//!   a package source in `<out>`, unsigned, for the hosted Store
//! - `store-demo`     Cartopolis installed from the hosted Store and opened,
//!   a screenshot each step, into `target/demo-store`
//! - `updates-demo`   an app brought to a new version by the updates service,
//!   told first, then installed by itself, into `target/demo-updates`
//! - `system-update-demo [pc]` a newer system fetched and started at a restart,
//!   then a broken one tried and fallen back from, into
//!   `target/demo-system-update` (a PC's: `-pc`; `docs/updates.md`)
//! - `package-system <out> <version>` the system for each board that hands
//!   over, as a package source in `<out>/system/<board>/`, unsigned
//! - `loader [pc]`, `installer [pc]`, `install-test [pc]`, `install-demo
//!   [pc]`: Pinnacle's UEFI loader, an install medium for a USB stick, and
//!   installing from it onto a disk in QEMU (`install.rs`)
//! - `firmware`       the closed firmware `firmware/*.txt` describes (Intel's
//!   Wi-Fi), fetched into `target/firmware/` and checked (`firmware.rs`); a
//!   PC's system disk carries it unless `PINNACLE_NO_FIRMWARE=1`

mod firmware;
mod install;
mod model;
mod profile;
mod unicode;
mod venus_gen;

use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use std::time::{Duration, Instant};

/// Programs: ARM64 with its FP/SIMD registers.
const TARGET: &str = "aarch64-unknown-none";
/// The kernel never touches the FP/SIMD registers, so it need not save them
/// around every exception: they belong to programs, switched lazily.
const KERNEL_TARGET: &str = "aarch64-unknown-none-softfloat";
const BOARDS: &[&str] = &["qemu-virt", "rk3399"];
/// How long a boot may take: 30 s, and 3 s more for each core past six,
/// which QEMU emulates on the host's few (16 cores took a little over 30 s
/// on vps-1's six).
fn boot_timeout() -> Duration {
    Duration::from_secs(30 + 3 * cores().saturating_sub(6) as u64)
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let result = match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
        ["build"] => build("qemu-virt").map(|elf| println!("{}", elf.display())),
        ["build", board] => build(board).map(|elf| println!("{}", elf.display())),
        ["run"] => run(),
        ["bundle"] => bundle(Arch::Arm).map(|tar| println!("{}", tar.display())),
        ["bundle", "pc"] => bundle(Arch::Pc).map(|tar| println!("{}", tar.display())),
        ["image"] => image("qemu-virt").map(|path| println!("{}", path.display())),
        ["image", board] => image(board).map(|path| println!("{}", path.display())),
        ["sdcard"] => sdcard().map(|dir| println!("{}", dir.display())),
        ["shot"] => shot(&root().join("target/shot.png"), "running"),
        ["shot", out] => shot(Path::new(out), "running"),
        ["shot", out, after] => shot(Path::new(out), after),
        ["lit-shot"] => lit_shot(&root().join("target/lit-shot.png")),
        ["lit-shot", out] => lit_shot(Path::new(out)),
        ["pc-shot"] => pc_shot(&root().join("target/shot-pc.png"), "launcher:"),
        ["pc-shot", out, after] => pc_shot(Path::new(out), after),
        ["demo"] => demo(),
        ["app", title] => app_shot(title),
        ["contacts-demo"] => contacts_demo(),
        ["files-demo"] => files_demo(),
        ["sms-demo"] => sms_demo(),
        ["notices-demo"] => notices_demo(),
        ["network-demo"] => network_demo(),
        ["bluetooth-demo"] => bluetooth_only_demo(),
        ["pinebook-demo"] => pinebook_demo(),
        ["access-demo"] => access_demo(),
        ["sound-demo"] => sound_demo(),
        ["updates-demo"] => updates_demo(),
        ["wifi-demo"] => wifi_demo(),
        ["fien-demo"] => fien_demo(),
        ["kees-demo"] => kees_demo(),
        ["fien-pair-demo"] => fien_pair_demo(),
        ["pair"] => pair(),
        ["remote"] => remote(),
        ["sync-demo"] => sync_demo(),
        ["backup-demo"] => backup_demo(),
        ["disks"] => {
            disks("http://10.0.2.2:8080/").map(|s| println!("{}\n{}", s.display(), repository().display()))
        }
        ["std"] => build_std(),
        ["ports"] => build_ports_check().map(drop),
        ["winit-demo"] => winit_demo(),
        ["wgpu-demo"] => wgpu_demo(),
        ["cartopolis", source] => cartopolis(Path::new(source)),
        ["flitz", source] => flitz(Path::new(source)),
        ["store-demo"] => store_demo(),
        ["package-apps", out, version] => package_apps(Path::new(out), version),
        ["package-system", out, version] => package_systems(Path::new(out), version),
        ["system-update-demo"] => system_update_demo(false),
        ["system-update-demo", "pc"] => system_update_demo(true),
        ["time-demo"] => time_demo(),
        ["package-cartopolis", source, out, version] => {
            package_cartopolis(Path::new(source), Path::new(out), version)
        }
        ["package-flitz", source, out, version] => package_flitz(Path::new(source), Path::new(out), version),
        ["terminal-demo"] => terminal_demo(),
        ["frits-demo"] => frits_demo(),
        ["pipeline-demo"] => pipeline_demo(),
        ["admin-demo"] => admin_demo(),
        ["agent-demo"] => agent_demo(),
        ["workbench-demo"] => workbench_demo(false),
        ["workbench-demo", "real"] => workbench_demo(true),
        ["ports-lock"] => lock_ports(),
        ["venus-gen"] => venus_gen::run(root()),
        ["unicode", ucd] => unicode::run(Path::new(ucd), &root().join("text/src/tables.rs")),
        ["profile", log, elfs @ ..] => profile::run(Path::new(log), elfs),
        ["test"] => test(),
        ["https"] => https("https://example.com/"),
        ["https", url] => https(url),
        ["gate"] => gate(),
        ["pc"] => pc(),
        ["pc-efi"] => pc_efi(),
        ["pc-demo"] => pc_demo(),
        ["loader"] => install::loader(Arch::Arm).map(|p| println!("{}", p.display())),
        ["loader", "pc"] => install::loader(Arch::Pc).map(|p| println!("{}", p.display())),
        ["installer"] => install::medium(Arch::Arm, "").map(drop),
        ["installer", "pc"] => install::medium(Arch::Pc, "").map(drop),
        ["install-test"] => install::test(Arch::Arm),
        ["install-test", "pc"] => install::test(Arch::Pc),
        ["install-demo"] => install::demo(Arch::Arm),
        ["install-demo", "pc"] => install::demo(Arch::Pc),
        ["laptop"] => install::laptop(),
        ["firmware"] => firmware::fetch_all(),
        _ => Err(
            "usage: cargo xtask build|image [qemu-virt|rk3399] | sdcard | run | bundle [pc] | test | gate | pair | remote"
                .into(),
        ),
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("xtask: {e}");
            ExitCode::FAILURE
        }
    }
}

type Result<T = ()> = std::result::Result<T, String>;

fn root() -> &'static Path {
    Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap()
}

/// The programs the kernel embeds (`programs/`), packed into one archive,
/// which every kernel build and lint is handed through `PINNACLE_PROGRAMS`.
fn programs_archive() -> PathBuf {
    root().join("target/programs.ppak")
}

fn cargo(args: &[&str]) -> Result {
    cargo_with(args, &programs_archive(), &[])
}

/// As [`cargo`], handing the kernel `programs` and setting `env`.
fn cargo_with(args: &[&str], programs: &Path, env: &[(&str, &str)]) -> Result {
    let status = Command::new(env!("CARGO"))
        .args(args)
        .env("PINNACLE_PROGRAMS", programs)
        .envs(env.iter().copied())
        .current_dir(root())
        .status()
        .map_err(|e| format!("cargo: {e}"))?;
    status
        .success()
        .then_some(())
        .ok_or_else(|| format!("cargo {} failed", args.join(" ")))
}

/// Builds every program and packs them for the kernel: `PPAK`, a count,
/// then per program a 16-bit name length, the name, a 32-bit size and the
/// ELF (`kernel/src/programs.rs` reads it).
fn build_user() -> Result {
    cargo(&[
        "build",
        "--locked",
        "-p",
        "pinnacle-programs",
        "--release",
        "--target",
        TARGET,
    ])?;
    build_std()?;
    let paths = SYSTEM_PROGRAMS
        .iter()
        .map(|name| {
            (
                *name,
                root().join("target").join(TARGET).join("release").join(name),
            )
        })
        .chain(STD_PROGRAMS.iter().map(|name| (*name, std_program(name))));
    let mut archive = b"PPAK".to_vec();
    archive.extend_from_slice(&((SYSTEM_PROGRAMS.len() + STD_PROGRAMS.len()) as u32).to_le_bytes());
    for (name, path) in paths {
        let elf = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
        // The system programs as the kernel loads them: their debug info
        // stays in target/ for `profile`, not in the kernel (95 MB with it,
        // a system update of 119 MB).
        let elf = if SYSTEM_PROGRAMS.contains(&name) {
            loadable(elf)?
        } else {
            elf
        };
        archive.extend_from_slice(&(name.len() as u16).to_le_bytes());
        archive.extend_from_slice(name.as_bytes());
        archive.extend_from_slice(&(elf.len() as u32).to_le_bytes());
        archive.extend_from_slice(&elf);
    }
    write_if_changed(&programs_archive(), &archive)
}

/// An ELF cut to what a loader reads: its header, its program headers and
/// the bytes its segments load. The section headers, the symbols and the
/// debug info after them go (`process.rs` reads none of them).
fn loadable(mut elf: Vec<u8>) -> Result<Vec<u8>> {
    let at = |elf: &[u8], offset: usize, len: usize| -> Result<u64> {
        let bytes = elf.get(offset..offset + len).ok_or("a truncated ELF")?;
        Ok(bytes.iter().rev().fold(0, |n, &b| n << 8 | u64::from(b)))
    };
    if elf.get(..5) != Some(b"\x7fELF\x02") {
        return Err("not a 64-bit ELF".into());
    }
    let (phoff, phentsize, phnum) = (
        at(&elf, 32, 8)? as usize,
        at(&elf, 54, 2)? as usize,
        at(&elf, 56, 2)? as usize,
    );
    let mut end = (phoff + phnum * phentsize).max(64);
    for i in 0..phnum {
        let header = phoff + i * phentsize;
        let (offset, size) = (at(&elf, header + 8, 8)?, at(&elf, header + 32, 8)?);
        end = end.max((offset + size) as usize);
    }
    if end > elf.len() {
        return Err("a segment past the ELF's end".into());
    }
    elf.truncate(end);
    // No section headers: e_shoff, e_shnum, e_shstrndx.
    elf[40..48].fill(0);
    elf[60..64].fill(0);
    Ok(elf)
}

/// The nightly Rust whose std Pinnacle's own is made from: its library's
/// source with `std/library.patch` applied (and the `abi` crate copied in).
/// A newer nightly needs the patch brought up to it (`std/README.md`).
const STD_TOOLCHAIN: &str = "nightly-2026-11-20";
/// Programs built against std: Pinnacle as an operating system Rust knows.
const STD_TARGET: &str = "aarch64-unknown-pinnacle";
/// Built against std, into the kernel with the system programs.
const STD_PROGRAMS: &[&str] = &["std-check"];

fn std_program(name: &str) -> PathBuf {
    root()
        .join("target/std")
        .join(STD_TARGET)
        .join("release")
        .join(name)
}

/// `rustup` for the std toolchain, with the stable toolchain's choice that
/// `cargo xtask` runs under taken away.
fn rustup() -> Command {
    let mut command = Command::new("rustup");
    command
        .env_remove("RUSTUP_TOOLCHAIN")
        .env_remove("RUSTC")
        .env_remove("CARGO");
    command
}

fn run_status(command: &mut Command, what: &str) -> Result {
    let status = command.status().map_err(|e| format!("{what}: {e}"))?;
    status
        .success()
        .then_some(())
        .ok_or_else(|| format!("{what} failed"))
}

/// Pinnacle's std library: the toolchain's library source, patched, in
/// `target/std-src/library`; made afresh when the patch or the ABI changes.
fn std_library() -> Result<PathBuf> {
    let sysroot = |r: &mut Command| -> Option<PathBuf> {
        let out = r
            .args(["run", STD_TOOLCHAIN, "rustc", "--print", "sysroot"])
            .output()
            .ok()?;
        out.status
            .success()
            .then(|| PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()))
    };
    let mut src = sysroot(&mut rustup()).map(|s| s.join("lib/rustlib/src/rust/library"));
    if !src.as_ref().is_some_and(|s| s.join("std").is_dir()) {
        run_status(
            rustup().args([
                "toolchain",
                "install",
                STD_TOOLCHAIN,
                "--profile",
                "minimal",
                "--component",
                "rust-src",
            ]),
            &format!("installing {STD_TOOLCHAIN}"),
        )?;
        src = sysroot(&mut rustup()).map(|s| s.join("lib/rustlib/src/rust/library"));
    }
    let src = src.ok_or(format!("{STD_TOOLCHAIN} has no sysroot"))?;
    let patch =
        std::fs::read(root().join("std/library.patch")).map_err(|e| format!("std/library.patch: {e}"))?;
    let abi = std::fs::read_to_string(root().join("abi/src/lib.rs")).map_err(|e| format!("abi: {e}"))?;
    // As a module of std: without the crate's own attributes, and each public
    // item marked stable, as std requires of what it offers (programs reach
    // it as `std::os::pinnacle::abi`).
    let mut module = String::new();
    for line in abi.lines().filter(|line| !line.starts_with("#![")) {
        let code = line.trim_start();
        if code.starts_with("pub ") {
            let indent = &line[..line.len() - code.len()];
            module += &format!("{indent}#[stable(feature = \"rust1\", since = \"1.0.0\")]\n");
        }
        module += line;
        module += "\n";
    }
    let abi = module;
    let stamp = format!(
        "{STD_TOOLCHAIN} {:08x} {:08x}",
        crc32(&patch),
        crc32(abi.as_bytes())
    );
    let base = root().join("target/std-src");
    let library = base.join("library");
    if std::fs::read_to_string(base.join("stamp")).ok().as_deref() == Some(&stamp) {
        return Ok(library);
    }
    if library.exists() {
        std::fs::remove_dir_all(&library).map_err(|e| format!("{}: {e}", library.display()))?;
    }
    copy_dir(&src, &library)?;
    // Applied as files, not in this repository: the ceiling keeps `git` from
    // finding the checkout around `target/`.
    run_status(
        Command::new("git")
            .args(["apply", "--whitespace=nowarn"])
            .arg(root().join("std/library.patch"))
            .env("GIT_CEILING_DIRECTORIES", &base)
            .current_dir(&library),
        "applying std/library.patch",
    )?;
    std::fs::write(library.join("std/src/sys/pal/pinnacle/abi.rs"), abi).map_err(|e| e.to_string())?;
    std::fs::write(base.join("stamp"), stamp).map_err(|e| e.to_string())?;
    Ok(library)
}

fn copy_dir(from: &Path, to: &Path) -> Result {
    std::fs::create_dir_all(to).map_err(|e| format!("{}: {e}", to.display()))?;
    for entry in std::fs::read_dir(from).map_err(|e| format!("{}: {e}", from.display()))? {
        let entry = entry.map_err(|e| e.to_string())?;
        let (path, target) = (entry.path(), to.join(entry.file_name()));
        if entry.file_type().map_err(|e| e.to_string())?.is_dir() {
            copy_dir(&path, &target)?;
        } else {
            std::fs::copy(&path, &target).map_err(|e| format!("{}: {e}", path.display()))?;
        }
    }
    Ok(())
}

/// Builds the programs written against std (`std/<name>`) with Pinnacle's
/// std, linked where the kernel loads programs.
fn build_std() -> Result {
    let library = std_library()?;
    let link = format!("-C link-arg=-T{}", root().join("programs/link.ld").display());
    for name in STD_PROGRAMS {
        let manifest = root()
            .join("std")
            .join(name.trim_start_matches("std-"))
            .join("Cargo.toml");
        run_status(
            rustup()
                .args(["run", STD_TOOLCHAIN, "cargo", "build", "--locked", "--release"])
                .args(["-Zbuild-std=std,panic_abort", "-Zjson-target-spec"])
                // memcpy, memset and the like from Rust's compiler-builtins:
                // there is no C library to bring them.
                .arg("-Zbuild-std-features=compiler-builtins-mem")
                .arg("--target")
                .arg(root().join("std").join(format!("{STD_TARGET}.json")))
                .arg("--manifest-path")
                .arg(&manifest)
                .arg("--target-dir")
                .arg(root().join("target/std"))
                // Where build-std takes the library from, rather than the
                // toolchain's own.
                .env("__CARGO_TESTS_ONLY_SRC_ROOT", &library)
                .env("RUSTFLAGS", &link)
                .current_dir(root()),
            &format!("building {name} against std"),
        )?;
    }
    Ok(())
}

/// Crates from crates.io with a Pinnacle branch added (`ports/`): the name a
/// build's `[patch]` gives it, the crate, and its folder. A port is of one
/// version; a build that resolves another leaves it unused (cargo warns).
const PORTS: &[(&str, &str, &str)] = &[
    ("getrandom02", "getrandom", "getrandom-0.2.17"),
    ("getrandom03", "getrandom", "getrandom-0.3.4"),
    ("getrandom", "getrandom", "getrandom-0.4.3"),
    ("errno", "errno", "errno-0.3.14"),
    ("hostname", "hostname", "hostname-0.4.2"),
    ("mio", "mio", "mio-1.2.4"),
    // The same port of the version before: which one a build resolves
    // depends on the crates.io index the machine has.
    ("mio122", "mio", "mio-1.2.2"),
    ("tokio", "tokio", "tokio-1.53.1"),
    ("winit", "winit", "winit-0.30.13"),
    ("bevy_asset", "bevy_asset", "bevy_asset-0.20.0"),
    ("ring", "ring", "ring-0.17.14"),
    // Servo's CSS engine, for Flitz: no raw thread handles on Pinnacle.
    ("stylo", "stylo", "stylo-0.24.0"),
    // `file:` URLs of Pinnacle's paths (`data:/a` is `file:///data:/a`).
    ("url", "url", "url-2.5.9"),
    // Vulkan from the driver linked in, not a library loaded (wgpu calls
    // ash::Entry::load).
    ("ash", "ash", "ash-0.38.0"),
    // Their Vulkan backend on Pinnacle too (it is on per platform).
    ("wgpu", "wgpu", "wgpu-30.0.1"),
    ("wgpu-core", "wgpu-core", "wgpu-core-30.0.1"),
    // A surface on a Pinnacle window (winit's handle to the driver).
    ("wgpu-hal", "wgpu-hal", "wgpu-hal-30.0.2"),
];

/// `--config` arguments switching the ports in for one build only: the
/// crate being built keeps its own manifest, and builds elsewhere the
/// originals.
fn port_patches() -> Vec<String> {
    port_patches_except(&[])
}

/// As [`port_patches`], but for the crates in `own`, which the workspace
/// built patches itself (Cartopolis its own copy of wgpu).
fn port_patches_except(own: &[&str]) -> Vec<String> {
    let mut args = Vec::new();
    for (key, package, dir) in PORTS.iter().filter(|(key, ..)| !own.contains(key)) {
        let path = root().join("ports").join(dir);
        args.push("--config".into());
        args.push(format!("patch.crates-io.{key}.path=\"{}\"", path.display()));
        args.push("--config".into());
        args.push(format!("patch.crates-io.{key}.package=\"{package}\""));
    }
    args
}

/// The self-check's program on the ports (`ports/check`): tokio over
/// Pinnacle's mio. Not part of the system: `test` puts it on the system
/// disk, as `/tests/ports-check`, and the self-check runs it when it is
/// there. Returns the ELF.
fn build_ports_check() -> Result<Vec<u8>> {
    build_on_ports("check", "ports-check")
}

/// Makes the lockfiles of the programs on the ports afresh, as the ports are
/// now: a port added or changed changes what `--locked` holds them to.
fn lock_ports() -> Result {
    for dir in ["check", "winit-demo", "wgpu-demo"] {
        run_status(
            rustup()
                .args(["run", STD_TOOLCHAIN, "cargo", "generate-lockfile"])
                .args(port_patches())
                .arg("--manifest-path")
                .arg(root().join("ports").join(dir).join("Cargo.toml"))
                .current_dir(root()),
            &format!("locking ports/{dir}"),
        )?;
    }
    Ok(())
}

/// Builds the program in `ports/<dir>` (its binary `bin`) against Pinnacle's
/// std with the ports switched in. Returns the ELF.
fn build_on_ports(dir: &str, bin: &str) -> Result<Vec<u8>> {
    let manifest = root().join("ports").join(dir).join("Cargo.toml");
    build_std_program(&manifest, &[], bin, &root().join("target/ports"), true, &[])
}

/// Builds binary `bin` of the workspace at `manifest` (with `args`, such as
/// `-p`) against Pinnacle's std with the ports switched in, into
/// `target_dir`; `locked` holds it to its lockfile. Returns the ELF.
fn build_std_program(
    manifest: &Path,
    args: &[&str],
    bin: &str,
    target_dir: &Path,
    locked: bool,
    own: &[&str],
) -> Result<Vec<u8>> {
    let library = std_library()?;
    let link = format!("-C link-arg=-T{}", root().join("programs/link.ld").display());
    run_status(
        rustup()
            .args(["run", STD_TOOLCHAIN, "cargo", "build", "--release"])
            .args(locked.then_some("--locked"))
            .args(args)
            .args(["-Zbuild-std=std,panic_abort", "-Zjson-target-spec"])
            .arg("-Zbuild-std-features=compiler-builtins-mem")
            .args(port_patches_except(own))
            .arg("--target")
            .arg(root().join("std").join(format!("{STD_TARGET}.json")))
            .arg("--manifest-path")
            .arg(manifest)
            .arg("--target-dir")
            .arg(target_dir)
            .env("__CARGO_TESTS_ONLY_SRC_ROOT", &library)
            .env("RUSTFLAGS", &link)
            .current_dir(root()),
        &format!("building {bin}"),
    )?;
    let path = target_dir.join(STD_TARGET).join("release").join(bin);
    std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))
}

/// Cartopolis's client built for Pinnacle from its source at `source` (a
/// checkout of jeroen/cartopolis, its LFS files had), installed on the
/// system disk and run: what it takes, and the program's size.
fn cartopolis(source: &Path) -> Result {
    let manifest = cartopolis_manifest(env!("CARGO_PKG_VERSION"));
    let mut files: Vec<(String, Vec<u8>)> = cartopolis_files(source)?
        .into_iter()
        .map(|(path, bytes)| (format!("/apps/cartopolis/{path}"), bytes))
        .collect();
    files.push(("/apps/cartopolis/manifest".into(), manifest.into_bytes()));
    disks_at(&root().join("target/system.img"), &serve()?, &files)?;
    // Half the host's cores, unless said: QEMU runs the guest's Vulkan on
    // threads of its own, and with as many guest cores as the host has
    // (6 on a Mac node) a message to the GPU waited 50 ms, not 0.1 ms.
    let cores = std::env::var("PINNACLE_CORES").unwrap_or_else(|_| {
        let host = std::thread::available_parallelism().map_or(2, |n| n.get());
        (host / 2).max(1).to_string()
    });
    // SAFETY: nothing else reads the environment while it is set.
    unsafe {
        std::env::set_var("PINNACLE_MEMORY", "3G");
        std::env::set_var("PINNACLE_CORES", cores);
    }
    let dir = demo_dir("demo-cartopolis")?;
    let mut s = Session::boot(&Guest::default(), "")?;
    s.wait_for(&home_apps(1))?;
    s.tap_named("launcher: tile ", "Cartopolis")?;
    // A screenshot a minute (a frame takes seconds, so the picture is
    // still forming), for `PINNACLE_CARTOPOLIS_MINUTES` minutes (1 when
    // not said); what it says meanwhile.
    let minutes: u32 = std::env::var("PINNACLE_CARTOPOLIS_MINUTES")
        .ok()
        .and_then(|m| m.parse().ok())
        .unwrap_or(1);
    let start = Instant::now();
    for minute in 1..=minutes.max(1) {
        let until = start + Duration::from_secs(30 + 60 * u64::from(minute));
        while let Ok(line) = s
            .lines
            .recv_timeout(until.saturating_duration_since(Instant::now()))
        {
            println!("  {line}");
        }
        s.shot(&dir.join(format!("{minute}-cartopolis.png")))?;
    }
    println!("{}", dir.display());
    Ok(())
}

/// Flitz, the web browser (jeroen/flitz), built for Pinnacle from its
/// source at `source`, installed on the system disk and opened on its start
/// page (on the internet: QEMU's user network reaches it). A screenshot
/// once the page is drawn, into `target/demo-flitz`.
fn flitz(source: &Path) -> Result {
    let elf = flitz_program(source)?;
    let manifest = manifest("flitz", "Flitz", "The web, in Rust only") + "network=yes\n";
    disks_at(
        &root().join("target/system.img"),
        &serve()?,
        &[
            ("/apps/flitz/program".into(), elf),
            ("/apps/flitz/manifest".into(), manifest.into_bytes()),
        ],
    )?;
    // SAFETY: nothing else reads the environment while it is set.
    unsafe {
        std::env::set_var("PINNACLE_MEMORY", "2G");
    }
    let dir = demo_dir("demo-flitz")?;
    let mut s = Session::boot(&Guest::default(), "")?;
    s.wait_for(&home_apps(1))?;
    s.tap_named("launcher: tile ", "Flitz")?;
    s.wait_for("flitz: loaded")?;
    s.wait_for("flitz: drawn")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("1-start.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// Flitz built for Pinnacle from its source at `source`: the program's ELF.
/// Not locked, as Cartopolis is not: the ports change what its lockfile has.
fn flitz_program(source: &Path) -> Result<Vec<u8>> {
    let elf = build_std_program(
        &source.join("Cargo.toml"),
        &["--bin", "flitz"],
        "flitz",
        &root().join("target/flitz"),
        false,
        &[],
    )?;
    println!("flitz: a program of {} MiB", elf.len() >> 20);
    Ok(elf)
}

/// Flitz built for Pinnacle and put into a package source at `out` for a
/// server to sign and publish (`docs/store.md`), as
/// [`package_cartopolis`]: `catalog`, `packages/flitz.ppa` (unsigned) and
/// `blobs/`. It carries its fonts in its program, so the program is its
/// one file.
fn package_flitz(source: &Path, out: &Path, version: &str) -> Result {
    if version.contains(['|', '\n']) {
        return Err(format!("no version can be {version:?}"));
    }
    let files = [("program".to_string(), flitz_program(source)?)];
    if out.exists() {
        std::fs::remove_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
    }
    let manifest = format!(
        "name=flitz\ntitle=Flitz\nversion={version}\ndescription=The web, in Rust only\nnetwork=yes\n"
    );
    let line = write_package(out, "flitz", &manifest, &files, None)?;
    std::fs::write(out.join("catalog"), &line).map_err(|e| e.to_string())?;
    println!(
        "flitz {version}: {} MiB, in {}",
        files[0].1.len() >> 20,
        out.display()
    );
    Ok(())
}

/// The hosted Store used: Cartopolis installed from
/// https://pinnacle-os.eu/store/cartopolis/ (a GPU and the internet
/// needed, so a Mac node), then opened; a screenshot each step into
/// `target/demo-store`, and how long the install took.
fn store_demo() -> Result {
    disks_for(Arch::Arm, &root().join("target/system.img"), &serve()?, &[], 1024)?;
    let cores = std::env::var("PINNACLE_CORES").unwrap_or_else(|_| {
        let host = std::thread::available_parallelism().map_or(2, |n| n.get());
        (host / 2).max(1).to_string()
    });
    // SAFETY: nothing else reads the environment while it is set.
    unsafe {
        std::env::set_var("PINNACLE_MEMORY", "3G");
        std::env::set_var("PINNACLE_CORES", cores);
    }
    let dir = demo_dir("demo-store")?;
    let mut s = Session::boot(&Guest::default(), "")?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Store")?;
    s.wait_for("display: Store connected")?;
    s.shot(&dir.join("1-store.png"))?;
    // The cards: this checkout's Calculator and Paint, then the hosted
    // source's Cartopolis.
    s.tap_named("store: button ", "offer-2")?;
    let start = Instant::now();
    let mut halfway = false;
    loop {
        let line = s
            .lines
            .recv_timeout(Duration::from_secs(1200).saturating_sub(start.elapsed()))
            .map_err(|_| "Cartopolis was not installed within 20 minutes")?;
        if !halfway && start.elapsed() > Duration::from_secs(20) {
            halfway = true;
            s.shot(&dir.join("2-installing.png"))?;
        }
        if line.starts_with("store: Cartopolis is installed") {
            break;
        }
        if line.starts_with("store: ") || line.starts_with("panic") {
            return Err(line);
        }
    }
    println!("store: Cartopolis installed in {} s", start.elapsed().as_secs());
    s.shot(&dir.join("3-installed.png"))?;
    s.home()?;
    s.wait_for(&home_apps(1))?;
    s.tap_named("launcher: tile ", "Cartopolis")?;
    let until = Instant::now() + Duration::from_secs(90);
    while let Ok(line) = s
        .lines
        .recv_timeout(until.saturating_duration_since(Instant::now()))
    {
        println!("  {line}");
    }
    s.shot(&dir.join("4-cartopolis.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// Cartopolis as an app: with the network and the GPU.
fn cartopolis_manifest(version: &str) -> String {
    format!(
        "name=cartopolis\ntitle=Cartopolis\nversion={version}\n\
         description=The map, its places and its people\nnetwork=yes\ngpu=yes\n"
    )
}

/// Cartopolis built for Pinnacle and put into a package source at `out`
/// for a server to sign and publish (`docs/store.md`): `catalog`,
/// `packages/cartopolis.ppa` (unsigned) and `blobs/`. `version` is what
/// the Store compares with the one installed.
fn package_cartopolis(source: &Path, out: &Path, version: &str) -> Result {
    if version.contains(['|', '\n']) {
        return Err(format!("no version can be {version:?}"));
    }
    let files = cartopolis_files(source)?;
    if out.exists() {
        std::fs::remove_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
    }
    let line = write_package(out, "cartopolis", &cartopolis_manifest(version), &files, None)?;
    std::fs::write(out.join("catalog"), &line).map_err(|e| e.to_string())?;
    let size: usize = files.iter().map(|(_, b)| b.len()).sum();
    println!(
        "cartopolis {version}: {} files, {} MiB, in {}",
        files.len(),
        size >> 20,
        out.display()
    );
    Ok(())
}

/// Cartopolis's client built for Pinnacle, and its files as they go into
/// its folder (path within it, contents): `program`, and its assets
/// beside it under `assets/`. Not locked: the ports change what its
/// lockfile has.
fn cartopolis_files(source: &Path) -> Result<Vec<(String, Vec<u8>)>> {
    let workspace = source.join("Cargo.toml");
    // Its lockfile may hold a version of a ported crate other than the
    // port's (wgpu-hal 30.0.1 where the port is 30.0.2), which leaves the
    // port unused: it is moved to the port's version (in this checkout's
    // lockfile).
    run_status(
        rustup()
            .args(["run", STD_TOOLCHAIN, "cargo", "update", "-p", "wgpu-hal"])
            .args(port_patches_except(&["wgpu"]))
            .arg("--manifest-path")
            .arg(&workspace)
            .current_dir(root()),
        "moving wgpu-hal to its port",
    )?;
    let elf = build_std_program(
        &workspace,
        &["-p", "cartopolis", "--bin", "cartopolis"],
        "cartopolis",
        &root().join("target/cartopolis"),
        false,
        // Its own copy of wgpu (its meter), with the Vulkan backend on for
        // Pinnacle in its own repo.
        &["wgpu"],
    )?;
    println!("cartopolis: a program of {} MiB", elf.len() >> 20);
    let mut files = vec![("program".to_string(), elf)];
    // Its assets beside the program, where Bevy looks (the program's folder,
    // `std::env::current_exe`'s, and `assets/` in it): an app may read its
    // own folder.
    let assets = source.join("assets");
    let mut todo = vec![assets.clone()];
    while let Some(dir) = todo.pop() {
        for entry in std::fs::read_dir(&dir).map_err(|e| format!("{}: {e}", dir.display()))? {
            let path = entry.map_err(|e| e.to_string())?.path();
            if path.is_dir() {
                todo.push(path);
            } else {
                let relative = path.strip_prefix(&assets).map_err(|e| e.to_string())?;
                let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
                // `/` between its parts on every host, as the Store reads it.
                let parts: Vec<String> = relative
                    .components()
                    .map(|c| c.as_os_str().to_string_lossy().into_owned())
                    .collect();
                files.push((format!("assets/{}", parts.join("/")), bytes));
            }
        }
    }
    // In one order whatever the directory listing's, so two builds of the
    // same source list the same files.
    files[1..].sort_by(|a, b| a.0.cmp(&b.0));
    println!("cartopolis: {} files of assets", files.len() - 1);
    Ok(files)
}

/// Writes only when the content differs, so an unchanged archive does not
/// rebuild the kernel that embeds it.
fn write_if_changed(path: &Path, bytes: &[u8]) -> Result {
    if std::fs::read(path).ok().as_deref() == Some(bytes) {
        return Ok(());
    }
    std::fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display()))
}
fn board_args(board: &str) -> Result<Vec<String>> {
    if !BOARDS.contains(&board) {
        return Err(format!("no board {board}; there are {}", BOARDS.join(", ")));
    }
    let feature = format!("board-{board}");
    Ok([
        "-p",
        "pinnacle",
        "--release",
        "--target",
        KERNEL_TARGET,
        "--no-default-features",
        "--features",
        &feature,
    ]
    .map(String::from)
    .to_vec())
}

/// The system's version: `PINNACLE_VERSION` when set, else the number of
/// commits in this checkout's history (what main's count will be once it
/// lands), else 0. The kernel carries it (`chain::VERSION`), and a boot
/// kernel hands over only to a newer one (`docs/updates.md`).
fn version() -> String {
    static VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    VERSION
        .get_or_init(|| {
            if let Ok(v) = std::env::var("PINNACLE_VERSION") {
                return v;
            }
            Command::new("git")
                .args(["rev-list", "--count", "HEAD"])
                .current_dir(root())
                .output()
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                .filter(|v| !v.is_empty())
                .unwrap_or_else(|| "0".into())
        })
        .clone()
}

fn build(board: &str) -> Result<PathBuf> {
    build_as(board, &version())
}

/// The kernel for `board`, numbered `version`.
fn build_as(board: &str, version: &str) -> Result<PathBuf> {
    build_user()?;
    let args = board_args(board)?;
    let mut all = vec!["build", "--locked"];
    all.extend(args.iter().map(String::as_str));
    cargo_with(&all, &programs_archive(), &[("PINNACLE_VERSION", version)])?;
    Ok(root().join("target").join(KERNEL_TARGET).join("release/pinnacle"))
}

/// The kernel as a boot image: the ELF's loadable bytes laid out from its
/// load address, header first (`boot::_image_header`), the format U-Boot's
/// `booti` and QEMU's `-kernel` take.
fn image(board: &str) -> Result<PathBuf> {
    image_as(board, &version())
}

/// As [`image`], numbered `version`.
fn image_as(board: &str, version: &str) -> Result<PathBuf> {
    let elf_path = build_as(board, version)?;
    let elf = std::fs::read(&elf_path).map_err(|e| format!("{}: {e}", elf_path.display()))?;
    let at = |offset: usize, len: usize| -> Result<u64> {
        let bytes = elf.get(offset..offset + len).ok_or("a truncated ELF")?;
        Ok(bytes.iter().rev().fold(0, |n, &b| n << 8 | u64::from(b)))
    };
    let (phoff, phentsize, phnum) = (at(32, 8)? as usize, at(54, 2)? as usize, at(56, 2)? as usize);
    let mut segments = Vec::new();
    for i in 0..phnum {
        let header = phoff + i * phentsize;
        const PT_LOAD: u64 = 1;
        if at(header, 4)? != PT_LOAD || at(header + 32, 8)? == 0 {
            continue;
        }
        let (offset, physical, size) = (at(header + 8, 8)?, at(header + 24, 8)?, at(header + 32, 8)?);
        segments.push((physical, &elf[offset as usize..(offset + size) as usize]));
    }
    let start = segments.iter().map(|s| s.0).min().ok_or("no loadable segment")?;
    let end = segments.iter().map(|s| s.0 + s.1.len() as u64).max().unwrap();
    let mut out = vec![0; (end - start) as usize];
    for (physical, bytes) in segments {
        let from = (physical - start) as usize;
        out[from..from + bytes.len()].copy_from_slice(bytes);
    }
    if out.get(56..60) != Some(b"ARM\x64") {
        return Err("the image has no arm64 header".into());
    }
    let path = elf_path.with_file_name(format!("Image-{board}"));
    std::fs::write(&path, &out).map_err(|e| format!("{}: {e}", path.display()))?;
    Ok(path)
}

/// A directory to copy onto an RK3399 board's SD card (its first
/// partition, FAT32): the Image, and the extlinux entry U-Boot's
/// distro boot look for (docs/hardware.md).
fn sdcard() -> Result<PathBuf> {
    let image = image("rk3399")?;
    let dir = root().join("target/sdcard");
    std::fs::create_dir_all(dir.join("extlinux")).map_err(|e| e.to_string())?;
    std::fs::copy(&image, dir.join("Image")).map_err(|e| e.to_string())?;
    std::fs::write(
        dir.join("extlinux/extlinux.conf"),
        "default pinnacle\ntimeout 30\n\nlabel pinnacle\n    menu label Pinnacle\n    kernel /Image\n",
    )
    .map_err(|e| e.to_string())?;
    Ok(dir)
}

/// How QEMU gets the kernel.
enum Load {
    /// `-kernel` with the ELF: started at its entry, no device tree.
    Elf(PathBuf),
    /// `-kernel` with the boot image and a command line: started as a
    /// bootloader starts it, a device tree in x0.
    Image(PathBuf, &'static str),
    /// As `Image`, with a device tree of ours rather than QEMU's own
    /// (`lit_tree`).
    ImageTree(PathBuf, &'static str, PathBuf),
    /// The Image placed at an address that is not its load address, and the
    /// first core started there: as a loader that ignores the header would.
    ImageAt(PathBuf, u64),
}

fn qemu(machine: &str, load: &Load) -> Command {
    qemu_with(machine, load, true)
}

/// QEMU with the system disk and the package source attached when they are
/// built; `snapshot` keeps what the run writes off the system disk.
fn qemu_with(machine: &str, load: &Load, snapshot: bool) -> Command {
    qemu_guest(machine, load, snapshot, &Guest::default())
}

/// The data disk's size.
const DATA_MIB: u64 = 32;
/// The passphrase the demos choose for the data, at the first start.
const DEMO_PASSPHRASE: &str = "lighthouse keeper 42";
/// What the demo changes it to in Settings.
const NEW_PASSWORD: &str = "harbour light 77";

/// One system in QEMU: its system disk, and the host UDP port forwarded to
/// its p2p port (7000), as a router forwarding a port would.
#[derive(Clone)]
struct Guest {
    system: PathBuf,
    udp_forward: Option<u16>,
    /// Where what it plays is written as a WAV file, if anywhere.
    audio: Option<PathBuf>,
    /// The Unix socket QEMU serves its Bluetooth controller's port on, for
    /// the simulated air ([`SimAir`]) to connect to.
    bluetooth: Option<PathBuf>,
    /// The Unix socket QEMU serves its modem's port on, for the simulated
    /// network ([`SimCell`]); only beside `bluetooth`, whose console is
    /// found first.
    modem: Option<PathBuf>,
    /// The Unix socket QEMU serves its Wi-Fi radio's port on, for the
    /// simulated access points ([`SimWifi`]); only beside `modem`, whose
    /// console is found before it.
    wifi: Option<PathBuf>,
    /// A host TCP port forwarded to the guest's 7080, where the self-check
    /// listens.
    tcp_forward: Option<u16>,
    /// The disk for the person's own data, made blank when missing: the
    /// system makes it a vault behind a passphrase at its first start.
    data: Option<PathBuf>,
    /// A PC's hardware beside the virtio devices ([`hardware`]): USB with a
    /// keyboard, a tablet and a stick, an NVMe and a SATA disk.
    hardware: bool,
    /// A disk labelled `backup` (`docs/backup-and-sync.md`), kept between
    /// runs as a USB stick would be: [`new_image`] makes it.
    backup: Option<PathBuf>,
    /// A Pinebook Pro's input rather than virtio's: a keyboard and a mouse
    /// (its touchpad) on USB 1.1, an OHCI controller, and nothing else.
    pinebook: bool,
}

impl Default for Guest {
    fn default() -> Guest {
        Guest {
            system: root().join("target/system.img"),
            udp_forward: None,
            audio: None,
            bluetooth: None,
            modem: None,
            wifi: None,
            tcp_forward: None,
            data: Some(root().join("target/data.img")),
            hardware: false,
            backup: None,
            pinebook: false,
        }
    }
}

/// QEMU's arguments for the hardware a PC or laptop has rather than
/// virtio: an xHCI USB controller with a keyboard, a tablet and a stick on
/// it, an NVMe disk and a SATA disk (on an AHCI controller of its own on
/// ARM, on the one built into a PC's `q35`). The disks are blank, 64 MiB
/// each, made afresh as `target/<name>-{stick,nvme,sata}.img`: the
/// self-check writes a block on each and puts it back (`selfcheck::storage`).
fn hardware(name: &str, arch: Arch) -> Result<Vec<String>> {
    let disk = |what: &str| -> Result<String> {
        let path = root().join(format!("target/{name}-{what}.img"));
        let _ = std::fs::remove_file(&path);
        std::fs::File::create(&path)
            .and_then(|f| f.set_len(64 << 20))
            .map_err(|e| format!("{}: {e}", path.display()))?;
        Ok(format!("if=none,id={what},format=raw,file={}", path.display()))
    };
    let mut args: Vec<String> = [
        "-device",
        "qemu-xhci,id=xhci",
        "-device",
        "usb-kbd,bus=xhci.0",
        "-device",
        "usb-tablet,bus=xhci.0",
    ]
    .map(String::from)
    .to_vec();
    args.extend([
        "-drive".into(),
        disk("stick")?,
        "-device".into(),
        "usb-storage,bus=xhci.0,drive=stick".into(),
    ]);
    args.extend([
        "-drive".into(),
        disk("nvme")?,
        "-device".into(),
        "nvme,serial=pinnacle0,drive=nvme".into(),
    ]);
    args.extend(["-drive".into(), disk("sata")?]);
    match arch {
        Arch::Arm => args.extend(
            [
                "-device",
                "ich9-ahci,id=ahci",
                "-device",
                "ide-hd,drive=sata,bus=ahci.0",
            ]
            .into_iter()
            .chain(OHCI_INPUT)
            .map(String::from),
        ),
        Arch::Pc => args.extend(["-device", "ide-hd,drive=sata,bus=ide.0"].map(String::from)),
    }
    Ok(args)
}

/// What the self-check says of [`hardware`], as the boots must show it.
const HARDWARE_LINES: &[&str] = &[
    "keyboard (QEMU USB Keyboard)",
    "tablet (QEMU USB Tablet)",
    "storage usb0 (QEMU QEMU HARDDISK, 64 MiB)",
    "storage: nvme0n1 (QEMU NVMe Ctrl, 64 MiB): a block written, read back and put back",
    "storage: sata0 (QEMU HARDDISK, 64 MiB): a block written, read back and put back",
    "storage: usb0 (QEMU QEMU HARDDISK, 64 MiB): a block written, read back and put back",
    "storage ok",
];

/// USB 1.1, as a board's USB 2.0 host hands a keyboard and a touchpad to
/// its OHCI (a Pinebook Pro's own are there): a keyboard and a mouse on
/// QEMU's OHCI, in [`hardware`] on ARM and as a `pinebook` guest's input.
const OHCI_INPUT: [&str; 6] = [
    "-device",
    "pci-ohci,id=ohci",
    "-device",
    "usb-kbd,bus=ohci.0",
    "-device",
    "usb-mouse,bus=ohci.0",
];

/// What the self-check says of [`OHCI_INPUT`], on ARM only: a
/// keyboard and a mouse on it, read through it.
const OHCI_LINES: &[&str] = &[
    "ohci0: OHCI, ",
    "ohci0: port 1: keyboard (QEMU USB Keyboard)",
    "ohci0: port 2: mouse (QEMU USB Mouse)",
];

/// How QEMU is given the 3D virtio-gpu, whose Venus runs the guest's Vulkan on
/// the host's, where this machine's QEMU has the device. `PINNACLE_GPU3D=0`
/// leaves it out.
#[derive(Clone, Copy)]
enum Gpu3d {
    /// Linux: QEMU makes a headless GL display on this render node (a GPU's,
    /// or the kernel's vgem on a machine with none), which the device needs.
    RenderNode(&'static str),
    /// macOS: Venus alone, on MoltenVK, with no GL display — a QEMU patched to
    /// allow that, built with a Venus virglrenderer (`tools/macos-venus`).
    VenusOnly,
}

fn gpu3d() -> Option<Gpu3d> {
    static GPU3D: std::sync::OnceLock<Option<Gpu3d>> = std::sync::OnceLock::new();
    *GPU3D.get_or_init(|| {
        if std::env::var("PINNACLE_GPU3D").as_deref() == Ok("0") {
            return None;
        }
        let node = "/dev/dri/renderD128";
        let gpu3d = if cfg!(target_os = "macos") {
            Gpu3d::VenusOnly
        } else if Path::new(node).exists() {
            Gpu3d::RenderNode(node)
        } else {
            return None;
        };
        let devices = qemu_command().args(["-device", "help"]).output().ok()?;
        String::from_utf8_lossy(&devices.stdout)
            .contains("virtio-gpu-gl-pci")
            .then_some(gpu3d)
    })
}

/// Where `tools/macos-venus/build.sh` installs its QEMU and Vulkan.
fn macos_venus() -> Option<PathBuf> {
    let prefix = Path::new(&std::env::var_os("HOME")?).join("opt/venus");
    (cfg!(target_os = "macos") && prefix.join("bin/qemu-system-aarch64").exists()).then_some(prefix)
}

/// The QEMU to run: `PINNACLE_QEMU`, else on a Mac the one
/// `tools/macos-venus` built, else the one on the path.
fn qemu_binary() -> PathBuf {
    if let Some(qemu) = std::env::var_os("PINNACLE_QEMU") {
        return qemu.into();
    }
    match macos_venus() {
        Some(prefix) => prefix.join("bin/qemu-system-aarch64"),
        None => "qemu-system-aarch64".into(),
    }
}

/// A QEMU command, told on a Mac where `tools/macos-venus`'s Vulkan loader
/// and MoltenVK are (virglrenderer loads them at run time).
fn qemu_command() -> Command {
    let mut qemu = Command::new(qemu_binary());
    if let Some(prefix) = macos_venus() {
        qemu.env("DYLD_FALLBACK_LIBRARY_PATH", prefix.join("lib")).env(
            "VK_DRIVER_FILES",
            prefix.join("share/vulkan/icd.d/MoltenVK_icd.json"),
        );
    }
    qemu
}

/// The guest's memory: `PINNACLE_MEMORY` (QEMU's `-m`, at most 3G: RAM ends
/// below 4 GiB, highmem being off; the kernel uses 2.5 GiB of it), else
/// 256M, which the self-check counts on.
fn memory() -> String {
    std::env::var("PINNACLE_MEMORY").unwrap_or_else(|_| "256M".into())
}

/// The cores to boot with: `PINNACLE_CORES`, else six (as the RK3399 has).
/// The kernel finds them itself, from the GIC.
fn cores() -> usize {
    std::env::var("PINNACLE_CORES")
        .ok()
        .and_then(|c| c.parse().ok())
        .filter(|&c: &usize| (1..=64).contains(&c))
        .unwrap_or(6)
}

/// The screen size to boot with: `PINNACLE_SCREEN` ("1280x800"), else the
/// kernel's default, a phone held upright.
fn screen() -> (i32, i32) {
    std::env::var("PINNACLE_SCREEN")
        .ok()
        .and_then(|s| {
            let (w, h) = s.split_once('x')?;
            Some((w.parse().ok()?, h.parse().ok()?))
        })
        .unwrap_or((720, 1440))
}

fn qemu_guest(machine: &str, load: &Load, snapshot: bool, guest: &Guest) -> Command {
    let mut qemu = qemu_command();
    let (width, height) = screen();
    // The kernel reads the screen's size from here (`drivers::display`).
    qemu.args([
        "-fw_cfg",
        &format!("name=opt/pinnacle/screen,string={width}x{height}"),
    ]);
    // On a Mac with Venus, the guest's RAM is shared memory: the patched
    // QEMU hands a guest blob in it to the GPU as it is (`GUEST_BLOB`), so
    // what wgpu maps takes no room in the 256 MiB host-visible window.
    let shared_ram = matches!(gpu3d(), Some(Gpu3d::VenusOnly));
    if shared_ram {
        qemu.args([
            "-object",
            &format!("memory-backend-shm,id=ram,size={},share=on", memory()),
        ]);
    }
    qemu.args([
        "-M",
        // highmem=off: PCI's configuration window below 4 GiB, which is
        // all the kernel maps.
        &format!(
            "{machine},gic-version=3,highmem=off{}",
            if shared_ram { ",memory-backend=ram" } else { "" }
        ),
        "-cpu",
        "cortex-a72",
        "-m",
        &memory(),
        "-smp",
        &cores().to_string(),
    ])
    // The kernel's sampling profiler, when `PINNACLE_PROFILE` is set: the
    // commonest places on the console every ten seconds ("profile:").
    .args(
        std::env::var_os("PINNACLE_PROFILE")
            .map(|_| {
                vec![
                    "-fw_cfg".to_string(),
                    "name=opt/pinnacle/profile,string=1".to_string(),
                ]
            })
            .unwrap_or_default(),
    )
    // The guest's clock: `PINNACLE_CLOCK` (QEMU's `-rtc base=`, as
    // `2026-11-25T12:00:00`) when set, so a shot of what the time of day
    // drives (Cartopolis's sun) comes out the same at any hour.
    .args(
        std::env::var("PINNACLE_CLOCK")
            .map(|base| vec!["-rtc".to_string(), format!("base={base}")])
            .unwrap_or_default(),
    )
    // No display, or on a machine with a render node a headless GL one, which
    // the 3D virtio-gpu below needs there.
    .args(match gpu3d() {
        Some(Gpu3d::RenderNode(node)) => vec![
            "-display".to_string(),
            format!("egl-headless,rendernode={node}"),
            "-serial".into(),
            "mon:stdio".into(),
        ],
        Some(Gpu3d::VenusOnly) | None => vec!["-nographic".to_string()],
    })
    // A reset (PSCI SYSTEM_RESET: a restart) starts the machine again from
    // its loader, as a device does; a panic still ends it (semihosting).
    .args(["-nic", "none"])
    .args(["-semihosting-config", "enable=on,target=native"])
    // The devices the kernel drives: modern virtio, and a framebuffer.
    .args(["-global", "virtio-mmio.force-legacy=false"])
    // The screen: a virtio-gpu of the size asked (a ramfb would show RAM as
    // it is; the gpu is told what changed, as a board's display controller is).
    .args([
        "-device",
        &format!("virtio-gpu-device,xres={width},yres={height}"),
    ])
    // Beside it, where the machine can: the 3D virtio-gpu, whose Venus runs
    // the guest's Vulkan on the host's. On PCI: QEMU offers Venus's host
    // memory there only (on MMIO asking for it crashes QEMU 11.1).
    .args(match gpu3d() {
        Some(_) => vec!["-device", "virtio-gpu-gl-pci,venus=on,blob=on,hostmem=256M"],
        None => vec![],
    })
    // Touch (a tablet: absolute positions) and a keyboard; or a Pinebook
    // Pro's, a keyboard and a touchpad on USB 1.1.
    .args(if guest.pinebook {
        OHCI_INPUT.as_slice()
    } else {
        [
            "-device",
            "virtio-tablet-device",
            "-device",
            "virtio-keyboard-device",
        ]
        .as_slice()
    })
    .args(if guest.hardware {
        hardware(machine.split(',').next().unwrap_or("virt"), Arch::Arm).unwrap_or_default()
    } else {
        Vec::new()
    })
    // The network: QEMU's user mode, DHCP and DNS included; the host is 10.0.2.2.
    .args([
        "-netdev",
        &{
            let mut netdev = String::from("user,id=net0");
            if let Some(port) = guest.udp_forward {
                netdev += &format!(",hostfwd=udp:127.0.0.1:{port}-:7000");
            }
            if let Some(port) = guest.tcp_forward {
                netdev += &format!(",hostfwd=tcp:127.0.0.1:{port}-:7080");
            }
            netdev
        },
        "-device",
        "virtio-net-device,netdev=net0",
    ])
    // Entropy from the host, for keys.
    // On PCI, so the boot proves that transport and its INTx routing.
    .args(["-device", "virtio-rng-pci"])
    // Sound: what the system plays goes to a WAV file when asked (what a
    // test listens to), else nowhere; the microphone gives silence.
    .args([
        "-audiodev",
        &match &guest.audio {
            Some(path) => format!("wav,id=snd0,path={}", path.display()),
            None => "none,id=snd0".into(),
        },
        "-device",
        "virtio-sound-device,audiodev=snd0",
    ]);
    // The Bluetooth controller's port: a serial port whose other end is the
    // simulated air, over a socket; and the modem's, on the simulated cell
    // network; and the Wi-Fi radio's, among the simulated access points.
    // Each console on a virtio-serial device of its own (named, or QEMU
    // puts them all on the first); the kernel takes the first it finds for
    // Bluetooth, the second for the modem and the third for Wi-Fi, by
    // address, and `virt` gives the device named first the highest: so
    // Wi-Fi's comes first, then the modem's (alone, Bluetooth's is at
    // 0xa003400; beside the others, below them).
    if let Some(socket) = &guest.bluetooth {
        let mut console = |id: &str, socket: &Path| {
            qemu.args([
                "-device",
                &format!("virtio-serial-device,id={id}-serial"),
                "-chardev",
                &format!("socket,id={id},path={},server=on,wait=off", socket.display()),
                "-device",
                &format!("virtconsole,chardev={id},bus={id}-serial.0"),
            ]);
        };
        if let Some(wifi) = &guest.wifi {
            console("wifi", wifi);
        }
        if let Some(modem) = &guest.modem {
            console("modem", modem);
        }
        console("bt", socket);
    }
    let system = &guest.system;
    if system.exists() {
        let snapshot = if snapshot { ",snapshot=on" } else { "" };
        qemu.args([
            "-drive",
            &format!("if=none,id=system,format=raw,file={}{snapshot}", system.display()),
        ]);
        qemu.args(["-device", "virtio-blk-device,drive=system"]);
    }
    if let Some(data) = &guest.data {
        if !data.exists() {
            // Blank: what the system makes a vault of at its first start.
            let file = std::fs::File::create(data).expect("could not make the data disk");
            file.set_len(DATA_MIB << 20)
                .expect("could not size the data disk");
        }
        let snapshot = if snapshot { ",snapshot=on" } else { "" };
        qemu.args([
            "-drive",
            &format!("if=none,id=data,format=raw,file={}{snapshot}", data.display()),
        ]);
        qemu.args(["-device", "virtio-blk-device,drive=data"]);
    }
    if let Some(backup) = &guest.backup {
        // Never a snapshot: what was backed up stays on it.
        qemu.args([
            "-drive",
            &format!("if=none,id=backup,format=raw,file={}", backup.display()),
        ]);
        qemu.args(["-device", "virtio-blk-device,drive=backup"]);
    }
    match load {
        Load::Elf(path) => {
            qemu.arg("-kernel").arg(path);
        }
        Load::Image(path, command_line) => {
            qemu.arg("-kernel").arg(path).arg("-append").arg(command_line);
        }
        Load::ImageTree(path, command_line, tree) => {
            qemu.arg("-kernel")
                .arg(path)
                .arg("-append")
                .arg(command_line)
                .arg("-dtb")
                .arg(tree);
        }
        Load::ImageAt(path, address) => {
            qemu.arg("-device")
                .arg(format!(
                    "loader,file={},addr={address:#x},force-raw=on",
                    path.display()
                ))
                .arg("-device")
                .arg(format!("loader,addr={address:#x},cpu-num=0"));
        }
    }
    qemu
}

/// The system as a folder to run on another machine with only QEMU: the
/// boot image, the system disk, the package source (`store`) and `start`
/// (`xtask/start.sh`), which boots it in a window and serves the Store
/// itself; packed as `target/pinnacle.tar.gz`, which this returns.
fn bundle(arch: Arch) -> Result<PathBuf> {
    // A PC's kernel is the ELF, named `kernel`, which is how `start` knows it.
    let (name, kernel, kernel_name) = match arch {
        Arch::Arm => ("pinnacle", image("qemu-virt")?, "Image"),
        Arch::Pc => ("pinnacle-pc", pc_kernel()?, "kernel"),
    };
    let dir = root().join("target").join(name);
    if dir.exists() {
        std::fs::remove_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    }
    let store = dir.join("store").join(arch.store_path());
    // The address `start` serves the package source at, inside QEMU; room
    // on the system disk for what the hosted Store offers (Cartopolis).
    disks_for(arch, &dir.join("system.img"), "http://10.0.2.2:8080/", &[], 1024)?;
    std::fs::copy(&kernel, dir.join(kernel_name)).map_err(|e| e.to_string())?;
    let repository = repository().join(arch.store_path());
    std::fs::create_dir_all(&store).map_err(|e| e.to_string())?;
    std::fs::copy(repository.join("catalog"), store.join("catalog")).map_err(|e| e.to_string())?;
    for folder in ["packages", "blobs"] {
        std::fs::create_dir_all(store.join(folder)).map_err(|e| e.to_string())?;
        for entry in std::fs::read_dir(repository.join(folder)).map_err(|e| e.to_string())? {
            let path = entry.map_err(|e| e.to_string())?.path();
            if path.is_file() {
                std::fs::copy(&path, store.join(folder).join(path.file_name().unwrap()))
                    .map_err(|e| e.to_string())?;
            }
        }
    }
    std::fs::copy(root().join("LICENSE"), dir.join("LICENSE")).map_err(|e| e.to_string())?;
    let start = dir.join("start");
    std::fs::write(&start, include_str!("../start.sh")).map_err(|e| e.to_string())?;
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(&start, std::fs::Permissions::from_mode(0o755)).map_err(|e| e.to_string())?;
    let tar = root().join(format!("target/{name}.tar.gz"));
    let status = Command::new("tar")
        .arg("-czf")
        .arg(&tar)
        .arg(name)
        .current_dir(root().join("target"))
        .status()
        .map_err(|e| format!("tar: {e}"))?;
    status
        .success()
        .then_some(tar)
        .ok_or_else(|| format!("tar ended with {status}"))
}

/// Boots the system, its disks kept between runs (made when missing, or
/// when the package source's port moved since).
fn run() -> Result {
    // A fixed port, so the system disk's store URL stays right between runs.
    let url = serve_on(8080)?;
    let marker = root().join("target/system.url");
    if !root().join("target/system.img").exists()
        || std::fs::read_to_string(&marker).ok().as_deref() != Some(url.as_str())
    {
        disks(&url)?;
        std::fs::write(&marker, &url).map_err(|e| e.to_string())?;
    }
    let image = image("qemu-virt")?;
    let status = qemu_with("virt", &Load::Image(image, ""), false)
        .status()
        .map_err(|e| format!("qemu-system-aarch64: {e}"))?;
    status
        .success()
        .then_some(())
        .ok_or_else(|| format!("the kernel powered off with {status}"))
}

/// Boots on `machine`, returning the serial output once the kernel powers
/// off with status 0.
fn boot(machine: &str, load: &Load, guest: &Guest) -> Result<String> {
    // A monitor to ask, should the boot hang, where every core is.
    let monitor = std::env::temp_dir().join(format!(
        "pinnacle-monitor-{}-{}",
        std::process::id(),
        SOCKETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    let mut child = qemu_guest(machine, load, true, guest)
        .arg("-monitor")
        .arg(format!("unix:{},server=on,wait=off", monitor.display()))
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| format!("qemu-system-aarch64: {e} (is QEMU installed?)"))?;
    if let Some(socket) = &guest.bluetooth {
        air().attach(socket)?;
    }
    if let Some(socket) = &guest.modem {
        cell().attach(socket)?;
    }
    let stdout = child.stdout.take().unwrap();
    let tcp_forward = guest.tcp_forward;
    let reader = std::thread::spawn(move || {
        use std::io::{BufRead, BufReader};
        let mut out = String::new();
        for line in BufReader::new(stdout).lines().map_while(|l| l.ok()) {
            // The self-check listens: this host connects, as a peer would.
            if line.trim_end() == "listen: waiting on 7080"
                && let Some(port) = tcp_forward
            {
                match knock(port) {
                    Ok(answer) => out += &format!("  [host] the guest answered: {answer}\n"),
                    Err(e) => out += &format!("  [host] knocking failed: {e}\n"),
                }
            }
            out += &line;
            out.push('\n');
        }
        out
    });
    let start = Instant::now();
    let status = loop {
        if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
            break Some(status);
        }
        if start.elapsed() > boot_timeout() {
            println!("{}", where_cores_are(&monitor));
            let _ = child.kill();
            let _ = child.wait();
            break None;
        }
        std::thread::sleep(Duration::from_millis(20));
    };
    // Printed in every case: what a hung boot got to is where to look.
    let mut out = reader.join().unwrap();
    child.stderr.take().unwrap().read_to_string(&mut out).ok();
    for line in out.lines() {
        println!("  [{machine}] {line}");
    }
    match status {
        None => Err(format!(
            "{machine}: no power-off within {}s",
            boot_timeout().as_secs()
        )),
        Some(status) if !status.success() => Err(format!("{machine}: QEMU exited with {status}")),
        Some(_) => Ok(out),
    }
}

fn test() -> Result {
    // The ports' check on the system disk, which the self-check runs.
    let ports_check = build_ports_check()?;
    disks_at(
        &root().join("target/system.img"),
        &serve()?,
        &[("/tests/ports-check".into(), ports_check)],
    )?;
    let image = image("qemu-virt")?;
    let elf = build("qemu-virt")?;
    // EL1, and EL2 as U-Boot leaves the RK3399; the ELF, the boot image as a
    // bootloader starts it, and the boot image where it must move itself.
    let runs = [
        ("virt", 1, Load::Elf(elf.clone()), "ELF"),
        ("virt,virtualization=on", 2, Load::Elf(elf), "ELF"),
        (
            "virt",
            1,
            Load::Image(image.clone(), "selfcheck"),
            "Image, device tree",
        ),
        (
            "virt,virtualization=on",
            2,
            Load::Image(image.clone(), "selfcheck"),
            "Image, device tree",
        ),
        (
            "virt",
            1,
            Load::ImageAt(image.clone(), 0x4800_0000),
            "Image at 0x48000000, moved",
        ),
        // As a board's loader leaves it: at EL2, the screen lit and
        // described, firmware's memory reserved.
        (
            "virt,virtualization=on",
            2,
            Load::ImageTree(image, "selfcheck", lit_tree("virt,virtualization=on")?),
            "Image, a screen the loader lit",
        ),
    ];
    for (i, (machine, entered, load, what)) in runs.iter().enumerate() {
        // What the self-check played, as QEMU heard it.
        let wav = root().join(format!("target/test-{i}.wav"));
        let guest = Guest {
            audio: Some(wav.clone()),
            bluetooth: Some(air().socket_for_guest()),
            modem: Some(cell().socket_for_guest()),
            tcp_forward: Some(free_tcp_port()?),
            // The first run also has a PC's own hardware: USB and its
            // devices, NVMe, SATA.
            hardware: i == 0,
            ..Guest::default()
        };
        let out = boot(machine, load, &guest)?;
        if guest.hardware {
            for expected in HARDWARE_LINES.iter().chain(OHCI_LINES) {
                if !out.contains(expected) {
                    return Err(format!("{machine}, {what}: no \"{expected}\" in the output"));
                }
            }
        }
        expect_tone(&wav, 440.0, 0.25)?;
        for expected in [
            "Pinnacle ",
            "running at EL1,",
            "caches on",
            "memory ok",
            "crypto ok",
            "scheduler ok",
            "smp ok",
            "programs ok",
            "ipc ok",
            "verbs ok",
            "threads ok",
            "unmap ok",
            "kill ok",
            "confinement ok",
            "handles ok",
            "text ok",
            "fp ok",
            "frits ok",
            "kees ok",
            "std ok",
            "ports ok",
            "files ok",
            "vault ok",
            "io ok",
            "audio ok",
            "bluetooth: paired with \"Pinnacle Test\", the numbers compared",
            "bluetooth ok",
            "modem: called +31 20 123 4567, answered after",
            "modem: texted +31 20 123 4567",
            "modem: a text from +31201234567: heard: ping €",
            "modem ok",
            "net: switched off and on, address",
            "net ok",
            "the stand-in model said",
            "model ok",
            "agent ok",
            "devices ok",
            "the guest answered: Pinnacle heard: ping",
            "listen ok",
            "idle ok",
            "display ok",
        ] {
            if !out.contains(expected) {
                return Err(format!("{machine}, {what}: no \"{expected}\" in the output"));
            }
        }
        // The 3D virtio-gpu, where QEMU was given one: a Venus context, and
        // Vulkan through ash on the driver, and wgpu on it (the ports program).
        for expected in [
            "gpu3d ok",
            "venus ok",
            "vulkan: through ash on Pinnacle's driver",
            "wgpu: on Pinnacle's driver",
        ] {
            if gpu3d().is_some() && !out.contains(expected) {
                return Err(format!("{machine}, {what}: no \"{expected}\" in the output"));
            }
        }
        // Every core QEMU was given, found by the kernel and running.
        let cores = format!("smp: {} cores running", cores());
        if !out.contains(&cores) {
            return Err(format!("{machine}, {what}: no \"{cores}\" in the output"));
        }
        let (width, height) = screen();
        if !out.contains(&format!("display: {width}x{height}")) {
            return Err(format!("{machine}, {what}: the screen is not {width}x{height}"));
        }
        if let Load::ImageTree(..) = load {
            let (_, _, stride) = lit_layout();
            for expected in [
                format!(
                    "display: drawn on the screen the loader lit (simple-framebuffer, Xrgb8888, {width}x{height} at {LIT_AT:#x}, stride {stride}), kept from the allocator"
                ),
                "memory: 3 ranges the loader reserved, kept from the allocator".to_string(),
            ] {
                if !out.contains(&expected) {
                    return Err(format!("{machine}, {what}: no \"{expected}\" in the output"));
                }
            }
        }
        if !out.contains(&format!("entered at EL{entered},")) {
            return Err(format!("{machine}, {what}: not entered at EL{entered}"));
        }
        // Lines come without their line ends (`lines()`): the file holds "\n".
        let device_tree = !out.contains("device tree at 0x0\n");
        if device_tree != matches!(load, Load::Image(..) | Load::ImageTree(..)) {
            return Err(format!(
                "{machine}, {what}: a device tree was {}expected",
                if device_tree { "not " } else { "" }
            ));
        }
        println!("ok   {machine}: {what} (entered at EL{entered})");
    }
    Ok(())
}

fn gate() -> Result {
    cargo(&["fmt", "--all", "--check"])?;
    cargo(&[
        "test",
        "--locked",
        "--release",
        "-p",
        "pinnacle-fs",
        "-p",
        "pinnacle-net",
        "-p",
        "pinnacle-crypto",
        "-p",
        "pinnacle-p2p",
        "-p",
        "pinnacle-media",
        "-p",
        "pinnacle-ttf",
        "-p",
        "pinnacle-vector",
        "-p",
        "pinnacle-layout",
        "-p",
        "pinnacle-pkg",
        "-p",
        "pinnacle-bt",
        "-p",
        "pinnacle-modem",
        "-p",
        "pinnacle-wifi",
        "-p",
        "pinnacle-tls",
        "-p",
        "pinnacle-json",
        "-p",
        "pinnacle-records",
        "-p",
        "pinnacle-contacts",
        "-p",
        "pinnacle-sync",
        "-p",
        "pinnacle-workbench",
        "-p",
        "pinnacle-disk",
        "-p",
        "pinnacle-text",
        "-p",
        "pinnacle-locale",
        "-p",
        "pinnacle-speech",
        "-p",
        "pinnacle-aml",
        "-p",
        "pinnacle-hid",
    ])?;
    cargo(&[
        "clippy",
        "--locked",
        "-p",
        "pinnacle-crypto",
        "-p",
        "pinnacle-p2p",
        "-p",
        "pinnacle-media",
        "-p",
        "pinnacle-ttf",
        "-p",
        "pinnacle-vector",
        "-p",
        "pinnacle-layout",
        "-p",
        "pinnacle-pkg",
        "-p",
        "pinnacle-bt",
        "-p",
        "pinnacle-modem",
        "-p",
        "pinnacle-wifi",
        "-p",
        "pinnacle-tls",
        "-p",
        "pinnacle-json",
        "-p",
        "pinnacle-records",
        "-p",
        "pinnacle-contacts",
        "-p",
        "pinnacle-sync",
        "-p",
        "pinnacle-workbench",
        "-p",
        "pinnacle-disk",
        "-p",
        "pinnacle-text",
        "-p",
        "pinnacle-locale",
        "-p",
        "pinnacle-speech",
        "-p",
        "pinnacle-aml",
        "-p",
        "pinnacle-hid",
        "--",
        "-D",
        "warnings",
    ])?;
    cargo(&["clippy", "--locked", "-p", "xtask", "--", "-D", "warnings"])?;
    cargo(&[
        "clippy",
        "--locked",
        "-p",
        "pinnacle-abi",
        "-p",
        "pinnacle-rt",
        "-p",
        "pinnacle-gfx",
        "-p",
        "pinnacle-fs",
        "-p",
        "pinnacle-net",
        "-p",
        "pinnacle-ui",
        "-p",
        "pinnacle-view",
        "-p",
        "pinnacle-programs",
        "--release",
        "--target",
        TARGET,
        "--",
        "-D",
        "warnings",
    ])?;
    build_user()?;
    for board in BOARDS {
        let args = board_args(board)?;
        let mut all = vec!["clippy", "--locked"];
        all.extend(args.iter().map(String::as_str));
        all.extend(["--", "-D", "warnings"]);
        cargo(&all)?;
    }
    // The hardware board's boot image must build and carry its header.
    image("rk3399")?;
    pc()?;
    test()?;
    // Installing on a disk, under UEFI, from a USB stick: ARM and a PC.
    install::test(Arch::Arm)?;
    install::test(Arch::Pc)
}

/// The system programs for a PC, packed as `build_user` packs ARM's: built
/// in a target directory of their own with the small code model (the
/// kernel's flags for this target are the kernel model's) and without LTO,
/// soft-float as the target is. Returns the archive.
fn build_user_pc() -> Result<PathBuf> {
    let dir = root().join("target/pc-user");
    cargo_with(
        &[
            "build",
            "--locked",
            "-p",
            "pinnacle-programs",
            "--release",
            "--target",
            "x86_64-unknown-none",
            "--target-dir",
            &dir.display().to_string(),
        ],
        &programs_archive(),
        &[
            (
                "CARGO_TARGET_X86_64_UNKNOWN_NONE_RUSTFLAGS",
                "-C relocation-model=static -C code-model=small",
            ),
            // The target's prebuilt `core` and `alloc` were built for the
            // kernel code model, and LTO refuses to merge across models.
            ("CARGO_PROFILE_RELEASE_LTO", "false"),
            // Without LTO each program carries all its crates' DWARF: 162
            // MB of programs in the kernel, on a PC of 256 MB, ran the
            // self-check out of pages. Their symbols stay.
            ("CARGO_PROFILE_RELEASE_STRIP", "debuginfo"),
        ],
    )?;
    let mut archive = b"PPAK".to_vec();
    archive.extend_from_slice(&(SYSTEM_PROGRAMS.len() as u32).to_le_bytes());
    for name in SYSTEM_PROGRAMS {
        let path = dir.join("x86_64-unknown-none/release").join(name);
        let elf = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
        archive.extend_from_slice(&(name.len() as u16).to_le_bytes());
        archive.extend_from_slice(name.as_bytes());
        archive.extend_from_slice(&(elf.len() as u32).to_le_bytes());
        archive.extend_from_slice(&elf);
    }
    let path = root().join("target/programs-pc.ppak");
    write_if_changed(&path, &archive)?;
    Ok(path)
}

/// The PC's kernel and programs, linted and built; its system disk (apps
/// for x86-64) and package source as ARM's test boots have them. Returns
/// the kernel.
fn pc_build() -> Result<PathBuf> {
    let kernel = pc_kernel()?;
    disks_for(Arch::Pc, &pc_system(), &serve()?, &[], 64)?;
    Ok(kernel)
}

/// The PC's system disk, apart from ARM's: its programs are x86-64's.
fn pc_system() -> PathBuf {
    root().join("target/system-pc.img")
}

/// The PC's kernel, its programs inside, linted and built.
fn pc_kernel() -> Result<PathBuf> {
    pc_kernel_as(&version())
}

/// As [`pc_kernel`], numbered `version`.
fn pc_kernel_as(version: &str) -> Result<PathBuf> {
    let programs = build_user_pc()?;
    let args = [
        "-p",
        "pinnacle",
        "--release",
        "--target",
        "x86_64-unknown-none",
        "--no-default-features",
        "--features",
        "board-pc",
    ];
    let mut lint = vec!["clippy", "--locked"];
    lint.extend(args);
    lint.extend(["--", "-D", "warnings"]);
    cargo_with(&lint, &programs, &[])?;
    let mut build = vec!["build", "--locked"];
    build.extend(args);
    cargo_with(&build, &programs, &[("PINNACLE_VERSION", version)])?;
    Ok(root().join("target/x86_64-unknown-none/release/pinnacle"))
}

/// QEMU as a PC (`q35`) with ARM's devices, each on PCI, the kernel loaded
/// by PVH with `command_line`; what it plays goes to `wav`.
fn qemu_pc(elf: &Path, command_line: &str, wav: &Path) -> Result<Command> {
    let mut qemu = qemu_pc_machine(wav)?;
    qemu.arg("-kernel").arg(elf).args(["-append", command_line]);
    Ok(qemu)
}

/// The machine of [`qemu_pc`], with no kernel given: its devices and disks.
fn qemu_pc_machine(wav: &Path) -> Result<Command> {
    qemu_pc_machine_with(wav, false)
}

/// As [`qemu_pc_machine`]; `restarts`: a restart starts it again rather
/// than ending QEMU, and the disks keep what is written to them from
/// one run to the next (a system update's).
fn qemu_pc_machine_with(wav: &Path, restarts: bool) -> Result<Command> {
    let data = root().join("target/data-pc.img");
    if !data.exists() {
        std::fs::File::create(&data)
            .and_then(|f| f.set_len(DATA_MIB << 20))
            .map_err(|e| format!("{}: {e}", data.display()))?;
    }
    let system = pc_system();
    let (width, height) = screen();
    let mut qemu = Command::new("qemu-system-x86_64");
    qemu.args(["-M", "q35", "-cpu", "max", "-m", "256M"])
        .args(["-smp", &cores().to_string()])
        // The virtio-gpu is the screen: no VGA beside it.
        .args(["-vga", "none", "-display", "none", "-monitor", "none"])
        .args(["-serial", "stdio"])
        .args(if restarts { &[][..] } else { &["-no-reboot"][..] })
        .args(["-device", "isa-debug-exit,iobase=0xf4,iosize=0x04"])
        .args(["-device", "virtio-rng-pci"])
        .args(["-device", &format!("virtio-gpu-pci,xres={width},yres={height}")])
        .args(["-device", "virtio-tablet-pci", "-device", "virtio-keyboard-pci"])
        .args(["-netdev", "user,id=net0", "-device", "virtio-net-pci,netdev=net0"])
        .args([
            "-audiodev",
            &format!("wav,id=snd0,path={}", wav.display()),
            "-device",
            "virtio-sound-pci,audiodev=snd0",
        ])
        .args([
            "-drive",
            &format!(
                "if=none,id=system,format=raw,file={},snapshot={}",
                system.display(),
                if restarts { "off" } else { "on" }
            ),
            "-device",
            "virtio-blk-pci,drive=system",
        ])
        .args([
            "-drive",
            &format!(
                "if=none,id=data,format=raw,file={},snapshot={}",
                data.display(),
                if restarts { "off" } else { "on" }
            ),
            "-device",
            "virtio-blk-pci,drive=data",
        ]);
    Ok(qemu)
}

/// The kernel for a PC (x86-64): linted, then booted in QEMU (`q35`, by
/// PVH through `-kernel`) through its checks, which end in "pc ok".
fn pc() -> Result {
    let elf = pc_build()?;
    let wav = root().join("target/test-pc.wav");
    let mut qemu = qemu_pc(&elf, "selfcheck", &wav)?;
    qemu.args(hardware("pc", Arch::Pc)?);
    let out = pc_check(qemu, &wav, "ELF by PVH (x86-64)")?;
    for expected in HARDWARE_LINES {
        if !out.contains(expected) {
            return Err(format!("pc: no \"{expected}\" in the output"));
        }
    }
    println!("ok   pc: USB (keyboard, tablet, stick), NVMe, SATA");
    Ok(())
}

/// As [`pc`], the way a real PC boots: UEFI's firmware (OVMF) starts
/// Pinnacle's loader (`boot/`) from an EFI system partition, and the loader
/// the kernel by Multiboot2 (`install.rs` has the firmware and the loader).
fn pc_efi() -> Result {
    let loader = install::loader(Arch::Pc)?;
    let elf = pc_kernel()?;
    disks_for(Arch::Pc, &pc_system(), &serve()?, &[], 64)?;
    let esp = root().join("target/pc-efi/esp");
    let _ = std::fs::remove_dir_all(&esp);
    for dir in ["EFI/BOOT", "PINNACLE"] {
        std::fs::create_dir_all(esp.join(dir)).map_err(|e| format!("{}: {e}", esp.display()))?;
    }
    let copy = |from: &Path, to: &str| {
        std::fs::copy(from, esp.join(to)).map_err(|e| format!("{}: {e}", from.display()))
    };
    copy(&loader, "EFI/BOOT/BOOTX64.EFI")?;
    copy(&elf, "PINNACLE/KERNEL")?;
    std::fs::write(esp.join("PINNACLE/CMDLINE"), "selfcheck").map_err(|e| e.to_string())?;
    let wav = root().join("target/test-pc-efi.wav");
    let mut qemu = qemu_pc_machine(&wav)?;
    // The loader holds the kernel's file (its programs inside) and puts its
    // copy where it runs: more than 256 MiB.
    qemu.args(["-m", "1G"]).args(install::firmware(Arch::Pc)?).args([
        "-drive",
        &format!("format=raw,file=fat:rw:{},if=ide", esp.display()),
    ]);
    let out = pc_check(qemu, &wav, "UEFI, Pinnacle's loader, Multiboot2 (x86-64)")?;
    if !out.contains("Pinnacle: starting the kernel") {
        return Err("pc-efi: the loader did not say it started the kernel".into());
    }
    Ok(())
}

/// Runs a PC's self-check in `qemu` (it plays into `wav`) and requires its
/// "pc ok", its power-off and its tone. Its output.
fn pc_check(mut qemu: Command, wav: &Path, what: &str) -> Result<String> {
    let mut child = qemu
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .spawn()
        .map_err(|e| format!("qemu-system-x86_64: {e}"))?;
    let start = Instant::now();
    let status = loop {
        if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
            break Some(status);
        }
        if start.elapsed() > Duration::from_secs(60) {
            let _ = child.kill();
            let _ = child.wait();
            break None;
        }
        std::thread::sleep(Duration::from_millis(100));
    };
    let mut out = String::new();
    if let Some(mut stdout) = child.stdout.take() {
        let _ = stdout.read_to_string(&mut out);
    }
    for line in out.lines() {
        println!("  [pc] {line}");
    }
    // isa-debug-exit: status 1 is the kernel's power_off(0).
    match status {
        Some(s) if s.code() == Some(1) && out.contains("pc ok") => {
            expect_tone(wav, 440.0, 0.25)?;
            println!("ok   pc: {what}");
            Ok(out)
        }
        Some(s) => Err(format!("pc: QEMU ended with {s}")),
        None => Err("pc: no power-off within 60 s".into()),
    }
}

/// Boots the boot image, waits for `after` on the serial port, pauses the
/// machine and writes its screen to `out` as a PNG.
fn shot(out: &Path, after: &str) -> Result {
    disks(&serve()?)?;
    let image = image("qemu-virt")?;
    shot_of(qemu("virt", &Load::Image(image, "")), out, after, boot_timeout())
}

/// As [`shot`], of a PC (`cargo xtask pc-shot`).
fn pc_shot(out: &Path, after: &str) -> Result {
    let elf = pc_build()?;
    // The PC runs every check before it starts the system: give it longer.
    let wav = root().join("target/shot-pc.wav");
    shot_of(qemu_pc(&elf, "", &wav)?, out, after, Duration::from_secs(120))
}

/// Starts `qemu`, waits for `after` on its serial port, pauses it and
/// writes its screen to `out`.
fn shot_of(qemu: Command, out: &Path, after: &str, timeout: Duration) -> Result {
    shot_with(qemu, out, after, timeout, None)
}

/// As [`shot_of`], the screen read from the guest's `memory` when given
/// rather than from QEMU's display.
fn shot_with(
    mut qemu: Command,
    out: &Path,
    after: &str,
    timeout: Duration,
    memory: Option<LitMemory>,
) -> Result {
    use std::io::{BufRead, BufReader, Write};
    use std::os::unix::net::UnixStream;
    let socket = std::env::temp_dir().join(format!("pinnacle-qmp-{}", std::process::id()));
    let mut child = qemu
        .arg("-qmp")
        .arg(format!("unix:{},server=on,wait=off", socket.display()))
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .spawn()
        .map_err(|e| format!("qemu: {e}"))?;
    let result = (|| -> Result {
        // Lines read on a thread of their own, so the deadline holds while
        // the kernel prints nothing: waiting on the read alone once held a
        // build node for hours.
        let (sender, lines) = std::sync::mpsc::channel();
        let stdout = child.stdout.take().unwrap();
        std::thread::spawn(move || {
            for line in BufReader::new(stdout).lines() {
                if sender.send(line).is_err() {
                    break;
                }
            }
        });
        let deadline = Instant::now() + timeout;
        loop {
            let left = deadline.saturating_duration_since(Instant::now());
            let line = match lines.recv_timeout(left) {
                Ok(line) => line.map_err(|e| e.to_string())?,
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    return Err(format!("no \"{after}\" within {}s", timeout.as_secs()));
                }
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                    return Err(format!("the kernel stopped before printing \"{after}\""));
                }
            };
            println!("  {}", line.trim_end());
            if line.trim_end().starts_with(after) {
                // The line comes when a frame is sent; let it reach the screen.
                std::thread::sleep(Duration::from_millis(500));
                break;
            }
            if Instant::now() > deadline {
                return Err(format!("no \"{after}\" within {}s", timeout.as_secs()));
            }
        }
        let mut qmp = UnixStream::connect(&socket).map_err(|e| format!("QMP: {e}"))?;
        let mut replies = BufReader::new(qmp.try_clone().map_err(|e| e.to_string())?).lines();
        let mut call = |command: String| -> Result<String> {
            writeln!(qmp, "{command}").map_err(|e| e.to_string())?;
            loop {
                let reply = replies.next().ok_or("QMP closed")?.map_err(|e| e.to_string())?;
                if reply.contains("\"return\"") || reply.contains("\"error\"") {
                    return Ok(reply);
                }
            }
        };
        replies_greeting(&mut call)?;
        call(r#"{"execute":"stop"}"#.into())?;
        let ppm = out.with_extension("ppm");
        if let Some(lit) = &memory {
            let raw = out.with_extension("raw");
            let reply = call(format!(
                r#"{{"execute":"pmemsave","arguments":{{"val":{},"size":{},"filename":"{}"}}}}"#,
                lit.address,
                u64::from(lit.stride) * u64::from(lit.height),
                raw.display()
            ))?;
            if reply.contains("\"error\"") {
                return Err(format!("pmemsave: {reply}"));
            }
            lit.to_ppm(&raw, &ppm)?;
            let _ = std::fs::remove_file(&raw);
        } else {
            let reply = call(format!(
                r#"{{"execute":"screendump","arguments":{{"filename":"{}"}}}}"#,
                ppm.display()
            ))?;
            if reply.contains("\"error\"") {
                return Err(format!("screendump: {reply}"));
            }
        }
        let _ = call(r#"{"execute":"quit"}"#.into());
        write_png(&ppm, out)?;
        let _ = std::fs::remove_file(&ppm);
        println!("{}", out.display());
        Ok(())
    })();
    let _ = child.kill();
    let _ = child.wait();
    let _ = std::fs::remove_file(&socket);
    result
}

/// QMP starts with a greeting and wants `qmp_capabilities` before anything.
fn replies_greeting(call: &mut impl FnMut(String) -> Result<String>) -> Result {
    call(r#"{"execute":"qmp_capabilities"}"#.into()).map(|_| ())
}

/// Converts QEMU's screendump (binary PPM) to a PNG: rows filtered by their
/// difference from the row above, compressed with a small deflate (static
/// Huffman codes, runs found by a hash of three bytes).
fn write_png(ppm: &Path, out: &Path) -> Result {
    let data = std::fs::read(ppm).map_err(|e| format!("{}: {e}", ppm.display()))?;
    let mut fields = Vec::new();
    let mut at = 0;
    while fields.len() < 4 {
        while data[at].is_ascii_whitespace() {
            at += 1;
        }
        let start = at;
        while !data[at].is_ascii_whitespace() {
            at += 1;
        }
        fields.push(String::from_utf8_lossy(&data[start..at]).into_owned());
    }
    at += 1;
    let (width, height): (usize, usize) = (
        fields[1].parse().map_err(|_| "bad PPM")?,
        fields[2].parse().map_err(|_| "bad PPM")?,
    );
    if fields[0] != "P6" || fields[3] != "255" {
        return Err("not an 8-bit binary PPM".into());
    }
    let rgb = &data[at..at + width * height * 3];
    let stride = width * 3;
    let mut raw = Vec::with_capacity((stride + 1) * height);
    for y in 0..height {
        let row = &rgb[y * stride..(y + 1) * stride];
        raw.push(2); // filter: Up
        if y == 0 {
            raw.extend_from_slice(row);
        } else {
            let above = &rgb[(y - 1) * stride..y * stride];
            raw.extend(row.iter().zip(above).map(|(a, b)| a.wrapping_sub(*b)));
        }
    }
    let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
    let mut chunk = |kind: &[u8], body: &[u8]| {
        png.extend_from_slice(&(body.len() as u32).to_be_bytes());
        let start = png.len();
        png.extend_from_slice(kind);
        png.extend_from_slice(body);
        let crc = crc32(&png[start..]);
        png.extend_from_slice(&crc.to_be_bytes());
    };
    let mut header = Vec::new();
    header.extend_from_slice(&(width as u32).to_be_bytes());
    header.extend_from_slice(&(height as u32).to_be_bytes());
    header.extend_from_slice(&[8, 2, 0, 0, 0]);
    chunk(b"IHDR", &header);
    chunk(b"IDAT", &zlib(&raw));
    chunk(b"IEND", &[]);
    std::fs::write(out, png).map_err(|e| format!("{}: {e}", out.display()))
}

fn crc32(bytes: &[u8]) -> u32 {
    let mut crc = !0u32;
    for &b in bytes {
        crc ^= u32::from(b);
        for _ in 0..8 {
            crc = if crc & 1 != 0 {
                0xedb8_8320 ^ (crc >> 1)
            } else {
                crc >> 1
            };
        }
    }
    !crc
}

/// zlib around one deflate block with the static Huffman codes.
fn zlib(data: &[u8]) -> Vec<u8> {
    struct Bits {
        out: Vec<u8>,
        bits: u64,
        count: u32,
    }
    impl Bits {
        fn put(&mut self, value: u32, count: u32) {
            self.bits |= u64::from(value) << self.count;
            self.count += count;
            while self.count >= 8 {
                self.out.push(self.bits as u8);
                self.bits >>= 8;
                self.count -= 8;
            }
        }
        /// Huffman codes go most significant bit first.
        fn code(&mut self, code: u32, count: u32) {
            let reversed = code.reverse_bits() >> (32 - count);
            self.put(reversed, count);
        }
        fn literal(&mut self, byte: u32) {
            match byte {
                0..=143 => self.code(0x30 + byte, 8),
                144..=255 => self.code(0x190 + byte - 144, 9),
                256..=279 => self.code(byte - 256, 7),
                _ => self.code(0xc0 + byte - 280, 8),
            }
        }
    }
    const LENGTHS: [(u32, u32); 29] = [
        (3, 0),
        (4, 0),
        (5, 0),
        (6, 0),
        (7, 0),
        (8, 0),
        (9, 0),
        (10, 0),
        (11, 1),
        (13, 1),
        (15, 1),
        (17, 1),
        (19, 2),
        (23, 2),
        (27, 2),
        (31, 2),
        (35, 3),
        (43, 3),
        (51, 3),
        (59, 3),
        (67, 4),
        (83, 4),
        (99, 4),
        (115, 4),
        (131, 5),
        (163, 5),
        (195, 5),
        (227, 5),
        (258, 0),
    ];
    const DISTANCES: [(u32, u32); 30] = [
        (1, 0),
        (2, 0),
        (3, 0),
        (4, 0),
        (5, 1),
        (7, 1),
        (9, 2),
        (13, 2),
        (17, 3),
        (25, 3),
        (33, 4),
        (49, 4),
        (65, 5),
        (97, 5),
        (129, 6),
        (193, 6),
        (257, 7),
        (385, 7),
        (513, 8),
        (769, 8),
        (1025, 9),
        (1537, 9),
        (2049, 10),
        (3073, 10),
        (4097, 11),
        (6145, 11),
        (8193, 12),
        (12289, 12),
        (16385, 13),
        (24577, 13),
    ];
    let mut bits = Bits {
        out: vec![0x78, 0x01],
        bits: 0,
        count: 0,
    };
    bits.put(1, 1); // the last block
    bits.put(1, 2); // static codes
    const WINDOW: usize = 32768;
    let mut table = vec![usize::MAX; 1 << 16];
    let hash = |i: usize| {
        ((u32::from(data[i]) << 8 ^ u32::from(data[i + 1]) << 4 ^ u32::from(data[i + 2])) & 0xffff) as usize
    };
    let mut i = 0;
    while i < data.len() {
        let mut best = (0, 0);
        if i + 3 <= data.len() {
            let h = hash(i);
            let candidate = table[h];
            table[h] = i;
            if candidate != usize::MAX && i - candidate <= WINDOW {
                let len = data[i..]
                    .iter()
                    .zip(&data[candidate..])
                    .take(258)
                    .take_while(|(a, b)| a == b)
                    .count();
                if len >= 3 {
                    best = (len, i - candidate);
                }
            }
        }
        if best.0 >= 3 {
            let (len, distance) = (best.0 as u32, best.1 as u32);
            let code = LENGTHS.iter().rposition(|&(base, _)| base <= len).unwrap();
            bits.literal(257 + code as u32);
            bits.put(len - LENGTHS[code].0, LENGTHS[code].1);
            let code = DISTANCES.iter().rposition(|&(base, _)| base <= distance).unwrap();
            bits.code(code as u32, 5);
            bits.put(distance - DISTANCES[code].0, DISTANCES[code].1);
            for j in i + 1..(i + best.0).min(data.len().saturating_sub(2)) {
                table[hash(j)] = j;
            }
            i += best.0;
        } else {
            bits.literal(u32::from(data[i]));
            i += 1;
        }
    }
    bits.literal(256);
    bits.put(0, 7);
    let (mut a, mut b) = (1u32, 0u32);
    for &byte in data {
        a = (a + u32::from(byte)) % 65521;
        b = (b + a) % 65521;
    }
    let mut out = bits.out;
    out.extend_from_slice(&(b << 16 | a).to_be_bytes());
    out
}

/// Built into the kernel: what runs before there is anything on disk.
const SYSTEM_PROGRAMS: &[&str] = &[
    "ask", "bt", "devices", "display", "echo", "hello", "info", "launcher", "p2p", "palette", "phone",
    "settings", "agent", "model", "store", "terminal", "verbs", "frits", "files", "filer", "filter", "fien",
    "kees", "updates", "wifi", "sync", "time", "speech", "admin",
];
/// On the system disk from the start: name, title, description.
const PREINSTALLED: &[(&str, &str, &str)] = &[
    ("clock", "Clock", "The time and the date"),
    ("about", "About", "This device: its system, cores and memory"),
    (
        "messages",
        "Messages",
        "End-to-end encrypted, peer to peer, no server",
    ),
    ("calls", "Calls", "Video calls, end-to-end encrypted, no server"),
    ("notes", "Notes", "Write things down"),
    (
        "contacts",
        "Contacts",
        "People: their numbers, addresses and birthdays",
    ),
    (
        "bluetooth",
        "Bluetooth",
        "Devices nearby; contacts with no network",
    ),
];

/// What the launcher prints once the home screen shows the preinstalled
/// apps and `added` more from the Store.
fn home_apps(added: usize) -> String {
    format!("launcher: {} apps", PREINSTALLED.len() + added)
}

/// Offered by the package source, to install from the Store.
const PACKAGES: &[(&str, &str, &str)] = &[
    (
        "calculator",
        "Calculator",
        "Sums with decimals and percentages, by tap or keyboard",
    ),
    ("paint", "Paint", "Draw with a finger; your drawing is kept"),
];

/// A disk image file, block by block.
struct ImageFile(std::fs::File, u32);

impl pinnacle_fs::Disk for ImageFile {
    fn read(&mut self, block: u32, into: &mut [u8; pinnacle_fs::BLOCK]) {
        use std::io::{Read, Seek, SeekFrom};
        self.0
            .seek(SeekFrom::Start(u64::from(block) * pinnacle_fs::BLOCK as u64))
            .unwrap();
        self.0.read_exact(into).unwrap();
    }
    fn write(&mut self, block: u32, from: &[u8; pinnacle_fs::BLOCK]) {
        use std::io::{Seek, SeekFrom, Write};
        self.0
            .seek(SeekFrom::Start(u64::from(block) * pinnacle_fs::BLOCK as u64))
            .unwrap();
        self.0.write_all(from).unwrap();
    }
    fn blocks(&self) -> u32 {
        self.1
    }
}

fn new_image(path: &Path, mib: u32, label: &str) -> Result<pinnacle_fs::Fs<ImageFile>> {
    let file = std::fs::File::options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(path)
        .map_err(|e| format!("{}: {e}", path.display()))?;
    file.set_len(u64::from(mib) << 20).map_err(|e| e.to_string())?;
    Ok(pinnacle_fs::format(ImageFile(file, mib * 256), label))
}

fn manifest(name: &str, title: &str, description: &str) -> String {
    format!(
        "name={name}\ntitle={title}\nversion={}\ndescription={description}\n",
        env!("CARGO_PKG_VERSION")
    )
}

/// The processor a system disk and its package source are for: a program
/// built for one is refused by the other's kernel (`process.rs`).
#[derive(Clone, Copy, PartialEq)]
enum Arch {
    Arm,
    Pc,
}

impl Arch {
    /// Builds its programs.
    fn build(self) -> Result {
        match self {
            Arch::Arm => build_user(),
            Arch::Pc => build_user_pc().map(drop),
        }
    }

    fn program(self, name: &str) -> Result<Vec<u8>> {
        let path = match self {
            Arch::Arm => root().join("target").join(TARGET).join("release"),
            Arch::Pc => root().join("target/pc-user/x86_64-unknown-none/release"),
        }
        .join(name);
        std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))
    }

    /// Where in the package source its packages are: a PC's beneath ARM's,
    /// so one server (and one store URL with `pc/` added) serves both.
    fn store_path(self) -> &'static str {
        match self {
            Arch::Arm => "",
            Arch::Pc => "pc/",
        }
    }
}

/// The package source the Store reads over HTTP: `target/repository/`,
/// holding `catalog` and `packages/<name>.ppk`, served by [`serve`].
fn repository() -> PathBuf {
    root().join("target/repository")
}

/// The system disk (the preinstalled apps under `/apps`, and where the Store
/// finds packages, `/settings/store-url`) and the package source, in
/// `target/`.
fn disks(store_url: &str) -> Result<PathBuf> {
    disks_at(&root().join("target/system.img"), store_url, &[])
}

/// As [`disks`], the system disk at `system_path` with `extra` files on it
/// (path, contents), making their folders.
fn disks_at(system_path: &Path, store_url: &str, extra: &[(String, Vec<u8>)]) -> Result<PathBuf> {
    disks_for(Arch::Arm, system_path, store_url, extra, 64)
}

/// The hosted package sources a system's Store reads beside its own
/// (`/settings/store-sources`), for `arch`: one folder a publisher at
/// pinnacle-os.eu, signed with `keys/store-publisher.pub`'s key: this
/// repository's own apps (`package-apps`, after every landing), and
/// Cartopolis and Flitz, built for ARM only.
fn hosted_sources(arch: Arch) -> &'static str {
    match arch {
        Arch::Arm => {
            "https://pinnacle-os.eu/store/pinnacle/\nhttps://pinnacle-os.eu/store/cartopolis/\n\
             https://pinnacle-os.eu/store/flitz/\n"
        }
        Arch::Pc => "https://pinnacle-os.eu/store/pinnacle/pc/\n",
    }
}

/// The boards a system update is published for: those whose kernel hands
/// over to another (`kernel/src/chain.rs`): ARM's on QEMU, and a PC.
const SYSTEM_BOARDS: &[&str] = &["qemu-virt", "pc"];

/// The system for `board`, numbered `version`, as a package source in
/// `source/system/<board>/` (`docs/updates.md`): its kernel, and the files
/// a system disk comes with (the apps, the fonts, the certificates' roots),
/// signed with `secret` or unsigned for a server to sign. Its catalog line.
fn package_system(source: &Path, board: &str, version: &str, secret: Option<&[u8; 32]>) -> Result<String> {
    if version.contains(['|', '\n']) {
        return Err(format!("no version can be {version:?}"));
    }
    let kernel = if board == "pc" {
        // A PC's is its ELF, as GRUB loads it (`chain`), without what
        // only a debugger reads.
        let elf = pc_kernel_as(version)?;
        loadable(std::fs::read(&elf).map_err(|e| format!("{}: {e}", elf.display()))?)?
    } else {
        let image = image_as(board, version)?;
        std::fs::read(&image).map_err(|e| format!("{}: {e}", image.display()))?
    };
    package_system_with(source, board, version, kernel, secret)
}

/// As [`package_system`], with `kernel` as its kernel.
fn package_system_with(
    source: &Path,
    board: &str,
    version: &str,
    kernel: Vec<u8>,
    secret: Option<&[u8; 32]>,
) -> Result<String> {
    let read = |path: &Path| std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()));
    let mut files = vec![("kernel".to_string(), kernel)];
    let arch = if board == "pc" { Arch::Pc } else { Arch::Arm };
    for (name, title, description) in PREINSTALLED {
        files.push((format!("apps/{name}/program"), loadable(arch.program(name)?)?));
        files.push((
            format!("apps/{name}/manifest"),
            manifest(name, title, description).into_bytes(),
        ));
    }
    for (from, to) in [
        ("fonts/AdwaitaSans-Regular.ttf", "fonts/sans.ttf"),
        ("fonts/AdwaitaMono-Regular.ttf", "fonts/mono.ttf"),
        ("fonts/NotoSansArabic-Regular.ttf", "fonts/arabic.ttf"),
        ("fonts/NotoSansHebrew-Regular.ttf", "fonts/hebrew.ttf"),
        ("fonts/DroidSansFallbackFull.ttf", "fonts/cjk.ttf"),
        ("fonts/NotoEmoji-Regular.ttf", "fonts/emoji.ttf"),
        ("fonts/LICENSE", "fonts/LICENSE"),
        ("certificates/mozilla-roots.pem", "certificates/roots.pem"),
    ] {
        files.push((to.to_string(), read(&root().join(from))?));
    }
    files.extend(zoneinfo()?);
    let manifest = format!(
        "name=system\ntitle=Pinnacle\nversion={version}\nboard={board}\n\
         description=The system: its kernel and programs, the apps it comes with, its fonts and certificates\n"
    );
    let dir = source.join("system").join(board);
    for old in [dir.join("packages"), dir.join("blobs")] {
        if old.exists() {
            std::fs::remove_dir_all(&old).map_err(|e| format!("{}: {e}", old.display()))?;
        }
    }
    let line = write_package(&dir, "system", &manifest, &files, secret)?;
    std::fs::write(dir.join("catalog"), &line).map_err(|e| e.to_string())?;
    Ok(line)
}

/// The time zones a system comes with (`zoneinfo/`, IANA's): each zone's
/// TZif file, `zones` and `version`, as paths under `zoneinfo/` and their
/// bytes.
fn zoneinfo() -> Result<Vec<(String, Vec<u8>)>> {
    fn walk(dir: &Path, under: &str, out: &mut Vec<(String, Vec<u8>)>) -> Result {
        let mut entries: Vec<_> = std::fs::read_dir(dir)
            .map_err(|e| format!("{}: {e}", dir.display()))?
            .map_while(|e| e.ok())
            .collect();
        entries.sort_by_key(|e| e.file_name());
        for entry in entries {
            let name = entry.file_name().to_string_lossy().into_owned();
            let path = format!("{under}/{name}");
            if entry.path().is_dir() {
                walk(&entry.path(), &path, out)?;
            } else if !["README.md", "update.sh"].contains(&name.as_str()) {
                out.push((path, std::fs::read(entry.path()).map_err(|e| e.to_string())?));
            }
        }
        Ok(())
    }
    let mut out = Vec::new();
    walk(&root().join("zoneinfo"), "zoneinfo", &mut out)?;
    Ok(out)
}

/// [`package_system`] for every board in [`SYSTEM_BOARDS`], unsigned, into
/// `out`: what `midas deploy pinnacle-apps` publishes beside the apps.
fn package_systems(out: &Path, version: &str) -> Result {
    for board in SYSTEM_BOARDS {
        // A PC's beside its apps, in `pc/`, where its updates service looks.
        let arch = if *board == "pc" { Arch::Pc } else { Arch::Arm };
        let source = out.join(arch.store_path());
        print!(
            "{}system/{board}/{}",
            arch.store_path(),
            package_system(&source, board, version, None)?
        );
    }
    Ok(())
}

/// This repository's Store apps ([`PACKAGES`]) for both processors, as the
/// package source a server signs and publishes (`docs/store.md`): ARM's in
/// `out`, a PC's in `out/pc`, each `catalog`, `packages/<name>.ppa`
/// (unsigned) and `blobs/`. `version` is what the Store compares with the
/// one installed.
fn package_apps(out: &Path, version: &str) -> Result {
    if version.contains(['|', '\n']) {
        return Err(format!("no version can be {version:?}"));
    }
    if out.exists() {
        std::fs::remove_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
    }
    for arch in [Arch::Arm, Arch::Pc] {
        arch.build()?;
        let source = out.join(arch.store_path());
        let mut catalog = String::new();
        for (name, title, description) in PACKAGES {
            let manifest =
                format!("name={name}\ntitle={title}\nversion={version}\ndescription={description}\n");
            let files = [("program".to_string(), arch.program(name)?)];
            catalog += &write_package(&source, name, &manifest, &files, None)?;
        }
        std::fs::write(source.join("catalog"), &catalog).map_err(|e| e.to_string())?;
        print!("{}{catalog}", arch.store_path());
    }
    // The hosted Store's registry list, `keys/publishers` issued as this
    // version, for the server to sign with the apps (`docs/store.md`).
    let list = format!("issued {version}\n{}", include_str!("../../keys/publishers"));
    let archive =
        pinnacle_pkg::trust::Registry::archive(&list).ok_or("keys/publishers is not a registry list")?;
    std::fs::write(out.join("packages/publishers.ppa"), archive).map_err(|e| e.to_string())?;
    println!("in {}", out.display());
    Ok(())
}

/// As [`disks_at`], its apps and packages built for `arch`; a PC's
/// package source is `pc/` within ARM's, and its store URL says so. The
/// system disk has `room_mib` MiB beside what is put on it, for what the
/// Store installs.
fn disks_for(
    arch: Arch,
    system_path: &Path,
    store_url: &str,
    extra: &[(String, Vec<u8>)],
    room_mib: usize,
) -> Result<PathBuf> {
    arch.build()?;
    let store_url = format!("{store_url}{}", arch.store_path());
    let repository = repository().join(arch.store_path());
    let fail = |e: pinnacle_fs::Error| format!("{e:?}");
    let system_path = system_path.to_path_buf();
    // A PC's closed firmware (Intel's Wi-Fi), as data in a folder of its
    // own, unless PINNACLE_NO_FIRMWARE=1 (`firmware/`, docs/hardware.md).
    let firmware = match arch {
        Arch::Pc => firmware::for_image()?,
        Arch::Arm => Vec::new(),
    };
    // The room, and room for what is added (Cartopolis is 141 MiB).
    let added: usize = extra.iter().chain(&firmware).map(|(_, bytes)| bytes.len()).sum();
    let mib = room_mib + (added + added / 4).div_ceil(1 << 20);
    let mut system = new_image(&system_path, mib as _, "system")?;
    for (name, title, description) in PREINSTALLED {
        system.create_dir(&format!("/apps/{name}")).map_err(fail)?;
        system
            .write(&format!("/apps/{name}/program"), &arch.program(name)?)
            .map_err(fail)?;
        system
            .write(
                &format!("/apps/{name}/manifest"),
                manifest(name, title, description).as_bytes(),
            )
            .map_err(fail)?;
    }
    system.create_dir("/settings").map_err(fail)?;
    system
        .write("/settings/store-url", store_url.as_bytes())
        .map_err(fail)?;
    if !hosted_sources(arch).is_empty() {
        system
            .write("/settings/store-sources", hosted_sources(arch).as_bytes())
            .map_err(fail)?;
    }
    // The system fonts, the fallbacks for what they lack, and their
    // licences, which travel with them.
    system.create_dir("/fonts").map_err(fail)?;
    for (from, to) in [
        ("fonts/AdwaitaSans-Regular.ttf", "/fonts/sans.ttf"),
        ("fonts/AdwaitaMono-Regular.ttf", "/fonts/mono.ttf"),
        ("fonts/NotoSansArabic-Regular.ttf", "/fonts/arabic.ttf"),
        ("fonts/NotoSansHebrew-Regular.ttf", "/fonts/hebrew.ttf"),
        ("fonts/DroidSansFallbackFull.ttf", "/fonts/cjk.ttf"),
        ("fonts/NotoEmoji-Regular.ttf", "/fonts/emoji.ttf"),
        ("fonts/LICENSE", "/fonts/LICENSE"),
    ] {
        let bytes = std::fs::read(root().join(from)).map_err(|e| format!("{from}: {e}"))?;
        system.write(to, &bytes).map_err(fail)?;
    }
    // The roots a TLS server's chain must reach: Mozilla's (`certificates/`).
    system.create_dir("/certificates").map_err(fail)?;
    let roots =
        std::fs::read(root().join("certificates/mozilla-roots.pem")).map_err(|e| format!("roots: {e}"))?;
    system.write("/certificates/roots.pem", &roots).map_err(fail)?;
    // The time zones (`zoneinfo/`), which every app may read.
    for (path, bytes) in zoneinfo()? {
        if let Some((dir, _)) = path.rsplit_once('/') {
            system.create_dir(&format!("/{dir}")).map_err(fail)?;
        }
        system.write(&format!("/{path}"), &bytes).map_err(fail)?;
    }
    for (path, contents) in extra {
        if let Some((dir, _)) = path.rsplit_once('/')
            && !dir.is_empty()
        {
            system.create_dir(dir).map_err(fail)?;
        }
        system.write(path, contents).map_err(fail)?;
    }
    for (path, contents) in &firmware {
        if let Some((dir, _)) = path.rsplit_once('/') {
            system.create_dir(dir).map_err(fail)?;
        }
        system.write(path, contents).map_err(fail)?;
    }
    // The keys the system trusts: this checkout's publisher, whose packages
    // `serve` offers, and the hosted Store's; for apps, and apart for
    // systems (`docs/updates.md`), which no app's publisher signs.
    let secret = publisher_key()?;
    let public = pinnacle_crypto::ed25519::public(&secret);
    let keys = format!(
        "{}\n{}",
        pinnacle_pkg::key_hex(&public),
        include_str!("../../keys/store-publisher.pub")
    );
    // For apps each key its publisher's, both registries
    // (`pinnacle_pkg::trust`): the hosted Store's admits other publishers.
    let hosted = pinnacle_pkg::parse_keys(include_str!("../../keys/store-publisher.pub"));
    let apps = format!(
        "{} this-checkout registry\n{} pinnacle registry\n",
        pinnacle_pkg::key_hex(&public),
        pinnacle_pkg::key_hex(hosted.first().ok_or("keys/store-publisher.pub has no key")?)
    );
    system
        .write("/settings/trusted-keys", apps.as_bytes())
        .map_err(fail)?;
    system
        .write("/settings/system-keys", keys.as_bytes())
        .map_err(fail)?;
    // Only this build's packages and files (a PC's source is a folder
    // within ARM's, and stays).
    for old in [repository.join("packages"), repository.join("blobs")] {
        if old.exists() {
            std::fs::remove_dir_all(&old).map_err(|e| format!("{}: {e}", old.display()))?;
        }
    }
    let mut catalog = String::new();
    for (name, title, description) in PACKAGES {
        let files = [("program".to_string(), arch.program(name)?)];
        catalog += &write_package(
            &repository,
            name,
            &manifest(name, title, description),
            &files,
            Some(&secret),
        )?;
    }
    std::fs::write(repository.join("catalog"), catalog).map_err(|e| e.to_string())?;
    // Not in the catalog: a package signed by a key nobody trusts, which the
    // self-check fetches to see it refused.
    let forged = pinnacle_pkg::pack_signed(&[("manifest", b"title=Forged\n")], &[0x66; 32]);
    std::fs::write(repository.join("packages/forged.ppk"), forged).map_err(|e| e.to_string())?;
    // This checkout's registry list, which the self-check reads: it admits
    // a publisher "friend", and admits and takes back "leaky"; a package
    // of each beside it, none in the catalog.
    let (friend, leaky) = ([0x21; 32], [0x22; 32]);
    let hex = |secret: &[u8; 32]| pinnacle_pkg::key_hex(&pinnacle_crypto::ed25519::public(secret));
    let list = format!(
        "issued 1\nkey {} friend\nkey {} leaky\nrevoked {}\n",
        hex(&friend),
        hex(&leaky),
        hex(&leaky)
    );
    let archive = pinnacle_pkg::trust::Registry::archive(&list).ok_or("a registry list that is not one")?;
    let registry = pinnacle_pkg::pack_signed(&pinnacle_pkg::unpack(&archive).unwrap(), &secret);
    let manifest = b"name=calculator\ntitle=Not the calculator\nversion=0\n";
    for (file, bytes) in [
        ("publishers.ppk", registry),
        (
            "friendly.ppk",
            pinnacle_pkg::pack_signed(&[("manifest", manifest)], &friend),
        ),
        (
            "leaked.ppk",
            pinnacle_pkg::pack_signed(&[("manifest", manifest)], &leaky),
        ),
    ] {
        std::fs::write(repository.join("packages").join(file), bytes).map_err(|e| e.to_string())?;
    }
    Ok(system_path)
}

/// Puts an app into the package source at `source`: each of its `files`
/// (path in its folder, contents) as `blobs/<sha256>`, and the package
/// listing them, `packages/<name>.ppk` signed with `secret`, or with none
/// `packages/<name>.ppa`, the archive a server signs (`docs/store.md`).
/// Returns its line of the catalog.
fn write_package(
    source: &Path,
    name: &str,
    manifest: &str,
    files: &[(String, Vec<u8>)],
    secret: Option<&[u8; 32]>,
) -> Result<String> {
    let (packages, blobs) = (source.join("packages"), source.join("blobs"));
    for dir in [&packages, &blobs] {
        std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    }
    let mut listed = Vec::new();
    for (path, bytes) in files {
        let file = pinnacle_pkg::File {
            sha256: pinnacle_crypto::sha2::Sha256::digest(bytes),
            size: bytes.len() as u64,
            path,
        };
        let blob = blobs.join(file.blob());
        if !blob.exists() {
            std::fs::write(&blob, bytes).map_err(|e| format!("{}: {e}", blob.display()))?;
        }
        listed.push(file);
    }
    let list = pinnacle_pkg::files_text(&listed);
    if pinnacle_pkg::files(&list).as_ref() != Some(&listed) {
        return Err(format!("{name}: a path the Store would refuse"));
    }
    let entries: [(&str, &[u8]); 2] = [("manifest", manifest.as_bytes()), ("files", list.as_bytes())];
    let (package, file) = match secret {
        Some(secret) => (pinnacle_pkg::pack_signed(&entries, secret), format!("{name}.ppk")),
        None => (pinnacle_pkg::pack(&entries), format!("{name}.ppa")),
    };
    std::fs::write(packages.join(file), &package).map_err(|e| e.to_string())?;
    // What it may do beyond its own folder, which the Store shows.
    let rights = pinnacle_pkg::Rights::of_manifest(manifest)
        .ok_or("a manifest with an unknown effect")?
        .to_catalog();
    let field = |key: &str| manifest_field(manifest, key);
    let size: u64 = listed.iter().map(|f| f.size).sum();
    Ok(format!(
        "{name}|{}|{}|{size}|{}|{rights}\n",
        field("title"),
        field("version"),
        field("description")
    ))
}

/// A manifest's `key=value`, empty when it has none.
fn manifest_field<'a>(manifest: &'a str, key: &str) -> &'a str {
    manifest
        .lines()
        .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
        .unwrap_or("")
        .trim()
}

/// The development publisher's secret key: made once per checkout in
/// `target/publisher.key` from the host's randomness, and never committed.
/// The hosted Store signs with a key of its own, on its server (`docs/store.md`).
fn publisher_key() -> Result<[u8; 32]> {
    let path = root().join("target/publisher.key");
    if let Ok(bytes) = std::fs::read(&path)
        && let Ok(key) = bytes.try_into()
    {
        return Ok(key);
    }
    let mut key = [0u8; 32];
    std::fs::File::open("/dev/urandom")
        .and_then(|mut f| f.read_exact(&mut key))
        .map_err(|e| format!("/dev/urandom: {e}"))?;
    std::fs::create_dir_all(root().join("target")).map_err(|e| e.to_string())?;
    std::fs::write(&path, key).map_err(|e| format!("{}: {e}", path.display()))?;
    Ok(key)
}

/// Serves the package source over HTTP/1.0 on a free local port, on a
/// thread for the rest of this run, and beside it a stand-in model provider
/// (`model.rs`); QEMU's guest reaches the host as 10.0.2.2, and over IPv6 as
/// fec0::2, which QEMU takes to the host's ::1, where it listens too when
/// the host has IPv6. Returns the URL the guest uses.
fn serve() -> Result<String> {
    serve_on(0)
}

/// As [`serve`], on `port` if it is free (0: any).
fn serve_on(port: u16) -> Result<String> {
    let listener = std::net::TcpListener::bind(("127.0.0.1", port))
        .or_else(|_| std::net::TcpListener::bind("127.0.0.1:0"))
        .map_err(|e| e.to_string())?;
    let port = listener.local_addr().map_err(|e| e.to_string())?.port();
    let six = std::net::TcpListener::bind(("::1", port)).ok();
    for listener in std::iter::once(listener).chain(six) {
        std::thread::spawn(move || serve_from(listener));
    }
    Ok(format!("http://10.0.2.2:{port}/"))
}

/// What [`serve_on`] answers, on one listener.
fn serve_from(listener: std::net::TcpListener) {
    use std::io::{BufRead, BufReader, Write};
    for stream in listener.incoming().map_while(|s| s.ok()) {
        std::thread::spawn(move || {
            let mut reader = BufReader::new(&stream);
            let mut line = String::new();
            if reader.read_line(&mut line).is_err() {
                return;
            }
            // The rest of the request's head.
            let mut headers = Vec::new();
            let mut header = String::new();
            while reader.read_line(&mut header).is_ok_and(|n| n > 2) {
                if let Some((name, value)) = header.split_once(':') {
                    headers.push((name.trim().to_string(), value.trim().to_string()));
                }
                header.clear();
            }
            let path = line.split(' ').nth(1).unwrap_or("/").trim_start_matches('/');
            // The stand-in model provider (`model.rs`).
            if line.starts_with("POST ") && path.ends_with("v1/messages") {
                let length = headers
                    .iter()
                    .find(|(n, _)| n.eq_ignore_ascii_case("content-length"))
                    .and_then(|(_, v)| v.parse::<usize>().ok())
                    .unwrap_or(0)
                    .min(16 << 20);
                let mut body = vec![0; length];
                if std::io::Read::read_exact(&mut reader, &mut body).is_ok() {
                    model::answer(&headers, &body, &stream);
                }
                return;
            }
            let file = (!path.contains("..")).then(|| repository().join(path));
            let mut stream = &stream;
            match file.and_then(|f| std::fs::read(f).ok()) {
                Some(body) => {
                    let _ = write!(
                        stream,
                        "HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n",
                        body.len()
                    );
                    let _ = stream.write_all(&body);
                }
                None => {
                    let _ = write!(stream, "HTTP/1.0 404 Not Found\r\nContent-Length: 0\r\n\r\n");
                }
            }
        });
    }
}

/// Numbers the QMP sockets of the sessions this run starts.
static SOCKETS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// A running QEMU to drive: its serial lines as they come, and QMP.
struct Session {
    child: std::process::Child,
    lines: std::sync::mpsc::Receiver<String>,
    qmp: std::os::unix::net::UnixStream,
    replies: std::io::Lines<std::io::BufReader<std::os::unix::net::UnixStream>>,
    socket: PathBuf,
    /// Where the controls apps announced last are (`<name> at <x> <y>`),
    /// by name, from whichever wait read the line.
    named: std::collections::HashMap<String, (i32, i32)>,
    /// Every serial line read so far, for [`Session::saw`].
    read: Vec<String>,
    /// The screen's size, which taps are scaled to.
    screen: (i32, i32),
}

impl Session {
    /// Boots the system (its disks fresh, writes kept for this run only).
    fn start() -> Result<Session> {
        disks(&serve()?)?;
        Session::boot(&Guest::default(), "")
    }

    /// Boots `guest` (writes kept for this run only), its serial lines
    /// prefixed with `label`.
    fn boot(guest: &Guest, label: &str) -> Result<Session> {
        let image = image("qemu-virt")?;
        // Every guest's Bluetooth controller is in the one simulated air.
        // And its modem on the one simulated cell network.
        let bt_socket = air().socket_for_guest();
        let modem_socket = cell().socket_for_guest();
        // And its Wi-Fi radio among the one set of access points.
        let wifi_socket = wifi_air().socket_for_guest();
        let guest = Guest {
            bluetooth: Some(bt_socket.clone()),
            modem: Some(modem_socket.clone()),
            wifi: Some(wifi_socket.clone()),
            ..guest.clone()
        };
        Session::attach(
            qemu_guest("virt", &Load::Image(image, ""), true, &guest),
            label,
            guest.data.is_some(),
            || {
                air().attach(&bt_socket)?;
                wifi_air().attach(&wifi_socket)?;
                cell().attach(&modem_socket).map(|_| ())
            },
        )
    }

    /// Starts `qemu` with QMP to drive it, runs `started` once it runs, and
    /// with a `blank_data` disk chooses the data's password.
    fn attach(
        mut qemu: Command,
        label: &str,
        blank_data: bool,
        started: impl FnOnce() -> Result,
    ) -> Result<Session> {
        use std::io::{BufRead, BufReader};
        let n = SOCKETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let socket = std::env::temp_dir().join(format!("pinnacle-qmp-{}-{n}", std::process::id()));
        let child = qemu
            .arg("-qmp")
            .arg(format!("unix:{},server=on,wait=off", socket.display()))
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .spawn()
            .map_err(|e| format!("qemu: {e}"))?;
        // Until the Session holds it (whose Drop ends it), QEMU is ended on
        // any way out of here. Left running after an error, it kept the
        // stderr it inherited — the pipe to a `| grep` — open, and an ssh
        // to the node waited on that grep for 19 hours (2026-11-27).
        let mut guard = Running(Some(child));
        started()?;
        let child = guard.0.as_mut().expect("held until the session takes it");
        let (send, lines) = std::sync::mpsc::channel();
        let stdout = child.stdout.take().unwrap();
        let label = label.to_string();
        std::thread::spawn(move || {
            for line in BufReader::new(stdout).lines().map_while(|l| l.ok()) {
                println!("  {label}{}", line.trim_end());
                if send.send(line.trim_end().to_string()).is_err() {
                    break;
                }
            }
        });
        let deadline = Instant::now() + Duration::from_secs(5);
        let qmp = loop {
            match std::os::unix::net::UnixStream::connect(&socket) {
                Ok(s) => break s,
                Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
                Err(e) => return Err(format!("QMP: {e}")),
            }
        };
        let replies = BufReader::new(qmp.try_clone().map_err(|e| e.to_string())?).lines();
        let mut session = Session {
            child: guard.0.take().expect("held until the session takes it"),
            lines,
            qmp,
            replies,
            socket,
            screen: screen(),
            named: std::collections::HashMap::new(),
            read: Vec::new(),
        };
        session.call(r#"{"execute":"qmp_capabilities"}"#)?;
        // A blank data disk (writes are kept for this run only): the system
        // asks for a passphrase, twice, before anything else starts.
        if blank_data {
            session.wait_for("display: choose a password for your data")?;
            for _ in 0..2 {
                session.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
                std::thread::sleep(Duration::from_millis(300));
            }
            session.wait_for("display: data opened")?;
        }
        Ok(session)
    }

    fn call(&mut self, command: &str) -> Result<String> {
        use std::io::Write;
        if let Err(e) = writeln!(self.qmp, "{command}") {
            // QEMU has gone: how it ended says more than the pipe.
            return Err(match self.child.try_wait() {
                Ok(Some(status)) => format!("QEMU ended ({status}) before {command}"),
                _ => e.to_string(),
            });
        }
        loop {
            let reply = self
                .replies
                .next()
                .ok_or("QMP closed")?
                .map_err(|e| e.to_string())?;
            if reply.contains("\"return\"") || reply.contains("\"error\"") {
                return Ok(reply);
            }
        }
    }

    /// Waits for a serial line that starts with `prefix`, then lets the
    /// frame it announces reach the screen.
    /// Waits up to `limit` for a line starting with one of `prefixes`; the line.
    /// The next serial line, within `timeout`; a control's announced place
    /// in it (`<name> at <x> <y>`) is kept in `named` on the way, so a wait
    /// that reads past it does not lose it for [`Session::tap_named`].
    fn line(&mut self, timeout: Duration) -> std::result::Result<String, std::sync::mpsc::RecvTimeoutError> {
        let line = self.lines.recv_timeout(timeout)?;
        if let Some((name, at)) = line.trim().rsplit_once(" at ") {
            let mut it = at.split_whitespace();
            let place = (|| Some((it.next()?.parse().ok()?, it.next()?.parse().ok()?)))();
            if let (Some(place), None) = (place, it.next()) {
                self.named.insert(name.to_string(), place);
            }
        }
        self.read.push(line.clone());
        Ok(line)
    }

    /// Whether a line starting with `prefix` was read already: one said
    /// while booting, before the session was handed over (the data's
    /// password typed meanwhile), or after, until it is.
    fn saw(&mut self, prefix: &str) -> Result {
        if self.read.iter().any(|l| l.starts_with(prefix)) {
            return Ok(());
        }
        self.wait_for(prefix)
    }

    fn wait_any(&mut self, prefixes: &[&str], limit: Duration) -> Result<String> {
        let deadline = Instant::now() + limit;
        loop {
            let left = deadline.saturating_duration_since(Instant::now());
            match self.line(left) {
                Ok(line) if prefixes.iter().any(|p| line.starts_with(p)) => return Ok(line),
                Ok(line) if line.starts_with("panic") => return Err(format!("the system panicked: {line}")),
                Ok(_) => {}
                Err(_) => return Err(format!("none of {prefixes:?} within {}s", limit.as_secs())),
            }
        }
    }

    fn wait_for(&mut self, prefix: &str) -> Result {
        let deadline = Instant::now() + boot_timeout();
        loop {
            let left = deadline.saturating_duration_since(Instant::now());
            match self.line(left) {
                Ok(line) if line.starts_with(prefix) => {
                    std::thread::sleep(Duration::from_millis(600));
                    return Ok(());
                }
                Ok(line) if line.starts_with("panic") => return Err(format!("the system panicked: {line}")),
                Ok(_) => {}
                Err(_) => return Err(format!("no \"{prefix}\" within {}s", boot_timeout().as_secs())),
            }
        }
    }

    fn pointer(&mut self, x: i32, y: i32, button: Option<bool>) -> Result {
        // The tablet's axes run 0..=0x7fff across the screen.
        let (ax, ay) = (x * 0x8000 / self.screen.0, y * 0x8000 / self.screen.1);
        let mut events = format!(
            r#"{{"type":"abs","data":{{"axis":"x","value":{ax}}}}},{{"type":"abs","data":{{"axis":"y","value":{ay}}}}}"#
        );
        if let Some(down) = button {
            events += &format!(r#",{{"type":"btn","data":{{"down":{down},"button":"left"}}}}"#);
        }
        self.call(&format!(
            r#"{{"execute":"input-send-event","arguments":{{"events":[{events}]}}}}"#
        ))?;
        std::thread::sleep(Duration::from_millis(40));
        Ok(())
    }

    fn tap(&mut self, x: i32, y: i32) -> Result {
        self.pointer(x, y, Some(true))?;
        self.pointer(x, y, Some(false))
    }

    /// Clicks at `x`, `y` with a mouse (a touchpad), which moves only by
    /// how far: into the top left corner first, where the pointer stops,
    /// then from there.
    fn click_at(&mut self, x: i32, y: i32) -> Result {
        let (w, h) = self.screen;
        for (dx, dy) in [(-2 * w, -2 * h), (x, y)] {
            self.call(&format!(
                r#"{{"execute":"input-send-event","arguments":{{"events":[{{"type":"rel","data":{{"axis":"x","value":{dx}}}}},{{"type":"rel","data":{{"axis":"y","value":{dy}}}}}]}}}}"#
            ))?;
            // QEMU's mouse says at most 127 a report, a report a poll.
            std::thread::sleep(Duration::from_millis(400));
        }
        for down in [true, false] {
            self.call(&format!(
                r#"{{"execute":"input-send-event","arguments":{{"events":[{{"type":"btn","data":{{"down":{down},"button":"left"}}}}]}}}}"#
            ))?;
            std::thread::sleep(Duration::from_millis(100));
        }
        Ok(())
    }

    fn drag(&mut self, points: &[(i32, i32)]) -> Result {
        let Some((&(x, y), rest)) = points.split_first() else {
            return Ok(());
        };
        self.pointer(x, y, Some(true))?;
        for &(x, y) in rest {
            self.pointer(x, y, None)?;
        }
        let &(x, y) = points.last().unwrap();
        self.pointer(x, y, Some(false))
    }

    fn shot(&mut self, out: &Path) -> Result {
        let ppm = out.with_extension("ppm");
        let reply = self.call(&format!(
            r#"{{"execute":"screendump","arguments":{{"filename":"{}"}}}}"#,
            ppm.display()
        ))?;
        if reply.contains("\"error\"") {
            return Err(format!("screendump: {reply}"));
        }
        write_png(&ppm, out)?;
        if std::env::var_os("PINNACLE_KEEP_PPM").is_none() {
            let _ = std::fs::remove_file(&ppm);
        }
        println!("{}", out.display());
        Ok(())
    }
}

/// A QEMU started but not yet in a [`Session`]: ended when dropped.
struct Running(Option<std::process::Child>);

impl Drop for Running {
    fn drop(&mut self) {
        if let Some(mut child) = self.0.take() {
            let _ = child.kill();
            let _ = child.wait();
        }
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
        let _ = std::fs::remove_file(&self.socket);
    }
}

/// Where demos write their screenshots: `target/<name>`, or
/// `target/<name>-1280x800` on a screen set with `PINNACLE_SCREEN`.
/// Opens the preinstalled app titled `title` from the home screen and
/// photographs it, then turns the screen and photographs it again:
/// `target/app/<title>.png` and `<title>-turned.png` (`cargo xtask app
/// About`). For an app's look, without a whole demo.
fn app_shot(title: &str) -> Result {
    let dir = demo_dir("app")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", title)?;
    s.wait_for(&format!("display: {title} connected"))?;
    // Its first frame drawn and presented.
    std::thread::sleep(Duration::from_millis(1500));
    let name = title.to_lowercase();
    s.shot(&dir.join(format!("{name}.png")))?;
    s.turn()?;
    std::thread::sleep(Duration::from_millis(1500));
    s.shot(&dir.join(format!("{name}-turned.png")))?;
    Ok(())
}

/// Contacts in use, photographed into `target/demo-contacts/`: a contact
/// written with the on-screen keyboard and kept, a second one, the list,
/// an export, one removed and brought back by importing the export (the
/// other replaced, not doubled), and a search.
fn contacts_demo() -> Result {
    const P: &str = "contacts: control ";
    let dir = demo_dir("demo-contacts")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Contacts")?;
    s.wait_for("display: Contacts connected")?;
    s.find_named(&format!("{P}new"))?;
    s.shot(&dir.join("1-empty.png"))?;

    // Bo, the name tapped out on the on-screen keyboard, the rest typed.
    s.tap_named(P, "new")?;
    s.tap_named(P, "field Name")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("2-keyboard.png"))?;
    s.type_keys("Bo de Vries")?;
    s.tap_named(P, "field Phone 1")?;
    s.type_keys("+31 6 12345678")?;
    s.tap_named(P, "field E-mail 1")?;
    s.type_keys("bo@example.nl")?;
    s.tap_named(P, "field Birthday")?;
    s.type_keys("1985-04-12")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("3-editing.png"))?;
    s.tap_named(P, "save")?;
    s.wait_for("contacts: kept Bo de Vries")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("4-bo.png"))?;

    // Ada, and the list of both.
    s.tap_named(P, "back")?;
    s.tap_named(P, "new")?;
    s.tap_named(P, "field Name")?;
    s.type_keys("Ada Jansen")?;
    s.tap_named(P, "field Phone 1")?;
    s.type_keys("050 1234567")?;
    s.tap_named(P, "save")?;
    s.wait_for("contacts: kept Ada Jansen")?;
    s.tap_named(P, "back")?;
    s.tap_named(P, "export")?;
    s.wait_for("contacts: 2 contacts exported to contacts.vcf")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("5-exported.png"))?;

    // Bo removed (twice: the second press is the one that removes), then
    // brought back from the export; Ada is not doubled.
    s.tap_named(P, "contact Bo de Vries")?;
    s.tap_named(P, "remove")?;
    s.tap_named(P, "remove")?;
    s.wait_for("contacts: removed")?;
    s.tap_named(P, "import")?;
    s.wait_for("contacts: 2 contacts imported from contacts.vcf")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("6-imported.png"))?;

    // A search.
    s.tap_named(P, "search")?;
    s.type_keys("ada")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("7-search.png"))?;
    Ok(())
}

/// A picture to open in Files, as a PNG: a harbour at dusk, a sun low over
/// the water and a boat's sail, with a see-through border.
fn harbour_png() -> Vec<u8> {
    let (w, h) = (960u32, 640u32);
    let mut image = wil_core::Image::new(w, h);
    for (i, p) in image.pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
        let (x, y) = ((i as u32 % w) as i32, (i as u32 / w) as i32);
        let horizon = 400;
        let (dx, dy) = (x - 620, y - 330);
        let sail = (180..300).contains(&y) && x >= 300 && x - 300 < (y - 180) * 2 / 3;
        let hull =
            (300..330).contains(&y) && (260..420).contains(&x) && x - 260 > (y - 300) && 420 - x > (y - 300);
        let rgb = if hull {
            [60, 40, 35]
        } else if sail {
            [245, 240, 225]
        } else if dx * dx + dy * dy < 60 * 60 && y < horizon {
            [255, 214, 120]
        } else if y < horizon {
            // Sky: deep blue above, orange at the horizon.
            let t = y * 255 / horizon;
            [
                (40 + t * 200 / 255) as u8,
                (60 + t * 90 / 255) as u8,
                (120 - t * 60 / 255) as u8,
            ]
        } else {
            // Water, darker further down, the sun's path on it.
            let t = (y - horizon) * 255 / (h as i32 - horizon);
            let path = (x - 620).abs() < 40 - (y - horizon) / 8 && (y / 6) % 2 == 0;
            match path {
                true => [230, 170, 90],
                false => [
                    (30 - t * 20 / 255) as u8,
                    (70 - t * 40 / 255) as u8,
                    (110 - t * 50 / 255) as u8,
                ],
            }
        };
        let border = x < 16 || y < 16 || x >= w as i32 - 16 || y >= h as i32 - 16;
        p.copy_from_slice(&[rgb[0], rgb[1], rgb[2], if border { 0 } else { 255 }]);
    }
    wil_core::png::encode(&image, wil_core::deflate::Level::DEFAULT)
}

/// Files, used by tapping, photographed into `target/demo-files/`: two
/// notes written in Notes, found in its folder in Files, one opened and
/// moved to the person's own files, the other deleted; Notes then has one.
/// Then a picture and a file that is neither text nor a picture, fetched
/// in the Terminal, opened in Files: the one shown, the other said so.
/// Last a folder made, the picture moved into it, both renamed, and the
/// folder deleted with the picture in it.
fn files_demo() -> Result {
    const P: &str = "filer: button ";
    let dir = demo_dir("demo-files")?;
    let url = serve()?;
    disks(&url)?;
    std::fs::write(repository().join("harbour.png"), harbour_png()).map_err(|e| e.to_string())?;
    let odd: Vec<u8> = (0..4096u32)
        .map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8)
        .collect();
    std::fs::write(repository().join("readings.bin"), odd).map_err(|e| e.to_string())?;
    let mut s = Session::boot(&Guest::default(), "")?;
    let (w, _) = s.app();
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Notes")?;
    s.wait_for("display: Notes connected")?;
    s.tap_named("notes: button ", "new")?;
    s.wait_for("notes: new 1")?;
    s.type_keys("Shopping list\nbread, cheese and apples\nstamps for the post")?;
    s.wait_for("notes: saved 1")?;
    // On a phone the open note hides the list and its button.
    if !pinnacle_layout::notes::two_panes(w) {
        s.tap_named("notes: button ", "back")?;
    }
    s.tap_named("notes: button ", "new")?;
    s.wait_for("notes: new 2")?;
    s.type_keys("Call the plumber on Monday")?;
    s.wait_for("notes: saved 2")?;
    // Closed, so that it reads its folder afresh at the end.
    s.close()?;
    s.wait_for("display: closed Notes")?;
    s.wait_for(&home_apps(0))?;
    s.shot(&dir.join("1-home.png"))?;

    s.tap_named("launcher: tile ", "Files")?;
    s.wait_for("display: Files connected")?;
    s.find_named(&format!("{P}row Notes"))?;
    s.shot(&dir.join("2-files.png"))?;
    s.tap_named(P, "row Notes")?;
    s.wait_for("filer: opened folder")?;
    s.find_named(&format!("{P}row 1"))?;
    s.shot(&dir.join("3-notes-folder.png"))?;
    s.tap_named(P, "row 1")?;
    s.wait_for("filer: opened ")?;
    s.find_named(&format!("{P}move"))?;
    s.shot(&dir.join("4-opened.png"))?;

    // Moved to the person's own files: Move, back to the first page, Move here.
    s.tap_named(P, "move")?;
    s.find_named(&format!("{P}cancel-move"))?;
    s.tap_named(P, "back")?;
    s.find_named(&format!("{P}move-here"))?;
    s.shot(&dir.join("5-moving.png"))?;
    s.tap_named(P, "move-here")?;
    s.wait_for("filer: moved ")?;
    s.find_named(&format!("{P}row 1"))?;
    s.shot(&dir.join("6-moved.png"))?;

    // The other note deleted, the second tap the one that deletes.
    s.tap_named(P, "row Notes")?;
    s.find_named(&format!("{P}row 2"))?;
    s.tap_named(P, "row 2")?;
    s.find_named(&format!("{P}delete"))?;
    s.tap_named(P, "delete")?;
    s.find_named(&format!("{P}delete-for-good"))?;
    s.shot(&dir.join("7-delete.png"))?;
    s.tap_named(P, "delete-for-good")?;
    s.wait_for("filer: deleted ")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("8-deleted.png"))?;

    // Notes has neither now: one moved out of its folder, one deleted.
    s.home()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Notes")?;
    s.wait_for("notes: 0 notes")?;
    s.close()?;
    s.wait_for("display: closed Notes")?;

    // A picture and a file nothing opens, brought onto the device.
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Terminal")?;
    s.wait_for("display: Terminal connected")?;
    for name in ["harbour.png", "readings.bin"] {
        let line = format!("fetch {url}{name} {name}");
        s.type_keys(&format!("{line}\n"))?;
        s.wait_for(&format!("terminal: {line} ended"))?;
    }
    s.close()?;
    s.wait_for("display: closed Terminal")?;
    s.wait_for(&home_apps(0))?;
    // Files is still open at Notes' folder: back to the person's own files.
    s.tap_named("launcher: tile ", "Files")?;
    s.find_named(&format!("{P}back"))?;
    s.tap_named(P, "back")?;
    s.find_named(&format!("{P}row harbour.png"))?;
    s.tap_named(P, "row harbour.png")?;
    s.wait_for("filer: showing data:/harbour.png 960x640")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("9-picture.png"))?;
    if !pinnacle_layout::notes::two_panes(w) {
        s.tap_named(P, "close")?;
    }
    s.tap_named(P, "row readings.bin")?;
    s.wait_for("filer: opened data:/readings.bin")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("10-nothing-opens-it.png"))?;
    if !pinnacle_layout::notes::two_panes(w) {
        s.tap_named(P, "close")?;
    }

    // A folder of the person's own: made, the picture moved into it, the
    // folder and the picture renamed, and the folder deleted with it.
    s.tap_named(P, "new-folder")?;
    s.find_named(&format!("{P}name-done"))?;
    s.type_keys("Harbour trip\n")?;
    s.wait_for("filer: made folder data:/Harbour trip")?;
    s.find_named(&format!("{P}row Harbour trip"))?;
    s.shot(&dir.join("11-new-folder.png"))?;
    s.tap_named(P, "row harbour.png")?;
    s.find_named(&format!("{P}move"))?;
    s.tap_named(P, "move")?;
    s.tap_named(P, "row Harbour trip")?;
    s.wait_for("filer: opened folder data:/Harbour trip")?;
    s.tap_named(P, "move-here")?;
    s.wait_for("filer: moved ")?;
    s.tap_named(P, "rename-folder")?;
    s.find_named(&format!("{P}name-done"))?;
    s.press_keys(&[&["ctrl", "a"]])?;
    s.type_keys("Harbour 2026\n")?;
    s.wait_for("filer: renamed folder data:/Harbour trip to data:/Harbour 2026")?;
    s.tap_named(P, "row harbour.png")?;
    s.find_named(&format!("{P}rename"))?;
    s.tap_named(P, "rename")?;
    s.find_named(&format!("{P}name-done"))?;
    s.press_keys(&[&["ctrl", "a"]])?;
    s.type_keys("boats.png\n")?;
    s.wait_for("filer: renamed data:/Harbour 2026/harbour.png to data:/Harbour 2026/boats.png")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("12-renamed.png"))?;
    if !pinnacle_layout::notes::two_panes(w) {
        s.tap_named(P, "close")?;
    }
    s.tap_named(P, "delete-folder")?;
    s.find_named(&format!("{P}delete-folder-for-good"))?;
    s.shot(&dir.join("13-delete-folder.png"))?;
    s.tap_named(P, "delete-folder-for-good")?;
    s.wait_for("filer: deleted folder data:/Harbour 2026")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("14-folder-deleted.png"))?;
    Ok(())
}

/// Texting someone with no Pinnacle, photographed into `target/demo-sms/`:
/// Cas is saved in Contacts with only a phone number, Messages texts Cas
/// over the simulated cell network and Cas's ordinary phone answers; then,
/// with Messages closed, a number in no contact texts, which shows as a
/// notification and as a conversation of its own.
fn sms_demo() -> Result {
    const P: &str = "contacts: control ";
    let dir = demo_dir("demo-sms")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Contacts")?;
    s.wait_for("display: Contacts connected")?;
    s.tap_named(P, "new")?;
    s.tap_named(P, "field Name")?;
    s.type_keys("Cas Bakker")?;
    s.tap_named(P, "field Phone 1")?;
    s.type_keys("06 2000 0001")?;
    s.tap_named(P, "save")?;
    s.wait_for("contacts: kept Cas Bakker")?;
    s.close()?;
    s.wait_for("display: closed Contacts")?;

    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Messages")?;
    s.wait_for("display: Messages connected")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("1-cas-by-sms.png"))?;
    s.tap_named("messages: button ", "contact-0")?;
    s.wait_for("messages: opened Cas Bakker")?;
    s.type_keys("Are you coming to dinner tonight?\n")?;
    s.wait_for("phone: texted 06 2000 0001")?;
    s.wait_for("messages: a text from +31620000001")?;
    s.type_keys("Great, see you at seven\n")?;
    s.wait_for("messages: texted 06 2000 0001")?;
    s.wait_for("messages: a text from +31620000001")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("2-texting-cas.png"))?;

    // Closed, so a text that comes is a notification.
    s.close()?;
    s.wait_for("display: closed Messages")?;
    s.wait_for(&home_apps(0))?;
    cell().text_guest(
        PARCELS,
        0,
        "Your parcel arrives tomorrow between 10:00 and 12:00.",
    )?;
    s.wait_for("phone: a text from +3197010203040")?;
    std::thread::sleep(Duration::from_millis(500));
    s.shot(&dir.join("3-a-text-comes.png"))?;

    // Both conversations, read back from the phone service.
    std::thread::sleep(Duration::from_secs(4));
    s.tap_named("launcher: tile ", "Messages")?;
    s.wait_for("display: Messages connected")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("4-both-conversations.png"))?;
    s.tap_named("messages: button ", "contact-0")?;
    s.wait_for("messages: opened Cas Bakker")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("5-cas-again.png"))?;
    Ok(())
}

/// Joining a Wi-Fi network in Settings, photographed into
/// `target/demo-wifi/`: the networks nearby with their signal, a wrong
/// password refused, the right one let on and the network kept; then the
/// network out of reach and back, and joined again by itself.
fn wifi_demo() -> Result {
    const P: &str = "settings: button ";
    let dir = demo_dir("demo-wifi")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Settings")?;
    s.wait_for("display: Settings connected")?;
    // The network page, whose Wi-Fi section opens Wi-Fi's own.
    s.tap_named(P, "network")?;
    s.wait_for("settings: network")?;
    s.shot(&dir.join("1-network.png"))?;
    s.tap_named(P, "wifi")?;
    s.wait_for("wifi: 4 networks nearby")?;
    s.shot(&dir.join("2-nearby.png"))?;
    // The strongest, the home network: a password wanted.
    s.tap_named(P, "wifi-join-0")?;
    s.type_keys("guess guess 1")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("3-password.png"))?;
    s.type_keys("\n")?;
    s.wait_for(&format!("wifi: could not join {}: Wrong password", WIFI_HOME.0))?;
    s.shot(&dir.join("4-wrong-password.png"))?;
    s.tap_named(P, "wifi-join-0")?;
    s.type_keys(&format!("{}\n", WIFI_HOME.1))?;
    s.wait_for(&format!("wifi: joined {}", WIFI_HOME.0))?;
    s.shot(&dir.join("5-joined.png"))?;
    // Out of reach, and back: joined again with the password kept.
    wifi_air().set_in_reach(WIFI_HOME.0, false);
    s.wait_for(&format!("wifi: lost {}", WIFI_HOME.0))?;
    s.wait_for("wifi: 3 networks nearby")?;
    s.shot(&dir.join("6-out-of-reach.png"))?;
    wifi_air().set_in_reach(WIFI_HOME.0, true);
    s.tap_named(P, "wifi-scan")?;
    s.wait_for(&format!("wifi: joining {} again", WIFI_HOME.0))?;
    s.wait_for(&format!("wifi: joined {}", WIFI_HOME.0))?;
    s.shot(&dir.join("7-joined-again.png"))?;
    Ok(())
}

/// Past notifications, photographed into `target/demo-notices/`: two texts
/// come while the person is on the home screen, their banners go, and the
/// status bar's button says two came; its list shows both, the newest
/// first, and a tap on one opens Messages. Opened again, the count is gone
/// and the list still holds them. A third comes, the device is reset as a
/// flat battery would leave it, and once unlocked the bell lists all three,
/// one unseen. Clear empties it.
fn notices_demo() -> Result {
    use pinnacle_layout::shell;
    let dir = demo_dir("demo-notices")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    cell().text_guest(
        PARCELS,
        0,
        "Your parcel arrives tomorrow between 10:00 and 12:00.",
    )?;
    s.wait_for("display: notice from messages")?;
    std::thread::sleep(Duration::from_millis(500));
    s.shot(&dir.join("1-a-banner.png"))?;
    cell().text_guest(FRIEND, 0, "Are we still on for Saturday?")?;
    s.wait_for("display: notice from messages")?;
    // Both banners gone: only the status bar's button says they came.
    std::thread::sleep(Duration::from_millis(5_000));
    s.shot(&dir.join("2-banners-gone.png"))?;

    let (x, y) = pinnacle_layout::center(shell::notices(s.screen.0));
    s.tap(x, y)?;
    s.wait_for("display: listed 2 notices")?;
    std::thread::sleep(Duration::from_millis(300));
    s.shot(&dir.join("3-the-list.png"))?;
    // The older one, the parcel service's, second in the list.
    s.tap_named("display: button ", "notice-1")?;
    s.wait_for("display: opening messages from the list")?;
    s.wait_for("display: Messages connected")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("4-opened-from-the-list.png"))?;

    s.home()?;
    s.wait_for(&home_apps(0))?;
    s.tap(x, y)?;
    s.wait_for("display: listed 2 notices")?;
    std::thread::sleep(Duration::from_millis(300));
    s.shot(&dir.join("5-seen-still-listed.png"))?;
    s.tap(x, y)?;
    std::thread::sleep(Duration::from_millis(300));

    // A third, not seen; then the power goes (a hardware reset, nothing
    // shut down) and the device starts again. Once its data is unlocked the
    // bell has all three, the new one unseen.
    cell().text_guest(FRIEND, 0, "I'll bring the cake.")?;
    s.wait_for("display: notice from messages")?;
    std::thread::sleep(Duration::from_millis(300));
    s.call(r#"{"execute":"system_reset"}"#)?;
    s.wait_for("display: your data is locked")?;
    s.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
    s.wait_for("display: data opened")?;
    s.wait_for("display: 3 notices kept from before, 1 unseen")?;
    s.wait_for(&home_apps(0))?;
    std::thread::sleep(Duration::from_millis(500));
    s.shot(&dir.join("6-after-a-restart.png"))?;
    s.tap(x, y)?;
    s.wait_for("display: listed 3 notices")?;
    std::thread::sleep(Duration::from_millis(300));
    s.shot(&dir.join("7-the-list-after-a-restart.png"))?;

    s.tap_named("display: button ", "clear")?;
    s.wait_for("display: notices cleared")?;
    std::thread::sleep(Duration::from_millis(300));
    s.shot(&dir.join("8-cleared.png"))?;
    s.home()?;
    s.wait_for(&home_apps(0))?;
    Ok(())
}

/// Fien, the code editor: its Rust example opened, a name changed at two
/// places with two cursors (ctrl+D twice), a line added, saved; then the
/// list of its files and the Frits example. A screenshot a step.
fn fien_demo() -> Result {
    const P: &str = "fien: button ";
    let dir = demo_dir("demo-fien")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Fien")?;
    s.wait_for("display: Fien connected")?;
    s.wait_for("fien: opened main.rs")?;
    s.find_named(&format!("{P}fien-text"))?;
    s.shot(&dir.join("1-opened.png"))?;

    // The text takes the keys; the first physical one sends the on-screen
    // keyboard away. To line 5's `name`, then it and its other use.
    s.tap_named(P, "fien-text")?;
    s.key_chord(&["ctrl", "home"])?;
    for _ in 0..4 {
        s.key_chord(&["down"])?;
    }
    s.key_chord(&["home"])?;
    for _ in 0..5 {
        s.key_chord(&["right"])?;
    }
    s.key_chord(&["ctrl", "d"])?;
    s.key_chord(&["ctrl", "d"])?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("2-two-selections.png"))?;
    s.type_keys("person")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("3-renamed.png"))?;

    // A line at the top of the loop: Enter after `{` indents a level in.
    s.key_chord(&["esc"])?;
    s.key_chord(&["up"])?;
    s.key_chord(&["end"])?;
    s.type_keys("\nlet count = names.len();")?;
    s.key_chord(&["ctrl", "s"])?;
    s.wait_for("fien: saved main.rs")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("4-saved.png"))?;

    // The bar is at the top, where `tap_named` would drag it into view.
    let files = s.find_named(&format!("{P}fien-files"))?;
    s.tap_app(files)?;
    s.find_named(&format!("{P}file hello.frits"))?;
    s.shot(&dir.join("5-files.png"))?;
    s.tap_named(P, "file hello.frits")?;
    s.wait_for("fien: opened hello.frits")?;
    s.wait_for("fien: 0 problems")?;
    s.find_named(&format!("{P}fien-text"))?;
    s.shot(&dir.join("6-frits.png"))?;

    // A line after `Console.print`: the names Console has, offered as it
    // is typed; then a call to one it has not, which the check marks.
    s.tap_named(P, "fien-text")?;
    s.key_chord(&["ctrl", "home"])?;
    for _ in 0..7 {
        s.key_chord(&["down"])?;
    }
    s.key_chord(&["end"])?;
    s.type_keys("\nConsole.p")?;
    // The list is drawn into the page it is on, which announces nothing new.
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("7-completions.png"))?;
    s.key_chord(&["esc"])?;
    s.type_keys("out(who)")?;
    s.wait_for("fien: 1 problems")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("8-a-problem.png"))?;

    // A line longer than the screen is wide wraps after a space.
    s.key_chord(&["ctrl", "end"])?;
    s.type_keys(
        "\n// A comment long enough to wrap onto a second row on a phone, after the last space that fits.",
    )?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("9-wrapped.png"))?;

    // Files opens a text file in Fien: Edit.
    s.home()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Files")?;
    s.wait_for("display: Files connected")?;
    s.tap_named("filer: button ", "row Fien")?;
    s.wait_for("filer: opened folder")?;
    s.tap_named("filer: button ", "row main.rs")?;
    s.wait_for("filer: opened ")?;
    s.tap_named("filer: button ", "edit")?;
    s.wait_for("filer: editing ")?;
    s.wait_for("fien: opened main.rs")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("10-from-files.png"))?;
    Ok(())
}

/// Two devices editing one text: Bo offers Ada his device's services, Ada
/// shares `main.rs` from Fien, Bo's Fien opens it, and both type at once:
/// each sees the other's line and cursor.
fn fien_pair_demo() -> Result {
    const P: &str = "fien: button ";
    let dir = demo_dir("demo-fien-pair")?;
    let (mut a, mut b) = two_devices("fien", None)?;
    a.wait_for("launcher: ")?;
    b.wait_for("launcher: ")?;

    b.tap_named("launcher: tile ", "Settings")?;
    b.wait_for("display: Settings connected")?;
    b.tap_named("settings: button ", "remote")?;
    b.wait_for("settings: remote access")?;
    std::thread::sleep(Duration::from_millis(600));
    b.tap_named("settings: button ", "offer-0")?;
    b.wait_for("settings: Ada may use this device's services")?;
    b.home()?;
    b.wait_for("launcher: ")?;
    b.tap_named("launcher: tile ", "Fien")?;
    b.wait_for("fien: opened main.rs")?;

    a.tap_named("launcher: tile ", "Fien")?;
    a.wait_for("fien: opened main.rs")?;
    let share = a.find_named(&format!("{P}fien-share"))?;
    a.tap_app(share)?;
    a.find_named(&format!("{P}contact Bo"))?;
    std::thread::sleep(Duration::from_millis(400));
    a.shot(&dir.join("1-share-with.png"))?;
    a.tap_named(P, "contact Bo")?;
    a.wait_for("fien: shared main.rs with Bo")?;
    b.wait_for("fien: joined main.rs from ")?;

    // Each types in a place of their own, at the same time.
    a.tap_named(P, "fien-text")?;
    a.key_chord(&["ctrl", "end"])?;
    b.tap_named(P, "fien-text")?;
    b.key_chord(&["ctrl", "home"])?;
    a.type_keys("// Ada was here\n")?;
    b.type_keys("// Bo too\n")?;
    std::thread::sleep(Duration::from_millis(1500));
    a.shot(&dir.join("2-ada.png"))?;
    b.shot(&dir.join("3-bo.png"))?;
    Ok(())
}

/// Kees, mail and calendar, against a provider on this machine
/// ([`kees_provider`]): signed in with its servers given, the inbox, an
/// invite accepted, the week with it, a message written with an address
/// completed from the contacts, sent. A screenshot a step, in
/// `target/demo-kees/`.
fn kees_demo() -> Result {
    const P: &str = "kees: control ";
    let dir = demo_dir("demo-kees")?;
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| e.to_string())?
        .as_secs() as i64;
    let (imap, smtp, http, sent) = kees_provider(now)?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Kees")?;
    s.wait_for("display: Kees connected")?;
    s.wait_for("kees: started")?;
    s.find_named(&format!("{P}sign in"))?;
    s.shot(&dir.join("1-sign-in.png"))?;

    // A field typed into on the physical keyboard; a filled one emptied first.
    let fill = |s: &mut Session, field: &str, text: &str| -> Result {
        s.tap_named(P, field)?;
        s.key_chord(&["end"])?;
        s.key_chord(&["shift", "home"])?;
        s.type_keys(text)
    };
    fill(&mut s, "field Your name", "Kees Jansen")?;
    fill(&mut s, "field E-mail address", "kees@example.nl")?;
    fill(&mut s, "field Password", "geheim")?;
    s.tap_named(P, "servers")?;
    s.find_named(&format!("{P}field Mail server (IMAP)"))?;
    fill(&mut s, "field Mail server (IMAP)", &format!("10.0.2.2:{imap}"))?;
    fill(&mut s, "field Sending server (SMTP)", &format!("10.0.2.2:{smtp}"))?;
    fill(
        &mut s,
        "field Calendars (CalDAV)",
        &format!("http://10.0.2.2:{http}/.well-known/caldav"),
    )?;
    fill(
        &mut s,
        "field Contacts (CardDAV)",
        &format!("http://10.0.2.2:{http}/.well-known/carddav"),
    )?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("2-servers.png"))?;
    s.tap_named(P, "sign in")?;
    s.wait_for("kees: signed in as kees@example.nl")?;
    s.wait_for("kees: synced")?;
    s.find_named(&format!("{P}mail Uitnodiging: Verjaardag Anna"))?;
    s.shot(&dir.join("3-inbox.png"))?;

    s.tap_named(P, "mail Uitnodiging: Verjaardag Anna")?;
    s.wait_for("kees: opened")?;
    s.find_named(&format!("{P}accept"))?;
    s.shot(&dir.join("4-invite.png"))?;
    s.tap_named(P, "accept")?;
    s.wait_for("kees: You accepted Verjaardag Anna")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("5-accepted.png"))?;

    s.tap_named(P, "tab calendar")?;
    s.find_named(&format!("{P}event Verjaardag Anna"))?;
    s.shot(&dir.join("6-week.png"))?;
    s.tap_named(P, "event Verjaardag Anna")?;
    s.find_named(&format!("{P}edit"))?;
    s.shot(&dir.join("7-event.png"))?;

    s.tap_named(P, "tab mail")?;
    s.tap_named(P, "write")?;
    s.tap_named(P, "field To")?;
    s.type_keys("bob")?;
    s.tap_named(P, "suggest bob@example.org")?;
    fill(&mut s, "field Subject", "Zaterdag")?;
    s.tap_named(P, "field Message")?;
    s.type_keys("Hoi Bob, ga je ook naar Anna? Dan fietsen we samen.")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("8-writing.png"))?;
    s.tap_named(P, "send")?;
    s.wait_for("kees: Sent")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("9-sent.png"))?;
    // The answer to Anna and the message to Bob.
    let n = sent.load(std::sync::atomic::Ordering::SeqCst);
    if n != 2 {
        return Err(format!("the provider was sent {n} messages, not 2"));
    }
    println!("kees-demo: {} screenshots in {}", 9, dir.display());
    Ok(())
}

/// Kees's demo provider (`kees_core::demo`, a lived-in account) served on
/// this machine: IMAP, SMTP and HTTP (CalDAV and CardDAV) on ports of
/// their own, unencrypted, which Kees allows only to a private address
/// (the guest reaches them at 10.0.2.2). Returns the ports, and how many
/// messages it was sent.
fn kees_provider(now: i64) -> Result<(u16, u16, u16, std::sync::Arc<std::sync::atomic::AtomicUsize>)> {
    use kees_core::demo;
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    let bind = || TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string());
    let (imap, smtp, http) = (bind()?, bind()?, bind()?);
    let port = |l: &TcpListener| l.local_addr().map(|a| a.port()).map_err(|e| e.to_string());
    let ports = (port(&imap)?, port(&smtp)?, port(&http)?);
    let sent = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let counted = sent.clone();
    enum Conn {
        Imap(TcpStream, demo::Imap),
        Smtp(TcpStream, demo::Smtp),
        Http(TcpStream, Vec<u8>),
    }
    /// What a connection has to read (None: it closed).
    fn read(c: &mut TcpStream) -> Option<Vec<u8>> {
        let mut b = [0u8; 65536];
        match c.read(&mut b) {
            Ok(0) => None,
            Ok(n) => Some(b[..n].to_vec()),
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => Some(Vec::new()),
            Err(_) => None,
        }
    }
    fn write(c: &mut TcpStream, bytes: &[u8]) -> bool {
        bytes.is_empty()
            || (c.set_nonblocking(false).is_ok()
                && c.write_all(bytes).is_ok()
                && c.set_nonblocking(true).is_ok())
    }
    /// A whole HTTP request answered, when it has all come.
    fn answer(world: &demo::Shared, http: u16, got: &[u8]) -> Option<Vec<u8>> {
        let end = got.windows(4).position(|w| w == b"\r\n\r\n")?;
        let head = String::from_utf8_lossy(&got[..end]).into_owned();
        let mut lines = head.lines();
        let mut first = lines.next()?.split_whitespace();
        let (method, path) = (first.next()?, first.next()?);
        let headers: Vec<(String, String)> = lines
            .filter_map(|l| {
                l.split_once(':')
                    .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
            })
            .collect();
        let header = |n: &str| {
            headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case(n))
                .map(|(_, v)| v.as_str())
        };
        let length: usize = header("content-length").and_then(|l| l.parse().ok()).unwrap_or(0);
        let body = got.get(end + 4..end + 4 + length)?;
        let method: &'static str = match method {
            "PROPFIND" => "PROPFIND",
            "REPORT" => "REPORT",
            "PUT" => "PUT",
            "DELETE" => "DELETE",
            _ => "GET",
        };
        let mut kept = Vec::new();
        for name in ["Depth", "Content-Type", "If-Match", "If-None-Match"] {
            if let Some(v) = header(name) {
                kept.push((name, v.to_string()));
            }
        }
        let request = kees_core::dav::Request {
            method,
            url: format!("http://10.0.2.2:{http}{path}"),
            headers: kept,
            body: String::from_utf8_lossy(body).into_owned(),
        };
        let a = demo::dav(
            &mut world.borrow_mut(),
            &request,
            header("authorization").unwrap_or(""),
        );
        let mut out = format!(
            "HTTP/1.1 {} Kees\r\nContent-Length: {}\r\nConnection: close\r\n",
            a.status,
            a.body.len()
        );
        for (k, v) in &a.headers {
            out.push_str(&format!("{k}: {v}\r\n"));
        }
        out.push_str("\r\n");
        let mut out = out.into_bytes();
        out.extend_from_slice(&a.body);
        Some(out)
    }
    std::thread::spawn(move || {
        let world: demo::Shared = std::rc::Rc::new(std::cell::RefCell::new(demo::World::sample(now)));
        for l in [&imap, &smtp, &http] {
            let _ = l.set_nonblocking(true);
        }
        let mut conns: Vec<Conn> = Vec::new();
        loop {
            for (i, l) in [&imap, &smtp, &http].into_iter().enumerate() {
                while let Ok((c, _)) = l.accept() {
                    let _ = c.set_nonblocking(true);
                    conns.push(match i {
                        0 => Conn::Imap(c, demo::Imap::new(&world)),
                        1 => Conn::Smtp(c, demo::Smtp::new(&world)),
                        _ => Conn::Http(c, Vec::new()),
                    });
                }
            }
            conns.retain_mut(|c| match c {
                Conn::Imap(s, p) => {
                    let out = p.output();
                    write(s, &out) && read(s).inspect(|b| p.input(b)).is_some()
                }
                Conn::Smtp(s, p) => {
                    let out = p.output();
                    write(s, &out) && read(s).inspect(|b| p.input(b)).is_some()
                }
                Conn::Http(s, got) => match read(s) {
                    Some(b) => {
                        got.extend_from_slice(&b);
                        match answer(&world, ports.2, got) {
                            Some(reply) => {
                                write(s, &reply);
                                false
                            }
                            None => true,
                        }
                    }
                    None => false,
                },
            });
            counted.store(world.borrow().sent.len(), std::sync::atomic::Ordering::SeqCst);
            std::thread::sleep(Duration::from_millis(5));
        }
    });
    Ok((ports.0, ports.1, ports.2, sent))
}

fn demo_dir(name: &str) -> Result<PathBuf> {
    let dir = match std::env::var("PINNACLE_SCREEN") {
        Ok(size) => root().join(format!("target/{name}-{size}")),
        Err(_) => root().join(format!("target/{name}")),
    };
    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
    Ok(dir)
}

/// The terminal in use, photographed into `target/demo-terminal/`: opened
/// from its tile, `help`, then commands that send records (`info`,
/// `devices`, `echo`), a plain std program whose `println!`s become lines
/// (`std-check`), and one that does not exist.
fn pc_demo() -> Result {
    let dir = demo_dir("demo-pc")?;
    let elf = pc_build()?;
    let wav = root().join("target/demo-pc.wav");
    let mut s = Session::attach(qemu_pc(&elf, "", &wav)?, "[pc] ", true, || Ok(()))?;
    s.wait_for(&home_apps(0))?;
    s.shot(&dir.join("1-home.png"))?;
    for (i, app) in ["Clock", "Notes", "About"].into_iter().enumerate() {
        s.tap_named("launcher: tile ", app)?;
        s.wait_for(&format!("display: {app} connected"))?;
        s.shot(&dir.join(format!("{}-{}.png", i + 2, app.to_lowercase())))?;
        s.home()?;
        s.wait_for(&home_apps(0))?;
    }
    s.tap_named("launcher: tile ", "Store")?;
    s.wait_for("display: Store connected")?;
    s.tap_named("store: button ", "offer-0")?;
    s.wait_for("store: Calculator is installed")?;
    s.home()?;
    s.wait_for(&home_apps(1))?;
    s.tap_named("launcher: tile ", "Calculator")?;
    s.wait_for("display: Calculator connected")?;
    s.shot(&dir.join("5-calculator-from-the-store.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// Updates by themselves: Calculator installed from the Store, then a new
/// version of it published; Settings → Updates looks and tells, then, set
/// to install by themselves, looks and brings Calculator up to date.
fn updates_demo() -> Result {
    const BUTTON: &str = "settings: button ";
    let dir = demo_dir("demo-updates")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Store")?;
    s.wait_for("display: Store connected")?;
    s.tap_named("store: button ", "offer-0")?;
    s.wait_for("store: Calculator is installed")?;
    // The Store draws what it installed before a press reaches home.
    std::thread::sleep(Duration::from_millis(800));
    s.home()?;
    s.wait_for(&home_apps(1))?;

    // A new version of Calculator in the package source: the same program,
    // a new manifest.
    let (name, title, description) = PACKAGES[0];
    let repository = repository();
    let secret = publisher_key()?;
    let catalog = std::fs::read_to_string(repository.join("catalog")).map_err(|e| e.to_string())?;
    let new = manifest(name, title, description)
        .replace(&format!("version={}", env!("CARGO_PKG_VERSION")), "version=2");
    let line = write_package(
        &repository,
        name,
        &new,
        &[("program".to_string(), Arch::Arm.program(name)?)],
        Some(&secret),
    )?;
    let catalog: String = catalog
        .lines()
        .map(|l| {
            if l.starts_with(&format!("{name}|")) {
                line.clone()
            } else {
                format!("{l}\n")
            }
        })
        .collect();
    std::fs::write(repository.join("catalog"), catalog).map_err(|e| e.to_string())?;

    s.tap_named("launcher: tile ", "Settings")?;
    s.wait_for("display: Settings connected")?;
    s.tap_named(BUTTON, "updates")?;
    s.wait_for("settings: updates")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("1-told-by-default.png"))?;
    s.tap_named(BUTTON, "updates-now")?;
    s.wait_for("settings: updates looked: Calculator in the Store")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("2-calculator-can-be-updated.png"))?;

    s.tap_named(BUTTON, "updates-install")?;
    s.wait_for("settings: updates Install")?;
    s.tap_named(BUTTON, "updates-now")?;
    s.wait_for("updates: calculator updated to 2")?;
    s.wait_for("display: notice from store: Apps updated")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("3-updated-by-itself.png"))?;

    s.home()?;
    s.wait_for(&home_apps(1))?;
    // Still running since Calculator was installed: brought to the front,
    // where it reads the catalogs again.
    s.tap_named("launcher: tile ", "Store")?;
    s.wait_for("store: button offer-0")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("4-store-has-version-2.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// A system update: the system as built here (version n) finds n+1 in the
/// package source, fetches it by itself and starts it at a restart; then
/// n+2, whose kernel never starts, is fetched and tried, the machine is
/// switched off and on, and n+1 runs again, saying so. On disks of its own,
/// kept between QEMU's runs as a device's are.
fn system_update_demo(pc: bool) -> Result {
    const BUTTON: &str = "settings: button ";
    let dir = demo_dir(if pc {
        "demo-system-update-pc"
    } else {
        "demo-system-update"
    })?;
    let now: u64 = version().parse().unwrap_or(0);
    let (up, bad) = ((now + 1).to_string(), (now + 2).to_string());
    let (board, arch) = if pc {
        ("pc", Arch::Pc)
    } else {
        ("qemu-virt", Arch::Arm)
    };
    // The package source the guest's Store and updates read: a PC's in `pc/`.
    let source = repository().join(arch.store_path());
    // The disks first (they make the package source afresh), then the
    // newer system into it, then the kernel that runs: building the newer
    // one leaves its own in the build's place.
    if pc {
        disks_for(Arch::Pc, &pc_system(), &serve()?, &[], 64)?;
    } else {
        disks(&serve()?)?;
    }
    let secret = publisher_key()?;
    let line = package_system(&source, board, &up, Some(&secret))?;
    print!("offered: {}system/{board}/{line}", arch.store_path());
    let kernel = if pc { pc_kernel()? } else { image("qemu-virt")? };
    let guest = Guest {
        system: root().join("target/update-system.img"),
        data: Some(root().join("target/update-data.img")),
        ..Guest::default()
    };
    if pc {
        // Its disks where `qemu_pc_machine` takes them, the data blank.
        let _ = std::fs::remove_file(root().join("target/data-pc.img"));
    } else {
        std::fs::copy(root().join("target/system.img"), &guest.system).map_err(|e| e.to_string())?;
        let _ = std::fs::remove_file(guest.data.as_ref().unwrap());
    }
    let wav = root().join("target/update-pc.wav");
    let boot = |blank: bool| {
        let qemu = if pc {
            // Room for the kernel it runs and the one it reads to hand over to.
            let mut qemu = qemu_pc_machine_with(&wav, true)?;
            qemu.arg("-kernel").arg(&kernel).args(["-append", "", "-m", "1G"]);
            qemu
        } else {
            qemu_guest("virt", &Load::Image(kernel.clone(), ""), false, &guest)
        };
        Session::attach(qemu, if pc { "[pc] " } else { "" }, blank, || Ok(()))
    };
    let settings_updates = |s: &mut Session| -> Result {
        s.tap_named("launcher: tile ", "Settings")?;
        s.wait_for("display: Settings connected")?;
        s.tap_named(BUTTON, "updates")?;
        s.wait_for("settings: updates")?;
        std::thread::sleep(Duration::from_millis(400));
        Ok(())
    };
    // Once the password screen shows (`display: your data is locked`, waited
    // for by the caller, before or after the line it comes with).
    let unlock = |s: &mut Session| -> Result {
        s.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
        s.wait_for("display: data opened")?;
        s.wait_for(&home_apps(0))
    };

    let mut s = boot(true)?;
    s.wait_for(&home_apps(0))?;
    settings_updates(&mut s)?;
    s.shot(&dir.join("1-as-it-came.png"))?;
    s.tap_named(BUTTON, "updates-install")?;
    s.wait_for("settings: updates Install")?;
    s.tap_named(BUTTON, "updates-now")?;
    s.wait_for(&format!("updates: system {up} ready in slot a"))?;
    s.wait_for("settings: updates looked:")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("2-ready-for-a-restart.png"))?;

    s.tap_named(BUTTON, "system-restart")?;
    s.wait_for(&format!("system: handing over to version {up} in slot a"))?;
    s.wait_for(&format!("system: version {up}, handed over to from slot a"))?;
    s.wait_for(&format!("display: system version {up} started well"))?;
    // The home screen, and the files of the system that now runs put in
    // their places: either may come first.
    s.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
    s.wait_for("display: data opened")?;
    let home = home_apps(0);
    let mut waiting = vec![home.as_str(), "updates: the system's files in their places"];
    while !waiting.is_empty() {
        let line = s.wait_any(&waiting, boot_timeout())?;
        waiting.retain(|p| !line.starts_with(p));
    }
    settings_updates(&mut s)?;
    s.shot(&dir.join("3-updated.png"))?;

    // A system whose kernel never starts: its first instruction a branch
    // to itself, behind a boot image's header, or as a PC's ELF.
    let broken = if pc {
        hanging_elf()
    } else {
        let mut broken = std::fs::read(&kernel).map_err(|e| e.to_string())?[..64].to_vec();
        broken[..4].copy_from_slice(&0x1400_0000u32.to_le_bytes());
        broken
    };
    let line = package_system_with(&source, board, &bad, broken, Some(&secret))?;
    print!("offered: {}system/{board}/{line}", arch.store_path());
    s.tap_named(BUTTON, "updates-now")?;
    s.wait_for(&format!("updates: system {bad} ready in slot b"))?;
    s.wait_for("settings: updates looked:")?;
    s.tap_named(BUTTON, "system-restart")?;
    s.wait_for(&format!("system: handing over to version {bad} in slot b"))?;
    // It hangs: nothing more comes. Switched off and on, as a person would.
    std::thread::sleep(Duration::from_secs(10));
    drop(s);
    let mut s = boot(false)?;
    s.wait_for("system: slot b's system did not start")?;
    s.wait_for(&format!("system: version {up}, handed over to from slot a"))?;
    s.wait_for("display: your data is locked")?;
    unlock(&mut s)?;
    settings_updates(&mut s)?;
    s.tap_named(BUTTON, "updates-now")?;
    s.wait_for(&format!("updates: system {bad} did not start"))?;
    s.wait_for("settings: updates looked:")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("4-the-broken-one-did-not-start.png"))?;
    println!("{}", dir.display());
    if pc {
        // Its vault was kept from run to run: the PC's other runs find
        // their data disk blank, as before.
        drop(s);
        let _ = std::fs::remove_file(root().join("target/data-pc.img"));
    }
    Ok(())
}

/// A PC kernel that never starts: an ELF whose one segment, at 2 MiB, is
/// its entry and a jump to itself (`jmp $`).
fn hanging_elf() -> Vec<u8> {
    const AT: u64 = 0x20_0000;
    let mut elf = vec![0u8; 64 + 56];
    elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
    elf[16..18].copy_from_slice(&2u16.to_le_bytes()); // an executable
    elf[18..20].copy_from_slice(&62u16.to_le_bytes()); // x86-64
    elf[20..24].copy_from_slice(&1u32.to_le_bytes());
    elf[24..32].copy_from_slice(&AT.to_le_bytes());
    elf[32..40].copy_from_slice(&64u64.to_le_bytes()); // program headers
    elf[52..54].copy_from_slice(&64u16.to_le_bytes());
    elf[54..56].copy_from_slice(&56u16.to_le_bytes());
    elf[56..58].copy_from_slice(&1u16.to_le_bytes());
    let header = &mut elf[64..];
    header[..4].copy_from_slice(&1u32.to_le_bytes()); // PT_LOAD
    header[4..8].copy_from_slice(&5u32.to_le_bytes()); // read, execute
    header[8..16].copy_from_slice(&120u64.to_le_bytes());
    header[16..24].copy_from_slice(&AT.to_le_bytes());
    header[24..32].copy_from_slice(&AT.to_le_bytes());
    header[32..40].copy_from_slice(&2u64.to_le_bytes());
    header[40..48].copy_from_slice(&2u64.to_le_bytes());
    elf.extend_from_slice(&[0xeb, 0xfe]);
    elf
}

/// The time from the network, a time zone and keyboard layouts: an NTS
/// server stands in on the host (a summer's day, not the host's clock), and
/// before each of its answers someone on the path sends one of their own,
/// a year back; the clock is set from the true one, and the forged one is
/// refused. Settings → Date and time shows it in UTC, Amsterdam is chosen
/// (summer time: two hours ahead), the Clock shows it; then US-International
/// and Dutch are chosen in Settings → Keyboard and a note typed with each,
/// its accents by dead keys.
fn time_demo() -> Result {
    const BUTTON: &str = "settings: button ";
    // Wednesday 15 July 2026, 10:00:00 UTC.
    const SUMMER: u64 = 1_784_109_600;
    let dir = demo_dir("demo-time")?;
    let started = Instant::now();
    let (ke_port, trusted) = nts_stand_in(move || SUMMER + started.elapsed().as_secs())?;
    let mut roots =
        std::fs::read(root().join("certificates/mozilla-roots.pem")).map_err(|e| format!("roots: {e}"))?;
    roots.extend_from_slice(pinnacle_tls::pem::certificate(&trusted).as_bytes());
    disks_at(
        &root().join("target/system.img"),
        &serve()?,
        &[
            (
                "/settings/time-server".into(),
                format!("10.0.2.2:{ke_port}").into_bytes(),
            ),
            ("/certificates/roots.pem".into(), roots),
        ],
    )?;
    let mut s = Session::boot(&Guest::default(), "")?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Settings")?;
    s.wait_for("display: Settings connected")?;
    s.tap_named(BUTTON, "date-time")?;
    // Set from the stand-in as soon as the network was up, the forged
    // answer refused before it: said while booting, or since.
    s.saw("time: refused an answer to 10.0.2.2 that is not authenticated")?;
    s.saw("time: set to 2026-07-15 10:0")?;
    let set = s
        .read
        .iter()
        .find(|l| l.starts_with("time: set to "))
        .cloned()
        .unwrap_or_default();
    if !set.contains("(NTS, authenticated)") {
        return Err(format!("the clock was not set by NTS: {set}"));
    }
    s.wait_for("settings: date and time, 10:0")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("1-utc.png"))?;
    // Europe, then Amsterdam: their places in the list Settings reads.
    let list = std::fs::read_to_string(root().join("zoneinfo/zones")).map_err(|e| e.to_string())?;
    let mut regions: Vec<&str> = list
        .lines()
        .filter_map(|l| l.split('\t').next()?.split_once('/').map(|(r, _)| r))
        .collect();
    regions.dedup();
    let europe = regions.iter().position(|r| *r == "Europe").ok_or("no Europe")?;
    let amsterdam = list
        .lines()
        .filter(|l| l.starts_with("Europe/"))
        .position(|l| l.starts_with("Europe/Amsterdam\t"))
        .ok_or("no Amsterdam")?;
    s.tap_named(BUTTON, "zone-regions")?;
    s.tap_named(BUTTON, &format!("zone-region-{europe}"))?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("2-europe.png"))?;
    s.tap_named(BUTTON, &format!("zone-{amsterdam}"))?;
    s.wait_for("settings: time zone Europe/Amsterdam")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("3-amsterdam.png"))?;
    s.home()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Clock")?;
    s.wait_for("clock: drawn, 12:0")?;
    s.shot(&dir.join("4-clock.png"))?;
    s.home()?;
    s.wait_for(&home_apps(0))?;

    // US-International: ' and " put their accents on the next letter.
    // Settings as it was left, on the date and time page.
    s.tap_named("launcher: tile ", "Settings")?;
    s.tap_named(BUTTON, "back")?;
    s.tap_named(BUTTON, "keyboard")?;
    s.wait_for("settings: keyboard")?;
    s.tap_named(BUTTON, "keyboard-1")?;
    s.wait_for("settings: keyboard us-intl")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("5-keyboard.png"))?;
    s.home()?;
    s.wait_for(&home_apps(0))?;
    // The layout is read again a moment after it changed.
    std::thread::sleep(Duration::from_millis(2500));
    s.tap_named("launcher: tile ", "Notes")?;
    s.wait_for("display: Notes connected")?;
    s.tap_named("notes: button ", "new")?;
    s.wait_for("notes: new 1")?;
    s.type_keys("Caf'e, na\"ive gar'con\n")?;
    s.wait_for("notes: saved 1")?;
    // On Dutch: ´ beside +, ¨ beside P, ¸ with AltGr beside /. Settings
    // as it was left, on the keyboard page.
    s.home()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Settings")?;
    s.tap_named(BUTTON, "keyboard-2")?;
    s.wait_for("settings: keyboard nl")?;
    s.home()?;
    s.wait_for(&home_apps(0))?;
    std::thread::sleep(Duration::from_millis(2500));
    s.tap_named("launcher: tile ", "Notes")?;
    // "één geëerd ça".
    s.press_keys(&[
        &["apostrophe"],
        &["e"],
        &["apostrophe"],
        &["e"],
        &["n"],
        &["spc"],
        &["g"],
        &["e"],
        &["bracket_left"],
        &["e"],
        &["e"],
        &["r"],
        &["d"],
        &["spc"],
        &["alt_r", "equal"],
        &["c"],
        &["a"],
    ])?;
    s.wait_for("notes: saved 1")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("6-typed.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// An NTS server on the host for the guest (as 10.0.2.2): its key
/// exchange over TLS on a free port, which is returned with the root its
/// certificate is signed by, for the guest to trust; NTP on another,
/// telling the time `now` gives (seconds since 1970). Someone on the path
/// is played too: before each true answer goes one forged with a key of
/// their own, a year back.
fn nts_stand_in(now: impl Fn() -> u64 + Send + 'static) -> Result<(u16, Vec<u8>)> {
    use pinnacle_net::nts;
    use pinnacle_tls::server::{Config, Issue, Server, certificate};
    use std::io::Write;
    let random = |n: usize| {
        let mut bytes = vec![0u8; n];
        std::fs::File::open("/dev/urandom")
            .and_then(|mut f| f.read_exact(&mut bytes))
            .map(|_| bytes)
            .map_err(|e| format!("/dev/urandom: {e}"))
    };
    let key = |bytes: Vec<u8>| -> [u8; 32] { bytes.try_into().unwrap() };
    let (root_key, server_key, master) = (key(random(32)?), key(random(32)?), key(random(32)?));
    // Valid from a year before the demo's day to five after.
    let (from, until) = ((now() - 365 * 86_400) as i64, (now() + 5 * 365 * 86_400) as i64);
    let root = certificate(&Issue {
        name: "Pinnacle demo time root",
        key: pinnacle_crypto::ed25519::public(&root_key),
        issuer: "Pinnacle demo time root",
        issuer_key: &root_key,
        ca: true,
        hosts: &[],
        from,
        until,
    });
    let leaf = certificate(&Issue {
        name: "10.0.2.2",
        key: pinnacle_crypto::ed25519::public(&server_key),
        issuer: "Pinnacle demo time root",
        issuer_key: &root_key,
        ca: false,
        hosts: &["10.0.2.2"],
        from,
        until,
    });

    let ntp = std::net::UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
    let ntp_port = ntp.local_addr().map_err(|e| e.to_string())?.port();
    let ke = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
    let ke_port = ke.local_addr().map_err(|e| e.to_string())?.port();
    std::thread::spawn(move || {
        for mut tcp in ke.incoming().flatten() {
            let (Ok(r), Ok(s)) = (random(32), random(32)) else {
                continue;
            };
            let config = Config {
                chain: vec![leaf.clone()],
                key: server_key,
                alpn: vec![nts::ALPN.into()],
            };
            let mut server = Server::new(config, key(r), key(s));
            let mut asked = Vec::new();
            let mut buffer = [0u8; 4096];
            while let Ok(n @ 1..) = tcp.read(&mut buffer) {
                if server.receive(&buffer[..n]).is_err() {
                    break;
                }
                asked.extend(server.read());
                // The request ends with its end-of-message record.
                if server.connected() && asked.ends_with(&[0x80, 0, 0, 0]) {
                    let export = |context: &[u8]| key(server.export(nts::EXPORTER, context, 32).unwrap());
                    let keys = nts::Keys {
                        c2s: export(&nts::C2S),
                        s2c: export(&nts::S2C),
                    };
                    let cookies: Vec<Vec<u8>> = (0..8)
                        .filter_map(|_| random(16).ok())
                        .map(|nonce| nts::seal_cookie(&master, &keys, &nonce.try_into().unwrap()))
                        .collect();
                    server.write(&nts::ke_answer(&cookies, None, Some(ntp_port)));
                }
                if tcp.write_all(&server.take_output()).is_err() {
                    break;
                }
            }
        }
    });
    std::thread::spawn(move || {
        let mut packet = [0u8; 1500];
        while let Ok((n, from)) = ntp.recv_from(&mut packet) {
            let Some(asked) = nts::asked(&packet[..n], |c| nts::open_cookie(&master, c)) else {
                continue;
            };
            // NTP counts from 1900.
            let header = |seconds: u64| {
                let stamp = (seconds + 2_208_988_800) << 32;
                let mut h = [0u8; 48];
                h[0] = 4 << 3 | 4;
                h[1] = 1;
                h[24..32].copy_from_slice(&packet[40..48]);
                h[32..40].copy_from_slice(&stamp.to_be_bytes());
                h[40..48].copy_from_slice(&stamp.to_be_bytes());
                h
            };
            let (Ok(nonce), Ok(theirs)) = (random(16), random(64)) else {
                continue;
            };
            let nonce: [u8; 16] = nonce.try_into().unwrap();
            // Seen on the path: the request's identifier and transmit time,
            // but not its keys.
            let forger = nts::Keys {
                c2s: key(theirs[..32].to_vec()),
                s2c: key(theirs[32..].to_vec()),
            };
            let forged = nts::reply(&header(now() - 365 * 86_400), &asked.uid, &forger, &[], &nonce);
            let _ = ntp.send_to(&forged, from);
            let cookies: Vec<Vec<u8>> = (0..asked.cookies)
                .filter_map(|_| random(16).ok())
                .map(|nonce| nts::seal_cookie(&master, &asked.keys, &nonce.try_into().unwrap()))
                .collect();
            let answer = nts::reply(&header(now()), &asked.uid, &asked.keys, &cookies, &nonce);
            let _ = ntp.send_to(&answer, from);
        }
    });
    Ok((ke_port, root))
}

fn terminal_demo() -> Result {
    let dir = demo_dir("demo-terminal")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Terminal")?;
    s.wait_for("display: Terminal connected")?;
    s.shot(&dir.join("1-empty.png"))?;
    s.type_keys("help\n")?;
    s.wait_for("terminal: help")?;
    s.shot(&dir.join("2-help.png"))?;
    for command in ["info", "devices", "echo Hallo vanuit Pinnacle"] {
        s.type_keys(&format!("{command}\n"))?;
        s.wait_for(&format!("terminal: {command} ended"))?;
    }
    s.shot(&dir.join("3-records.png"))?;
    s.type_keys("std-check\n")?;
    s.wait_for("terminal: std-check ended")?;
    s.type_keys("nothing\n")?;
    s.wait_for("terminal: nothing")?;
    s.shot(&dir.join("4-plain-output.png"))?;
    // An image, then questions: a line typed, a choice and a yes tapped.
    // Typing on the physical keyboard hid the on-screen one: the field is
    // at the window's bottom.
    s.type_keys("palette\n")?;
    s.wait_for("terminal: palette ended")?;
    s.type_keys("ask\n")?;
    s.wait_for("terminal: asked What is your name")?;
    s.type_keys("Sam\n")?;
    s.wait_for("terminal: asked Which fruit")?;
    s.shot(&dir.join("5-a-choice.png"))?;
    s.tap_named("terminal: button ", "answer-1")?;
    s.wait_for("terminal: asked Is that your final answer")?;
    s.tap_named("terminal: button ", "answer-0")?;
    s.wait_for("terminal: ask ended")?;
    s.shot(&dir.join("6-answered.png"))?;
    // Closed and opened again: the session is kept.
    s.close()?;
    s.wait_for("display: closed Terminal")?;
    s.tap_named("launcher: tile ", "Terminal")?;
    s.wait_for("terminal: 8 commands kept")?;
    s.shot(&dir.join("7-kept.png"))?;
    // Folders and files: cd, ls, cat, as in any terminal.
    s.type_keys("clear\ncd system:/fonts\n")?;
    s.wait_for("terminal: cd system:/fonts ended (Some(0))")?;
    s.type_keys("ls\n")?;
    s.wait_for("terminal: ls ended")?;
    s.type_keys("cat LICENSE\n")?;
    s.wait_for("terminal: cat LICENSE ended")?;
    s.shot(&dir.join("8-files.png"))?;
    // Tab completes a path; up brings the last command back.
    s.type_keys("clear\ncd ..\nls ap\t\n")?;
    s.wait_for("terminal: ls apps/ ended")?;
    s.type_keys("hist\t\n")?;
    s.wait_for("terminal: history ended")?;
    s.type_keys("ca\t")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("9-completion.png"))?;
    // A tap on the page brings the on-screen keyboard back, and above it
    // the keys it lacks.
    let (w, h) = s.app();
    s.tap_app((w / 2, h / 3))?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("10-touch.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// Pipelines in the terminal: a folder's table sorted, filtered and cut to
/// two columns, a file's lines filtered, and a column that is not there;
/// photographed into `target/demo-pipeline/`.
fn pipeline_demo() -> Result {
    let dir = demo_dir("demo-pipeline")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Terminal")?;
    s.wait_for("display: Terminal connected")?;
    s.type_keys("cd system:/fonts\n")?;
    s.wait_for("terminal: cd system:/fonts ended")?;
    let run = |s: &mut Session, line: &str| -> Result {
        s.type_keys(&format!("{line}\n"))?;
        s.wait_for(&format!("terminal: {line} ended"))
    };
    run(&mut s, "ls")?;
    run(&mut s, "ls | sort Size down")?;
    s.shot(&dir.join("1-sorted.png"))?;
    s.type_keys("clear\n")?;
    run(&mut s, "ls | where Size > 100 KB | sort Size | pick Name Size")?;
    run(&mut s, "cat LICENSE | where copyright | first 3")?;
    s.shot(&dir.join("2-filtered.png"))?;
    s.type_keys("clear\n")?;
    run(&mut s, "ls | sort Kind")?;
    run(&mut s, "ls nothing | sort Size")?;
    run(&mut s, "sort Size")?;
    s.shot(&dir.join("3-mistakes.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// The terminal for looking after a device: the programs that run and the
/// services, the disks and the network, the kernel's log searched, a
/// table written to a file and read back, commands one after another, a
/// system program ended once the person says yes; photographed into
/// `target/demo-admin/`.
fn admin_demo() -> Result {
    let dir = demo_dir("demo-admin")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Terminal")?;
    s.wait_for("display: Terminal connected")?;
    let run = |s: &mut Session, line: &str| -> Result {
        s.type_keys(&format!("{line}\n"))?;
        s.wait_for(&format!("terminal: {line} ended"))
    };
    run(&mut s, "ps")?;
    run(&mut s, "services | first 6")?;
    s.shot(&dir.join("1-ps-services.png"))?;
    s.type_keys("clear\n")?;
    run(&mut s, "df")?;
    run(&mut s, "du system:/")?;
    run(&mut s, "net")?;
    run(&mut s, "date")?;
    s.shot(&dir.join("2-disks-network.png"))?;
    s.type_keys("clear\n")?;
    run(&mut s, "log display | last 4")?;
    run(&mut s, "grep -r -i copyright system:/fonts | first 3")?;
    run(&mut s, "find system:/ License | count")?;
    s.shot(&dir.join("3-log-and-search.png"))?;
    s.type_keys("clear\n")?;
    // One line, three commands: the second and third each as the one
    // before ends.
    s.type_keys("cd data:/ && ps | sort Memory down | pick Program Memory > ps.txt; head -n 4 ps.txt\n")?;
    s.wait_for("terminal: head -n 4 ps.txt ended")?;
    run(&mut s, "wc ps.txt")?;
    // The `ls` after a `cd` that failed does not run, and says nothing.
    s.type_keys("cd nowhere && ls\n")?;
    s.wait_for("terminal: cd nowhere ended")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("4-redirect-and-chain.png"))?;
    s.type_keys("clear\n")?;
    run(&mut s, "ps | where Program = time")?;
    s.type_keys("kill time\n")?;
    s.wait_for("terminal: asked time")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("5-kill-asks.png"))?;
    s.type_keys("y\n")?;
    s.wait_for("terminal: kill time ended")?;
    run(&mut s, "ps | where Program = time")?;
    s.shot(&dir.join("6-killed.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// The command `frits` in the terminal: the examples, a script that keeps
/// a file, its effects and tests, and lines typed one at a time;
/// photographed into `target/demo-frits/`.
fn frits_demo() -> Result {
    let dir = demo_dir("demo-frits")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Terminal")?;
    s.wait_for("display: Terminal connected")?;
    for command in ["frits examples", "frits run hello Pinnacle"] {
        s.type_keys(&format!("{command}\n"))?;
        s.wait_for(&format!("terminal: {command} ended"))?;
    }
    s.shot(&dir.join("1-examples.png"))?;
    for command in [
        "frits run todo add Buy milk",
        "frits run todo add Call Anna",
        "frits run todo done 1",
    ] {
        s.type_keys(&format!("{command}\n"))?;
        s.wait_for(&format!("terminal: {command} ended"))?;
    }
    s.shot(&dir.join("2-todo.png"))?;
    for command in ["frits check todo", "frits test todo"] {
        s.type_keys(&format!("{command}\n"))?;
        s.wait_for(&format!("terminal: {command} ended"))?;
    }
    s.shot(&dir.join("3-check-and-test.png"))?;
    // Lines typed at its prompt: a function kept, then used.
    s.type_keys("frits\n")?;
    s.wait_for("terminal: asked frits>")?;
    for line in [
        "fn square(x: Int) -> Int { x * x }",
        "square(12)",
        "[1, 2, 3].map(fn(x) { square(x) })",
        "Console.table([\"n\", \"square\"], [[\"3\", \"{square(3)}\"], [\"4\", \"{square(4)}\"]])",
    ] {
        s.type_keys(&format!("{line}\n"))?;
        s.wait_for("terminal: asked frits>")?;
    }
    s.shot(&dir.join("4-lines.png"))?;
    s.type_keys("\n")?;
    s.wait_for("terminal: frits ended")?;
    s.shot(&dir.join("5-ended.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// The agent, as a person meets it: Settings → Agent off, a key given and
/// the agent turned on, against the stand-in provider beside the package
/// source (`model.rs`); photographed into `target/demo-agent/`.
fn agent_demo() -> Result {
    let store = serve()?;
    // The host the person would type: the stand-in, on this machine.
    let host = format!("host={}\nmodel=stand-in\non=no\n", store.trim_end_matches('/'));
    // A contact, Anna, for the agent to send to (moved into the vault as
    // the system opens it).
    let anna = pinnacle_p2p::identity::Identity::from_seed([0xa4; 32]).card("Anna");
    let hex: String = anna.key[..16].iter().map(|b| format!("{b:02x}")).collect();
    disks_at(
        &root().join("target/system.img"),
        &store,
        &[
            ("/settings/agent".into(), host.into_bytes()),
            (format!("/contacts/{hex}"), anna.to_bytes().to_vec()),
        ],
    )?;
    let dir = demo_dir("demo-agent")?;
    let mut s = Session::boot(&Guest::default(), "")?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Settings")?;
    s.wait_for("display: Settings connected")?;
    // This device's fourth row, the agent; its page's rows: the switch, the
    // host, the model, the key, back.
    s.tap_named("settings: button ", "agent")?;
    s.wait_for("settings: agent")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("1-agent-off.png"))?;
    s.tap_named("settings: button ", "agent-key")?;
    s.type_keys("test-key\n")?;
    s.wait_for("settings: the agent's Key changed")?;
    s.tap_named("settings: button ", "agent-switch")?;
    s.wait_for("settings: the agent is on")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("2-agent-on.png"))?;
    // The terminal: what the p2p service can do, then a task for the
    // agent with it. The stand-in answers `call …` with that call.
    s.home()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Terminal")?;
    s.wait_for("display: Terminal connected")?;
    s.type_keys("p2p\n")?;
    s.wait_for("terminal: p2p ended")?;
    s.shot(&dir.join("3-verbs.png"))?;
    let task = r#"agent +p2p call p2p__send {"contact":"Anna","text":"See you at eight"}"#;
    s.type_keys(task)?;
    s.type_keys("\n")?;
    // Sending out of the device: the display server asks, over everything.
    s.wait_for("display: the agent asks")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("4-confirm.png"))?;
    s.tap_screen_named("display: button ", "allow")?;
    s.wait_for(&format!("terminal: {task} ended"))?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("5-done.png"))?;
    // And undone, as far as it can be: a message sent cannot.
    s.type_keys("agent undo\n")?;
    s.wait_for("terminal: agent undo ended")?;
    s.shot(&dir.join("6-undo.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// The agent at a workbench (`docs/agent-workbench.md`): `workbench` runs
/// on this machine with a small git repository and a bare one as its
/// remote, as a contact of the device; in the terminal the agent opens a
/// task, writes a file, runs the tests sandboxed, commits and proposes —
/// the proposal confirmed on the device's screen — and the branch is then
/// in the remote. Photographed into `target/demo-workbench/`.
///
/// `real`: a real model does it, Anthropic's, with the key in
/// `ANTHROPIC_API_KEY`, told the task in words rather than scripted; every
/// question it asks is allowed, as the person would.
fn workbench_demo(real: bool) -> Result {
    use pinnacle_p2p::identity::Identity;
    let run = |dir: &Path, program: &str, args: &[&str]| -> Result<String> {
        let out = Command::new(program)
            .args(args)
            .current_dir(dir)
            .output()
            .map_err(|e| format!("{program}: {e}"))?;
        if !out.status.success() {
            return Err(format!(
                "{program} {args:?}: {}",
                String::from_utf8_lossy(&out.stderr)
            ));
        }
        Ok(String::from_utf8_lossy(&out.stdout).into_owned())
    };
    cargo(&["build", "--locked", "--release", "-p", "pinnacle-workbench"])?;
    let bin = root().join("target/release/workbench");
    // A repository with a test the agent's change must pass, and a bare
    // one as the remote a proposal goes to.
    let base = root().join("target/workbench-demo");
    let _ = std::fs::remove_dir_all(&base);
    let (repo, remote, state) = (base.join("demo"), base.join("remote.git"), base.join("state"));
    std::fs::create_dir_all(repo.join("src")).map_err(|e| e.to_string())?;
    std::fs::create_dir_all(repo.join("tests")).map_err(|e| e.to_string())?;
    std::fs::create_dir_all(&state).map_err(|e| e.to_string())?;
    let write = |path: PathBuf, text: &str| {
        std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))
    };
    write(
        repo.join("Cargo.toml"),
        "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[workspace]\n",
    )?;
    write(repo.join("src/lib.rs"), "pub fn two() -> u32 {\n    3\n}\n")?;
    write(
        repo.join("tests/two.rs"),
        "#[test]\nfn two_is_two() {\n    assert_eq!(demo::two(), 2);\n}\n",
    )?;
    run(&base, "git", &["init", "-q", "--bare", "remote.git"])?;
    for args in [
        &["init", "-q", "-b", "main"][..],
        &["add", "-A"],
        &[
            "-c",
            "user.name=demo",
            "-c",
            "user.email=demo@invalid",
            "commit",
            "-q",
            "-m",
            "a wrong two",
        ],
        &["remote", "add", "origin", &remote.display().to_string()],
    ] {
        run(&repo, "git", args)?;
    }
    // Who is who: the device's identity and the workbench's, each the
    // other's contact.
    let (device, bench) = (Identity::from_seed([0xd1; 32]), Identity::from_seed([0xbe; 32]));
    let bench_card = bench.card("Bench");
    std::fs::write(state.join("identity"), bench.seed()).map_err(|e| e.to_string())?;
    let card_hex = |c: &pinnacle_p2p::identity::Card| {
        c.to_bytes()
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect::<String>()
    };
    let port = free_udp_port()?;
    let config = format!(
        "name=Bench\nport={port}\naddress=10.0.2.2:{port}\nstate={}\ncontact={}\nrepo=demo {}\nremote=origin\n\
         job=check cargo check --offline {{package}}\njob=test cargo test --offline {{package}} {{filter}}\njob-minutes=5\n",
        state.display(),
        card_hex(&device.card("Pinnacle")),
        repo.display()
    );
    write(base.join("workbench.conf"), &config)?;
    let mut workbench = Command::new(&bin)
        .arg(base.join("workbench.conf"))
        .stdout(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| format!("workbench: {e}"))?;
    let bench_out = workbench.stdout.take().unwrap();
    let bench_log = std::thread::spawn(move || {
        use std::io::BufRead;
        for line in std::io::BufReader::new(bench_out).lines().map_while(|l| l.ok()) {
            println!("  [bench] {line}");
        }
    });
    let store = serve()?;
    let (host, key) = if real {
        let key = std::env::var("ANTHROPIC_API_KEY").map_err(|_| "no ANTHROPIC_API_KEY for a real model")?;
        (
            "host=https://api.anthropic.com\nmodel=claude-sonnet-5\non=no\n".to_string(),
            key,
        )
    } else {
        (
            format!("host={}\nmodel=stand-in\non=no\n", store.trim_end_matches('/')),
            String::from("test-key"),
        )
    };
    let key_hex: String = bench_card.key[..16].iter().map(|b| format!("{b:02x}")).collect();
    disks_at(
        &root().join("target/system.img"),
        &store,
        &[
            ("/settings/agent".into(), host.into_bytes()),
            ("/settings/identity".into(), device.seed().to_vec()),
            ("/settings/peers".into(), format!("10.0.2.2:{port}").into_bytes()),
            (format!("/contacts/{key_hex}"), bench_card.to_bytes().to_vec()),
        ],
    )?;
    let result = (|| -> Result {
        let dir = demo_dir(if real {
            "demo-workbench-real"
        } else {
            "demo-workbench"
        })?;
        let mut s = Session::boot(&Guest::default(), "")?;
        s.wait_for(&home_apps(0))?;
        // The agent on, with the stand-in's key, as agent-demo does it.
        s.tap_named("launcher: tile ", "Settings")?;
        s.wait_for("display: Settings connected")?;
        s.tap_named("settings: button ", "agent")?;
        s.wait_for("settings: agent")?;
        std::thread::sleep(Duration::from_millis(600));
        s.tap_named("settings: button ", "agent-key")?;
        s.type_keys(&format!("{key}\n"))?;
        s.wait_for("settings: the agent's Key changed")?;
        s.tap_named("settings: button ", "agent-switch")?;
        s.wait_for("settings: the agent is on")?;
        s.home()?;
        s.wait_for(&home_apps(0))?;
        s.tap_named("launcher: tile ", "Terminal")?;
        s.wait_for("display: Terminal connected")?;
        if real {
            let task = "agent +workbench@Bench On the workbench, open a task in the repository demo from main. \
                        Its test in tests/two.rs fails: read it and src/lib.rs, fix src/lib.rs, run the job test \
                        and wait for it until it passes, commit, and propose the branch.";
            s.type_keys(task)?;
            s.type_keys("\n")?;
            // The model takes its time: questions allowed as they come, until it ends.
            let mut asked = 0;
            loop {
                match s.wait_any(
                    &["display: the agent asks", &format!("terminal: {task} ended")],
                    Duration::from_secs(600),
                )? {
                    line if line.starts_with("display: the agent asks") => {
                        asked += 1;
                        std::thread::sleep(Duration::from_millis(600));
                        s.shot(&dir.join(format!("{asked}-asks.png")))?;
                        s.tap_screen_named("display: button ", "allow")?;
                    }
                    line => {
                        println!("workbench: {line}");
                        break;
                    }
                }
            }
            std::thread::sleep(Duration::from_millis(600));
            s.shot(&dir.join("9-done.png"))?;
        } else {
            // The stand-in calls what the line says, in order: a task opened
            // (the workbench's first is 1), the fix written, the tests run and
            // waited for, the diff, a commit, and the proposal.
            let task = concat!(
                r#"agent +workbench@Bench call workbench__open {"repo":"demo","base":"main"} ; "#,
                r#"call workbench__write {"task":1,"path":"src/lib.rs","text":"pub fn two() -> u32 { 1 + 1 }"} ; "#,
                r#"call workbench__run {"task":1,"job":"test"} ; "#,
                r#"call workbench__job {"task":1,"id":1,"wait":60} ; "#,
                r#"call workbench__commit {"task":1,"message":"two is two"} ; "#,
                r#"call workbench__propose {"task":1}"#
            );
            s.type_keys(task)?;
            s.type_keys("\n")?;
            std::thread::sleep(Duration::from_secs(15));
            s.shot(&dir.join("0-working.png"))?;
            s.wait_for("display: the agent asks")?;
            std::thread::sleep(Duration::from_millis(600));
            s.shot(&dir.join("1-propose.png"))?;
            s.tap_screen_named("display: button ", "allow")?;
            s.wait_for(&format!("terminal: {task} ended"))?;
            std::thread::sleep(Duration::from_millis(600));
            s.shot(&dir.join("2-done.png"))?;
        }
        // The proposal is in the remote, and holds the fix: two, however the
        // model wrote it, and not the three it was.
        let shown = run(&remote, "git", &["show", "agent/1:src/lib.rs"])?;
        let three = shown.lines().any(|l| l.trim() == "3" || l.contains("{ 3 }"));
        if three || !(shown.contains("1 + 1") || shown.contains('2')) {
            return Err(format!("the remote's agent/1 holds {shown:?}"));
        }
        println!("workbench: agent/1 is in the remote, with the fix");
        println!("{}", dir.display());
        Ok(())
    })();
    let _ = workbench.kill();
    let _ = workbench.wait();
    let _ = bench_log.join();
    result
}

/// A winit app on Pinnacle (`ports/winit-demo`), installed as the app
/// "Winit": opened from the launcher, dragged across, photographed into
/// `target/demo-winit/`.
fn winit_demo() -> Result {
    let program = build_on_ports("winit-demo", "winit-demo")?;
    let manifest = manifest("winit", "Winit", "A winit app, from crates.io");
    disks_at(
        &root().join("target/system.img"),
        &serve()?,
        &[
            ("/apps/winit/program".into(), program),
            ("/apps/winit/manifest".into(), manifest.into_bytes()),
        ],
    )?;
    let dir = demo_dir("demo-winit")?;
    let mut s = Session::boot(&Guest::default(), "")?;
    let (w, h) = s.app();
    s.wait_for(&home_apps(1))?;
    s.tap_named("launcher: tile ", "Winit")?;
    s.wait_for("winit: drawn")?;
    s.shot(&dir.join("1-window.png"))?;
    // A loop drawn with a finger.
    let r = (w.min(h) / 4) as f32;
    let path: Vec<(i32, i32)> = (0..=60)
        .map(|i| i as f32 * std::f32::consts::TAU / 60.0)
        .map(|a| (w / 2 + (a.cos() * r) as i32, h / 3 + (a.sin() * r * 0.6) as i32))
        .collect();
    s.drag_app(&path)?;
    s.wait_for("winit: a trail of")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("2-drawn.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// A wgpu app on Pinnacle: installed as "wgpu" (its manifest granting the
/// GPU), opened from the launcher, its triangle drawn by the host's GPU
/// through Pinnacle's Vulkan driver, photographed into `target/demo-wgpu/`.
fn wgpu_demo() -> Result {
    let program = build_on_ports("wgpu-demo", "wgpu-demo")?;
    let manifest = manifest("wgpu", "wgpu", "A wgpu app, drawn by the GPU") + "gpu=yes\n";
    disks_at(
        &root().join("target/system.img"),
        &serve()?,
        &[
            ("/apps/wgpu/program".into(), program),
            ("/apps/wgpu/manifest".into(), manifest.into_bytes()),
        ],
    )?;
    let dir = demo_dir("demo-wgpu")?;
    let mut s = Session::boot(&Guest::default(), "")?;
    s.wait_for(&home_apps(1))?;
    s.tap_named("launcher: tile ", "wgpu")?;
    s.wait_for("wgpu-demo: drawn")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("1-triangle.png"))?;
    println!("{}", dir.display());
    Ok(())
}

/// Drives the system as a person would, with a screenshot at each step,
/// into `target/demo/`: home, the Store, installing two apps, home again
/// with them, then Paint, Calculator, Clock and About in use, the screen
/// turned, Clock closed, a note written, and Settings: the device named and
/// the screen turned back from it. Every tap is found by `pinnacle_layout`, as the apps lay
/// themselves out, so the demo runs on any screen size (`PINNACLE_SCREEN`).
fn demo() -> Result {
    let dir = demo_dir("demo")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.shot(&dir.join("1-home.png"))?;
    s.tap_named("launcher: tile ", "Store")?;
    s.wait_for("display: Store connected")?;
    s.shot(&dir.join("2-store.png"))?;
    s.tap_named("store: button ", "offer-0")?;
    s.wait_for("store: Calculator is installed")?;
    s.tap_named("store: button ", "offer-1")?;
    s.wait_for("store: Paint is installed")?;
    s.shot(&dir.join("3-installed.png"))?;
    s.home()?;
    s.wait_for(&home_apps(2))?;
    s.shot(&dir.join("4-home-with-new-apps.png"))?;
    s.tap_named("launcher: tile ", "Paint")?;
    s.wait_for("display: Paint connected")?;
    let (w, _) = s.app();
    // The canvas, from the top of the window to the palette: twice as
    // tall as its centre is low.
    s.wait_for("paint: drawn")?;
    let canvas = 2 * s.find_named("paint: button canvas")?.1;
    let wave: Vec<(i32, i32)> = (0..40)
        .map(|i| {
            let y = canvas * 3 / 10 + ((i as f32 * 0.5).sin() * (canvas / 8) as f32) as i32;
            (80 + i * (w - 160) / 40, y)
        })
        .collect();
    s.drag_app(&wave)?;
    // The yellow swatch.
    s.tap_named("paint: button ", "swatch-3")?;
    let r = (canvas / 5).min(160) as f32;
    let circle: Vec<(i32, i32)> = (0..=48)
        .map(|i| i as f32 * std::f32::consts::TAU / 48.0)
        .map(|a| {
            (
                w / 2 + (a.cos() * r) as i32,
                canvas * 7 / 10 + (a.sin() * r) as i32,
            )
        })
        .collect();
    s.drag_app(&circle)?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("5-paint.png"))?;
    // The circle undone and done again, then kept in Paint's folder.
    s.tap_named("paint: button ", "undo")?;
    s.wait_for("paint: undone")?;
    s.tap_named("paint: button ", "redo")?;
    s.wait_for("paint: redone")?;
    s.wait_for("paint: saved")?;
    s.home()?;
    s.wait_for(&home_apps(2))?;
    s.tap_named("launcher: tile ", "Calculator")?;
    s.wait_for("display: Calculator connected")?;
    // 1 2 × 8 = (the keypad: 7 8 9 ÷ / 4 5 6 × / 1 2 3 − / C 0 = +).
    for i in [8, 9, 7, 1, 14] {
        s.tap_named("calculator: key ", &i.to_string())?;
    }
    // Then × 1.5 = on the 96, with the decimal key: 144.
    for key in ["7", "8", "decimal", "5", "14"] {
        s.tap_named("calculator: key ", key)?;
    }
    s.wait_for("calculator: ")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("6-calculator.png"))?;
    s.home()?;
    s.wait_for(&home_apps(2))?;
    s.tap_named("launcher: tile ", "Clock")?;
    s.wait_for("display: Clock connected")?;
    s.wait_for("clock: drawn")?;
    s.shot(&dir.join("7-clock.png"))?;
    // A five-minute timer started, and the stopwatch with a lap.
    s.tap_named("clock: button ", "tab-timer")?;
    s.tap_named("clock: button ", "timer-preset-5")?;
    s.tap_named("clock: button ", "timer-start")?;
    s.wait_for("clock: timer started, 05:00")?;
    std::thread::sleep(Duration::from_secs(2));
    s.shot(&dir.join("7b-clock-timer.png"))?;
    s.tap_named("clock: button ", "tab-stopwatch")?;
    s.tap_named("clock: button ", "stopwatch-start")?;
    s.wait_for("clock: stopwatch started")?;
    std::thread::sleep(Duration::from_secs(2));
    s.tap_named("clock: button ", "stopwatch-lap")?;
    s.wait_for("clock: lap 1")?;
    std::thread::sleep(Duration::from_secs(1));
    s.shot(&dir.join("7c-clock-stopwatch.png"))?;
    s.home()?;
    s.wait_for(&home_apps(2))?;
    s.tap_named("launcher: tile ", "About")?;
    s.wait_for("display: About connected")?;
    s.shot(&dir.join("8-about.png"))?;
    // Turn the screen (F12): About and then the home screen lay out afresh.
    s.turn()?;
    s.shot(&dir.join("9-about-turned.png"))?;
    s.home()?;
    s.wait_for(&home_apps(2))?;
    s.shot(&dir.join("10-home-turned.png"))?;
    // Close an app with the status bar's button: the home screen returns.
    // Clock still runs from before: the tap brings it back to the front.
    s.tap_named("launcher: tile ", "Clock")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("11-clock-closable.png"))?;
    s.close()?;
    s.wait_for("display: closed Clock")?;
    s.shot(&dir.join("12-clock-closed.png"))?;
    // A note, typed on the physical keyboard: saved, and in the list beside it.
    s.tap_named("launcher: tile ", "Notes")?;
    s.wait_for("display: Notes connected")?;
    s.tap_named("notes: button ", "new")?;
    s.wait_for("notes: new 1")?;
    s.type_keys("Shopping list\nbread, cheese and apples\nstamps for the post")?;
    s.wait_for("notes: saved 1")?;
    s.shot(&dir.join("13-note.png"))?;
    // The note copied, and pasted into a new one with ctrl+V.
    s.tap_named("notes: button ", "copy")?;
    s.wait_for("display: copied")?;
    s.tap_named("notes: button ", "new")?;
    s.wait_for("notes: new 2")?;
    s.key_chord(&["ctrl", "v"])?;
    s.wait_for("notes: pasted")?;
    s.wait_for("notes: saved 2")?;
    s.shot(&dir.join("13b-note-pasted.png"))?;
    // A word in the middle: selected with shift and the arrows, typed over,
    // and then that word alone copied.
    s.key_chord(&["home"])?;
    for _ in 0.."stamps".len() {
        s.key_chord(&["shift", "right"])?;
        std::thread::sleep(Duration::from_millis(40));
    }
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("13c-note-selected.png"))?;
    s.type_keys("Envelopes")?;
    s.key_chord(&["shift", "home"])?;
    s.key_chord(&["ctrl", "c"])?;
    s.wait_for("notes: copied 9 bytes of 2")?;
    s.wait_for("notes: saved 2")?;
    s.shot(&dir.join("13d-note-word-copied.png"))?;
    // Bluetooth: the devices around, one opened, a Pinnacle added as a contact.
    s.home()?;
    s.wait_for(&home_apps(2))?;
    bluetooth_demo(&mut s, &dir)?;
    // Settings: a new name for the device, typed; then the screen turned by
    // its button, as the orientation sensor would.
    s.home()?;
    s.wait_for(&home_apps(2))?;
    s.tap_named("launcher: tile ", "Settings")?;
    s.wait_for("display: Settings connected")?;
    // Drawn: it says where its buttons are once it has.
    s.wait_for("settings: button ")?;
    s.shot(&dir.join("14-settings.png"))?;
    // Settings' buttons by the names it announces where it drew them.
    const BUTTON: &str = "settings: button ";
    s.tap_named(BUTTON, "name")?;
    s.type_keys("Kitchen tablet\n")?;
    s.wait_for("settings: name is Kitchen tablet")?;
    let (w, h) = s.screen;
    s.tap_named(BUTTON, "turn")?;
    s.wait_for(&format!("display: {h}x{w}"))?;
    s.screen = (h, w);
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("15-settings-turned.png"))?;
    // The password changed in Settings (the current one, the new one
    // twice); the screen locked from there, a wrong password refused, the
    // new one let in.
    s.tap_named(BUTTON, "password")?;
    s.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
    s.type_keys(&format!("{NEW_PASSWORD}\n"))?;
    s.type_keys(&format!("{NEW_PASSWORD}\n"))?;
    s.wait_for("settings: password changed")?;
    std::thread::sleep(Duration::from_millis(400));
    s.tap_named(BUTTON, "lock")?;
    s.wait_for("display: locked")?;
    s.type_keys("not my password\n")?;
    s.wait_for("display: wrong password")?;
    s.shot(&dir.join("16-locked.png"))?;
    s.type_keys(&format!("{NEW_PASSWORD}\n"))?;
    s.wait_for("display: unlocked")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("17-unlocked.png"))?;
    // The hardware the kernel found, and which driver took each.
    s.tap_named(BUTTON, "hardware")?;
    s.wait_for("settings: hardware")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("18-hardware.png"))?;
    Ok(())
}

/// Settings' network page: online and over which connection; switched off,
/// and on again until DHCP gives it its address back.
fn network_demo() -> Result {
    const BUTTON: &str = "settings: button ";
    let dir = demo_dir("demo-network")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Settings")?;
    s.wait_for("display: Settings connected")?;
    s.wait_for(BUTTON)?;
    s.shot(&dir.join("1-settings.png"))?;
    s.tap_named(BUTTON, "network")?;
    s.wait_for("settings: network")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("2-online.png"))?;
    s.tap_named(BUTTON, "network-switch")?;
    s.wait_for("settings: networking switched off")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("3-off.png"))?;
    s.tap_named(BUTTON, "network-switch")?;
    s.wait_for("settings: networking switched on")?;
    // The page looks again twice a second: online once it has.
    std::thread::sleep(Duration::from_millis(900));
    s.shot(&dir.join("4-online-again.png"))?;
    Ok(())
}

/// `cargo xtask pinebook-demo`: the system with a Pinebook Pro's input
/// and no other: its keyboard and touchpad one USB 1.1 device on the
/// RK3399's OHCI (here QEMU's keyboard and mouse on its OHCI). The data's
/// password typed on that keyboard, then Settings opened with the
/// touchpad's pointer and its click; a screenshot each.
fn pinebook_demo() -> Result {
    let dir = demo_dir("demo-pinebook")?;
    disks(&serve()?)?;
    let guest = Guest {
        pinebook: true,
        ..Guest::default()
    };
    let qemu = qemu_guest("virt", &Load::Image(image("qemu-virt")?, ""), true, &guest);
    // The password chosen here, not by `attach`: on the OHCI keyboard.
    let mut s = Session::attach(qemu, "", false, || Ok(()))?;
    s.wait_for("display: choose a password for your data")?;
    for line in OHCI_LINES {
        if !s.read.iter().any(|l| l.starts_with(line)) {
            return Err(format!("pinebook: no \"{line}\" in the output"));
        }
    }
    s.type_keys(DEMO_PASSPHRASE)?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("1-password-typed.png"))?;
    s.type_keys("\n")?;
    std::thread::sleep(Duration::from_millis(300));
    s.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
    s.wait_for("display: data opened")?;
    s.wait_for(&home_apps(0))?;
    // The touchpad: the pointer moved to Settings' tile, and a click.
    let at = s.find_named("launcher: tile Settings")?;
    let (x, y) = pinnacle_layout::shell::to_screen(s.screen.0, s.screen.1, at);
    s.click_at(x, y)?;
    s.wait_for("display: Settings connected")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("2-settings-opened.png"))?;
    println!("ok   pinebook: the password typed and Settings opened, on USB 1.1 (OHCI) alone");
    Ok(())
}

/// The sound's volume: the one Settings kept (30 %) given to the mixer at
/// start, Settings' slider tapped at its middle (50 %), and the tone it then
/// plays as loud in what QEMU heard as that says.
fn sound_demo() -> Result {
    const BUTTON: &str = "settings: button ";
    let dir = demo_dir("demo-sound")?;
    disks_at(
        &root().join("target/system.img"),
        &serve()?,
        &[("/settings/volume".into(), b"30".to_vec())],
    )?;
    let wav = dir.join("heard.wav");
    let guest = Guest {
        audio: Some(wav.clone()),
        ..Guest::default()
    };
    let mut s = Session::boot(&guest, "")?;
    s.saw("display: volume 30 %")?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Settings")?;
    s.wait_for("display: Settings connected")?;
    s.find_named(&format!("{BUTTON}volume"))?;
    // The page scrolled until Sound shows whole: a drag where the labels
    // are, which no control takes.
    let (w, h) = s.app();
    let points: Vec<(i32, i32)> = (0..=10).map(|i| (w / 4, h * 3 / 4 - h / 3 * i / 10)).collect();
    s.drag_app(&points)?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("1-volume-30.png"))?;
    s.tap_named(BUTTON, "volume")?;
    s.wait_for("settings: volume 50 %")?;
    // The tone's 200 ms, and the device's own time after it.
    std::thread::sleep(Duration::from_millis(1200));
    s.shot(&dir.join("2-volume-50.png"))?;
    // The last sound heard (the self-check's 440 Hz tone plays at every
    // start, before the display server sets the volume): Settings' tone,
    // whose loudest sample is 8000 (`TONE_LEVEL` in settings.rs).
    let want = 8000 * 50 / 100;
    match wav_last(&wav)? {
        Some((hz, seconds, peak))
            if (hz - 660.0).abs() <= 20.0 && seconds >= 0.15 && (peak - want).abs() <= want / 20 =>
        {
            println!(
                "ok   a tone of {hz:.0} Hz for {seconds:.2} s, peaking at {peak} at 50 % (8000 at 100 %)"
            );
        }
        Some((hz, seconds, peak)) => {
            return Err(format!(
                "{}: last a tone of {hz:.0} Hz for {seconds:.2} s peaking at {peak}, \
                 wanted 660 Hz peaking at {want}",
                wav.display()
            ));
        }
        None => return Err(format!("{}: no sound in it", wav.display())),
    }
    println!("{}", dir.display());
    Ok(())
}

/// Text beyond Latin, the language and accessibility: the device named in
/// five scripts (Arabic joined and right to left, Hebrew with its points,
/// Chinese, an emoji with a skin tone), Settings switched to Dutch, the text
/// made larger, high contrast, and the screen reader: a tap says what it
/// touched, a double tap acts on it, a swipe moves on.
fn access_demo() -> Result {
    const BUTTON: &str = "settings: button ";
    const PREFS: &str = "display: preferences: ";
    let dir = demo_dir("demo-access")?;
    let name = "Pinnacle · مرحبا بالعالم · שָׁלוֹם · 你好 · 👍🏽";
    disks_at(
        &root().join("target/system.img"),
        &serve()?,
        &[("/settings/name".into(), name.as_bytes().to_vec())],
    )?;
    let mut s = Session::boot(&Guest::default(), "")?;
    s.wait_for(&home_apps(0))?;
    s.tap_named("launcher: tile ", "Settings")?;
    s.wait_for("display: Settings connected")?;
    s.wait_for(BUTTON)?;
    s.shot(&dir.join("1-settings.png"))?;

    s.tap_named(BUTTON, "language")?;
    s.wait_for("settings: language")?;
    // The language is chosen from a dropdown: its options open over the
    // page, each row named for the language it chooses.
    s.tap_named(BUTTON, "language-choice")?;
    s.find_named(&format!("{BUTTON}language-nl"))?;
    s.shot(&dir.join("2-languages.png"))?;
    s.tap_named(BUTTON, "language-nl")?;
    s.wait_for(&format!("{PREFS}language nl"))?;
    s.shot(&dir.join("2-taal.png"))?;
    s.tap_named(BUTTON, "back")?;
    s.find_named(&format!("{BUTTON}access"))?;
    s.shot(&dir.join("3-instellingen.png"))?;

    s.tap_named(BUTTON, "access")?;
    s.wait_for("settings: accessibility")?;
    s.tap_named(BUTTON, "text-size")?;
    s.wait_for(&format!("{PREFS}language nl, text 125 %"))?;
    s.shot(&dir.join("4-tekst-125.png"))?;
    s.tap_named(BUTTON, "text-size")?;
    s.wait_for(&format!("{PREFS}language nl, text 150 %"))?;
    s.shot(&dir.join("5-tekst-150.png"))?;
    // On round: 200 %, then back to 100 %.
    s.tap_named(BUTTON, "text-size")?;
    s.wait_for(&format!("{PREFS}language nl, text 200 %"))?;
    s.tap_named(BUTTON, "text-size")?;
    s.wait_for(&format!("{PREFS}language nl, text 100 %"))?;
    s.tap_named(BUTTON, "contrast")?;
    s.wait_for(&format!("{PREFS}language nl, text 100 %, contrast high"))?;
    s.shot(&dir.join("6-contrast.png"))?;

    // The screen reader: from here a tap only says what it touched.
    s.tap_named(BUTTON, "reader")?;
    s.wait_for("reader: Schermlezer aan")?;
    let contrast = s.find_named(&format!("{BUTTON}contrast"))?;
    s.tap_app(contrast)?;
    s.wait_for("reader: Hoog contrast, schakelaar, aan")?;
    s.shot(&dir.join("7-schermlezer.png"))?;
    // A swipe to the right: the next row, then its switch.
    let (w, _) = s.app();
    let points: Vec<(i32, i32)> = (0..=6).map(|i| (w / 4 + w / 2 * i / 6, contrast.1)).collect();
    s.drag_app(&points)?;
    s.wait_for("reader: Schermlezer")?;
    s.drag_app(&points)?;
    s.wait_for("reader: Schermlezer, schakelaar, aan")?;
    s.shot(&dir.join("8-volgende.png"))?;
    // A double tap anywhere acts on what has the focus: the reader off.
    s.tap_app(contrast)?;
    s.tap_app(contrast)?;
    s.wait_for("reader: activating Schermlezer")?;
    s.wait_for(&format!(
        "{PREFS}language nl, text 100 %, contrast high, reader off"
    ))?;
    s.tap_named(BUTTON, "contrast")?;
    s.wait_for(&format!("{PREFS}language nl, text 100 %, contrast normal"))?;
    s.home()?;
    s.wait_for(&home_apps(0))?;
    s.shot(&dir.join("9-thuis.png"))?;
    Ok(())
}

impl Session {
    /// The app area's size.
    fn app(&self) -> (i32, i32) {
        let a = pinnacle_layout::shell::app_area(self.screen.0, self.screen.1);
        (a.width, a.height)
    }

    /// Taps the control an app built from a view announced as `<prefix><name>
    /// at <x> <y>` (`Screen::announce`, after each time it draws a page):
    /// the latest such line, once the lines have gone quiet for a moment, or
    /// the next one if none came yet. The stylesheet places those controls,
    /// so their places are the app's to say, not `pinnacle_layout`'s to work
    /// out.
    /// A control below or above the window (a page taller than the screen,
    /// held sideways) is first dragged into view, as a finger would.
    fn tap_named(&mut self, prefix: &str, name: &str) -> Result {
        let want = format!("{prefix}{name}");
        for _ in 0..4 {
            let (x, y) = self.find_named(&want)?;
            let (w, h) = self.app();
            // Its middle on the screen is enough: a drag to bring it further
            // in may start on a field, and a press there calls the keyboard up
            // and moves what was to be tapped.
            if (0..h).contains(&y) {
                return self.tap_app((x, y));
            }
            // Bring it to the middle: a drag from where no control is (the
            // left quarter, where the labels are).
            let from = h / 2;
            let to = (from - (y - h / 2)).clamp(8, h - 8);
            let points: Vec<(i32, i32)> = (0..=10).map(|i| (w / 4, from + (to - from) * i / 10)).collect();
            self.drag_app(&points)?;
        }
        Err(format!("\"{want}\" stayed out of view"))
    }

    /// Taps a control of a screen that covers the whole screen (the display
    /// server's question, its password), which announces screen pixels.
    fn tap_screen_named(&mut self, prefix: &str, name: &str) -> Result {
        let (x, y) = self.find_named(&format!("{prefix}{name}"))?;
        self.tap(x, y)
    }

    /// Where the control `<want>` was last announced: after the lines on
    /// their way from a redraw have come in (quiet for 300 ms, at most 3 s),
    /// or as soon as it is first announced.
    fn find_named(&mut self, want: &str) -> Result<(i32, i32)> {
        let settle = Instant::now() + Duration::from_secs(3);
        while Instant::now() < settle {
            let Ok(line) = self.line(Duration::from_millis(300)) else {
                break;
            };
            if line.starts_with("panic") {
                return Err(format!("the system panicked: {line}"));
            }
        }
        let deadline = Instant::now() + boot_timeout();
        loop {
            if let Some(at) = self.named.get(want) {
                return Ok(*at);
            }
            let left = deadline.saturating_duration_since(Instant::now());
            if self.line(left).is_err() {
                return Err(format!("no \"{want} at\" within {}s", boot_timeout().as_secs()));
            }
        }
    }

    /// Taps a point of the app area.
    fn tap_app(&mut self, at: (i32, i32)) -> Result {
        let (x, y) = pinnacle_layout::shell::to_screen(self.screen.0, self.screen.1, at);
        self.tap(x, y)
    }

    fn drag_app(&mut self, points: &[(i32, i32)]) -> Result {
        let (w, h) = self.screen;
        let points: Vec<_> = points
            .iter()
            .map(|&p| pinnacle_layout::shell::to_screen(w, h, p))
            .collect();
        self.drag(&points)
    }

    /// Turns the screen (F12, as an orientation sensor would) and waits
    /// for the display server to say it has.
    fn turn(&mut self) -> Result {
        let (w, h) = self.screen;
        self.call(r#"{"execute":"send-key","arguments":{"keys":[{"type":"qcode","data":"f12"}]}}"#)?;
        self.wait_for(&format!("display: {h}x{w}"))?;
        self.screen = (h, w);
        Ok(())
    }

    /// Taps the status bar's close button.
    fn close(&mut self) -> Result {
        let r = pinnacle_layout::shell::close(self.screen.0);
        self.tap(r.x + r.width / 2, r.y + r.height / 2)
    }

    /// Taps the home bar.
    fn home(&mut self) -> Result {
        let (x, y) = pinnacle_layout::shell::home(self.screen.0, self.screen.1);
        self.tap(x, y)
    }

    /// Presses keys together on the guest's physical keyboard (QEMU
    /// qcodes: "ctrl", "v").
    fn key_chord(&mut self, keys: &[&str]) -> Result {
        let keys: Vec<String> = keys
            .iter()
            .map(|k| format!(r#"{{"type":"qcode","data":"{k}"}}"#))
            .collect();
        self.call(&format!(
            r#"{{"execute":"send-key","arguments":{{"keys":[{}]}}}}"#,
            keys.join(",")
        ))
        .map(|_| ())
    }

    /// Types `text` on the guest's physical keyboard (QEMU's virtio
    /// keyboard), shift and all, as someone at a laptop would.
    fn type_keys(&mut self, text: &str) -> Result {
        for c in text.chars() {
            let (shift, key) = match c {
                'a'..='z' | '0'..='9' => (false, c.to_string()),
                'A'..='Z' => (true, c.to_ascii_lowercase().to_string()),
                ' ' => (false, "spc".into()),
                '\n' => (false, "ret".into()),
                '\t' => (false, "tab".into()),
                '~' => (true, "grave_accent".into()),
                ',' => (false, "comma".into()),
                '.' => (false, "dot".into()),
                '!' => (true, "1".into()),
                '?' => (true, "slash".into()),
                '-' => (false, "minus".into()),
                '_' => (true, "minus".into()),
                '=' => (false, "equal".into()),
                '+' => (true, "equal".into()),
                '/' => (false, "slash".into()),
                ':' => (true, "semicolon".into()),
                '"' => (true, "apostrophe".into()),
                '{' => (true, "bracket_left".into()),
                '}' => (true, "bracket_right".into()),
                '@' => (true, "2".into()),
                '&' => (true, "7".into()),
                ';' => (false, "semicolon".into()),
                '(' => (true, "9".into()),
                ')' => (true, "0".into()),
                '>' => (true, "dot".into()),
                '<' => (true, "comma".into()),
                '[' => (false, "bracket_left".into()),
                ']' => (false, "bracket_right".into()),
                '*' => (true, "8".into()),
                '|' => (true, "backslash".into()),
                '\'' => (false, "apostrophe".into()),
                '`' => (false, "grave_accent".into()),
                '^' => (true, "6".into()),
                c => return Err(format!("no key for {c:?}")),
            };
            let mut keys = String::new();
            if shift {
                keys += r#"{"type":"qcode","data":"shift"},"#;
            }
            keys += &format!(r#"{{"type":"qcode","data":"{key}"}}"#);
            self.call(&format!(
                r#"{{"execute":"send-key","arguments":{{"keys":[{keys}]}}}}"#
            ))?;
            std::thread::sleep(Duration::from_millis(40));
        }
        Ok(())
    }

    /// Presses keys by their place (QEMU's names: `bracket_left`, `ralt`),
    /// each combination held together: `[&["shift", "6"], &["e"]]`.
    fn press_keys(&mut self, combinations: &[&[&str]]) -> Result {
        for keys in combinations {
            let keys: Vec<String> = keys
                .iter()
                .map(|k| format!(r#"{{"type":"qcode","data":"{k}"}}"#))
                .collect();
            self.call(&format!(
                r#"{{"execute":"send-key","arguments":{{"keys":[{}]}}}}"#,
                keys.join(",")
            ))?;
            std::thread::sleep(Duration::from_millis(40));
        }
        Ok(())
    }

    /// Taps out `text` on the on-screen keyboard of an app built from a
    /// view (Messages' conversation): it spans the window's bottom.
    fn type_text(&mut self, text: &str) -> Result {
        use pinnacle_layout::{Rect, keyboard};
        let (w, h) = self.app();
        let area = keyboard::area(Rect::new(0, 0, w, h));
        for c in text.chars() {
            let at = keyboard::key_center(area, c).ok_or(format!("no key for {c:?}"))?;
            self.tap_app(at)?;
        }
        Ok(())
    }
}

/// A free UDP port on this host, to forward to a guest.
/// Connects to the guest's listener through the forwarded `port`, sends a
/// line and returns the one that comes back.
fn knock(port: u16) -> Result<String> {
    use std::io::{BufRead, BufReader, Write};
    let address = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    let mut stream =
        std::net::TcpStream::connect_timeout(&address, Duration::from_secs(5)).map_err(|e| e.to_string())?;
    stream
        .set_read_timeout(Some(Duration::from_secs(5)))
        .map_err(|e| e.to_string())?;
    stream.write_all(b"ping\n").map_err(|e| e.to_string())?;
    let mut answer = String::new();
    BufReader::new(&stream)
        .read_line(&mut answer)
        .map_err(|e| e.to_string())?;
    Ok(answer.trim_end().to_string())
}

fn free_tcp_port() -> Result<u16> {
    let socket = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
    Ok(socket.local_addr().map_err(|e| e.to_string())?.port())
}

fn free_udp_port() -> Result<u16> {
    let socket = std::net::UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
    Ok(socket.local_addr().map_err(|e| e.to_string())?.port())
}

/// Two devices booted side by side, Ada and Bo, each the other's contact
/// and joined to the DHT through the other: their disks named by `tag`,
/// Bo's speaker written to `bo_audio`.
fn two_devices(tag: &str, bo_audio: Option<PathBuf>) -> Result<(Session, Session)> {
    use pinnacle_p2p::identity::Identity;
    let url = serve()?;
    let (ada_port, bo_port) = (free_udp_port()?, free_udp_port()?);
    let (ada, bo) = (Identity::from_seed([0xad; 32]), Identity::from_seed([0xb0; 32]));
    let (ada_card, bo_card) = (ada.card("Ada"), bo.card("Bo"));
    // As the p2p service names files: the key's first 16 bytes in hex.
    let hex = |k: &[u8; 32]| k[..16].iter().map(|b| format!("{b:02x}")).collect::<String>();
    let disk = |name: &str, me: &Identity, port: u16, peer_port: u16, peer: &pinnacle_p2p::identity::Card| {
        let path = root().join(format!("target/{tag}-{}.img", name.to_lowercase()));
        disks_at(
            &path,
            &url,
            &[
                ("/settings/identity".into(), me.seed().to_vec()),
                ("/settings/name".into(), name.as_bytes().to_vec()),
                (
                    "/settings/public-address".into(),
                    format!("10.0.2.2:{port}").into_bytes(),
                ),
                (
                    "/settings/peers".into(),
                    format!("10.0.2.2:{peer_port}").into_bytes(),
                ),
                (format!("/contacts/{}", hex(&peer.key)), peer.to_bytes().to_vec()),
            ],
        )
    };
    let ada_disk = disk("Ada", &ada, ada_port, bo_port, &bo_card)?;
    let bo_disk = disk("Bo", &bo, bo_port, ada_port, &ada_card)?;
    let a = Session::boot(
        &Guest {
            system: ada_disk,
            udp_forward: Some(ada_port),
            audio: None,
            bluetooth: None,
            modem: None,
            wifi: None,
            tcp_forward: None,
            data: Some(root().join(format!("target/{tag}-ada-data.img"))),
            hardware: false,
            backup: None,
            pinebook: false,
        },
        "ada| ",
    )?;
    let b = Session::boot(
        &Guest {
            system: bo_disk,
            udp_forward: Some(bo_port),
            audio: bo_audio,
            bluetooth: None,
            modem: None,
            wifi: None,
            tcp_forward: None,
            data: Some(root().join(format!("target/{tag}-bo-data.img"))),
            hardware: false,
            backup: None,
            pinebook: false,
        },
        "bo | ",
    )?;
    Ok((a, b))
}

/// Two devices, Ada and Bo, each with its own identity and the other as a
/// contact, each reachable at a forwarded UDP port of this host, as behind
/// a router that forwards one. They find each other through the DHT the
/// two of them make (Bo joins through Ada, Ada through Bo), and talk end to
/// end encrypted: Ada writes, Bo reads and answers. Screenshots of both go
/// into `target/demo-pair/`.
fn pair() -> Result {
    let dir = demo_dir("demo-pair")?;
    // What Bo's speaker plays, for the check at the end.
    let bo_wav = dir.join("bo.wav");
    let (mut a, mut b) = two_devices("pair", Some(bo_wav.clone()))?;
    a.wait_for("launcher: ")?;
    b.wait_for("launcher: ")?;

    a.tap_named("launcher: tile ", "Messages")?;
    a.wait_for("display: Messages connected")?;
    a.shot(&dir.join("1-ada-contacts.png"))?;
    a.tap_named("messages: button ", "contact-0")?;
    std::thread::sleep(Duration::from_millis(500));
    a.type_text("hoi bo, dit gaat zonder server\n")?;
    a.wait_for("messages: sent")?;
    b.wait_for("p2p: connected")?;
    std::thread::sleep(Duration::from_millis(800));
    a.shot(&dir.join("2-ada-sent.png"))?;

    b.tap_named("launcher: tile ", "Messages")?;
    b.wait_for("display: Messages connected")?;
    b.shot(&dir.join("3-bo-contacts.png"))?;
    b.tap_named("messages: button ", "contact-0")?;
    std::thread::sleep(Duration::from_millis(500));
    // Bo answers on a physical keyboard: the on-screen one steps aside.
    b.type_keys("Hoi Ada, het werkt!\n")?;
    b.wait_for("messages: sent")?;
    a.wait_for("messages: received")?;
    std::thread::sleep(Duration::from_millis(800));
    b.shot(&dir.join("4-bo-answered.png"))?;
    a.shot(&dir.join("5-ada-received.png"))?;

    // Bo has gone home when Ada writes again: a notification, whose tap
    // opens Messages.
    b.home()?;
    b.wait_for("launcher: ")?;
    a.type_text("tot zo\n")?;
    b.wait_for("display: notice from messages")?;
    std::thread::sleep(Duration::from_millis(300));
    b.shot(&dir.join("5b-bo-notified.png"))?;
    let (x, y) = pinnacle_layout::center(pinnacle_layout::shell::banner(b.screen.0));
    b.tap(x, y)?;
    b.wait_for("display: opening messages from its notice")?;
    std::thread::sleep(Duration::from_millis(600));
    b.shot(&dir.join("5c-bo-opened.png"))?;

    // A video call: Ada rings Bo from Calls; Bo's device opens Calls by
    // itself, Bo answers, and video goes both ways.
    a.home()?;
    a.wait_for("launcher: ")?;
    a.tap_named("launcher: tile ", "Calls")?;
    a.wait_for("display: Calls connected")?;
    a.tap_named("calls: button ", "call-0")?;
    a.wait_for("calls: calling Bo")?;
    b.wait_for("display: Calls connected")?;
    std::thread::sleep(Duration::from_millis(800));
    b.shot(&dir.join("6-bo-ringing.png"))?;
    b.tap_named("calls: button ", "answer")?;
    b.wait_for("calls: answered Ada")?;
    a.wait_for("calls: Bo answered")?;
    std::thread::sleep(Duration::from_secs(4));
    a.shot(&dir.join("7-ada-in-call.png"))?;
    b.shot(&dir.join("8-bo-in-call.png"))?;
    // Two more seconds of the call (what came out of Bo's speaker is
    // checked at the end), then Bo turns the camera off: Ada sees Bo's
    // mark where the video stopped. Ada hangs up, and both keep the call.
    std::thread::sleep(Duration::from_secs(2));
    b.tap_named("calls: button ", "camera")?;
    b.wait_for("calls: camera off")?;
    std::thread::sleep(Duration::from_secs(2));
    a.shot(&dir.join("8b-ada-sees-bos-camera-off.png"))?;
    a.tap_named("calls: button ", "end")?;
    a.wait_for("calls: the call with Bo ended after")?;
    b.wait_for("calls: the call with Ada ended after")?;
    std::thread::sleep(Duration::from_secs(3));

    // A voice call back: no video either way; Ada mutes, then Bo hangs
    // up. Ada's recent calls list both, and Bo's the video call again.
    b.tap_named("calls: button ", "voice-0")?;
    b.wait_for("calls: calling Ada, voice only")?;
    std::thread::sleep(Duration::from_millis(1500));
    a.shot(&dir.join("8c-ada-voice-ringing.png"))?;
    a.tap_named("calls: button ", "answer")?;
    a.wait_for("calls: answered Bo")?;
    a.tap_named("calls: button ", "mute")?;
    a.wait_for("calls: muted")?;
    std::thread::sleep(Duration::from_secs(2));
    a.shot(&dir.join("8d-ada-voice-muted.png"))?;
    b.tap_named("calls: button ", "end")?;
    a.wait_for("calls: the call with Bo ended after")?;
    std::thread::sleep(Duration::from_secs(3));
    a.tap_named("calls: button ", "tab-recent")?;
    a.wait_for("calls: recent calls")?;
    a.shot(&dir.join("8e-ada-recent-calls.png"))?;
    a.tap_named("calls: button ", "tab-people")?;
    a.wait_for("calls: people")?;
    pair_by_phone(&mut a, &mut b, &dir)?;
    drop(a);
    drop(b);
    expect_tone(&bo_wav, 442.0, 1.0)
}

/// The fallback to an ordinary call: each writes down the other's phone
/// number in Contacts (as people do: Ada saves Bo's in its national form),
/// Bo's network goes down, and Ada's call finds no Bo online: Calls dials
/// Bo's number on the simulated cell network instead, Bo's phone rings
/// with Ada's name, and Bo answers. Bo stays in Calls, which is told of a
/// phone call ringing in. Then Ada writes to Bo in Messages: Bo's device
/// does not say it arrived, so it goes to Bo's number as a text, which
/// both conversations mark as SMS, not encrypted.
fn pair_by_phone(a: &mut Session, b: &mut Session, dir: &Path) -> Result {
    const P: &str = "contacts: control ";
    // Ada's modem attached first; their numbers are the cell's.
    let (ada_number, bo_number) = (guest_number(0), guest_number(1));
    let national = format!("0{}", &bo_number[3..]);
    for (s, other, number) in [
        (&mut *a, "Bo", national.as_str()),
        (&mut *b, "Ada", ada_number.as_str()),
    ] {
        s.home()?;
        s.wait_for("launcher: ")?;
        s.tap_named("launcher: tile ", "Contacts")?;
        s.wait_for("display: Contacts connected")?;
        s.tap_named(P, &format!("contact {other}"))?;
        s.tap_named(P, "edit")?;
        s.tap_named(P, "field Phone 1")?;
        s.type_keys(number)?;
        s.tap_named(P, "save")?;
        s.wait_for(&format!("contacts: kept {other}"))?;
        std::thread::sleep(Duration::from_millis(600));
    }
    a.shot(&dir.join("9-ada-saved-bos-number.png"))?;
    // Bo back in Calls, then off the internet: the modem stays on.
    b.home()?;
    b.wait_for("launcher: ")?;
    b.tap_named("launcher: tile ", "Calls")?;
    b.wait_for("calls: in front")?;
    let reply = b.call(r#"{"execute": "set_link", "arguments": {"name": "net0", "up": false}}"#)?;
    if reply.contains("\"error\"") {
        return Err(format!("Bo's link stayed up: {reply}"));
    }
    a.home()?;
    a.wait_for("launcher: ")?;
    a.tap_named("launcher: tile ", "Calls")?;
    a.wait_for("calls: in front")?;
    a.tap_named("calls: button ", "call-0")?;
    a.wait_for("calls: calling Bo")?;
    a.wait_for("calls: Bo not reachable online; calling")?;
    std::thread::sleep(Duration::from_millis(800));
    a.shot(&dir.join("10-ada-calling-bos-phone.png"))?;
    b.wait_for(&format!("phone: a call from {ada_number}"))?;
    std::thread::sleep(Duration::from_millis(800));
    b.shot(&dir.join("11-bo-phone-rings.png"))?;
    b.tap_named("calls: button ", "answer")?;
    b.wait_for("calls: on the phone with Ada")?;
    a.wait_for("calls: on the phone with Bo")?;
    std::thread::sleep(Duration::from_secs(3));
    a.shot(&dir.join("12-ada-on-the-phone.png"))?;
    b.shot(&dir.join("13-bo-on-the-phone.png"))?;
    a.tap_named("calls: button ", "end")?;
    b.wait_for("calls: the phone call ended: Call ended")?;

    // Still offline, Bo is written to: no answer from Bo's device, so the
    // message goes to Bo's number as a text, and both conversations say so.
    // Messages, left open behind, is closed on both to start afresh.
    for s in [&mut *a, &mut *b] {
        s.home()?;
        s.wait_for("launcher: ")?;
        s.tap_named("launcher: tile ", "Messages")?;
        std::thread::sleep(Duration::from_millis(800));
        s.close()?;
        s.wait_for("display: closed Messages")?;
        s.wait_for("launcher: ")?;
    }
    a.tap_named("launcher: tile ", "Messages")?;
    a.wait_for("display: Messages connected")?;
    a.tap_named("messages: button ", "contact-0")?;
    a.wait_for("messages: opened Bo")?;
    a.type_keys("Je telefoon is offline, dit komt als sms\n")?;
    a.wait_for("messages: sent")?;
    a.wait_for(&format!("p2p: Bo not reachable online; texting {national}"))?;
    b.wait_for(&format!("phone: a text from {ada_number}"))?;
    b.wait_for("display: notice from messages")?;
    std::thread::sleep(Duration::from_millis(300));
    b.shot(&dir.join("15-bo-gets-a-text.png"))?;
    a.wait_for(&format!("messages: texted {national}"))?;
    std::thread::sleep(Duration::from_millis(800));
    a.shot(&dir.join("14-ada-texted-bo.png"))?;
    // The banner gone, Messages opened from the home screen.
    std::thread::sleep(Duration::from_secs(4));
    b.tap_named("launcher: tile ", "Messages")?;
    b.wait_for("display: Messages connected")?;
    b.tap_named("messages: button ", "contact-0")?;
    b.wait_for("messages: opened Ada")?;
    std::thread::sleep(Duration::from_millis(600));
    b.shot(&dir.join("16-bo-reads-it-from-ada.png"))?;
    Ok(())
}
/// Ada's terminal running commands on Bo's device (`remote Bo`), over the
/// p2p layer's encrypted stream: refused until Bo allows Ada in Settings,
/// then text, a table and an image come back, and Stop ends a command
/// there. Screenshots of both go into `target/demo-remote/`.
fn remote() -> Result {
    let dir = demo_dir("demo-remote")?;
    let (mut a, mut b) = two_devices("remote", None)?;
    a.wait_for("launcher: ")?;
    b.wait_for("launcher: ")?;

    // Ada points her terminal at Bo, who has not allowed her.
    a.tap_named("launcher: tile ", "Terminal")?;
    a.wait_for("terminal: ready")?;
    a.type_keys("remote Bo\n")?;
    a.wait_for("terminal: remote Bo")?;
    a.type_keys("info\n")?;
    a.wait_for("terminal: Bo › info ended")?;
    a.shot(&dir.join("1-ada-refused.png"))?;

    // Bo allows her: Settings, Remote access, Allow by Ada.
    b.tap_named("launcher: tile ", "Settings")?;
    b.wait_for("display: Settings connected")?;
    // The first card, This device, is laid out alike whatever follows it.
    b.tap_named("settings: button ", "remote")?;
    b.wait_for("settings: remote access")?;
    std::thread::sleep(Duration::from_millis(600));
    b.tap_named("settings: button ", "allow-0")?;
    b.wait_for("settings: Ada allowed")?;
    std::thread::sleep(Duration::from_millis(600));
    b.shot(&dir.join("2-bo-allows-ada.png"))?;
    b.home()?;
    b.wait_for("launcher: ")?;

    // Now it runs there, and Bo sees that it does: text, a table, an image.
    a.type_keys("info\n")?;
    b.wait_for("p2p: Ada runs info here")?;
    b.wait_for("display: notice from settings")?;
    std::thread::sleep(Duration::from_millis(300));
    b.shot(&dir.join("4-bo-notified.png"))?;
    a.wait_for("terminal: Bo › info ended (Some(0))")?;
    a.type_keys("devices\n")?;
    a.wait_for("terminal: Bo › devices ended (Some(0))")?;
    a.type_keys("palette\n")?;
    a.wait_for("terminal: Bo › palette ended (Some(0))")?;
    std::thread::sleep(Duration::from_millis(600));
    a.shot(&dir.join("3-ada-on-bo.png"))?;

    // Questions asked there, answered here; the last left for Stop.
    a.type_keys("ask\n")?;
    a.wait_for("terminal: asked What is your name?")?;
    a.type_keys("Ada\n")?;
    a.wait_for("terminal: asked Which fruit?")?;
    // Typed on a physical keyboard: the on-screen one stepped aside.
    a.tap_named("terminal: button ", "answer-1")?;
    a.wait_for("terminal: asked Is that your final answer?")?;
    std::thread::sleep(Duration::from_millis(400));
    a.shot(&dir.join("5-ada-answering.png"))?;
    a.tap_named("terminal: button ", "stop")?;
    a.wait_for("terminal: stopped Bo › ask")?;
    a.wait_for("terminal: Bo › ask ended")?;
    std::thread::sleep(Duration::from_millis(600));
    a.shot(&dir.join("6-ada-stopped.png"))?;
    Ok(())
}
/// Two devices of one person, Ada's laptop and her new phone, booted side
/// by side and joined to the DHT through each other, but not contacts:
/// the laptop's disk holds notes, a contact and a conversation, which go
/// into its vault at the first start; the phone's holds nothing of Ada's.
fn own_devices(tag: &str) -> Result<(Session, Session)> {
    use pinnacle_p2p::identity::Identity;
    let url = serve()?;
    let (laptop_port, phone_port) = (free_udp_port()?, free_udp_port()?);
    let (laptop, phone) = (Identity::from_seed([0xa1; 32]), Identity::from_seed([0xa2; 32]));
    let bo = Identity::from_seed([0xb0; 32]).card("Bo");
    let hex = |k: &[u8; 32]| k[..16].iter().map(|b| format!("{b:02x}")).collect::<String>();
    let mut conversation = Vec::new();
    for (out, text) in [(0u8, "Are you coming on Saturday?"), (1, "Yes, with cake")] {
        conversation.push(out);
        conversation.extend_from_slice(&1_764_400_000_000u64.to_le_bytes());
        conversation.extend_from_slice(&(text.len() as u16).to_le_bytes());
        conversation.extend_from_slice(text.as_bytes());
    }
    let disk = |name: &str, me: &Identity, port: u16, peer_port: u16, own: &[(String, Vec<u8>)]| {
        let path = root().join(format!(
            "target/{tag}-{}.img",
            if port == laptop_port { "laptop" } else { "phone" }
        ));
        let mut files = vec![
            ("/settings/identity".into(), me.seed().to_vec()),
            ("/settings/name".into(), name.as_bytes().to_vec()),
            (
                "/settings/public-address".into(),
                format!("10.0.2.2:{port}").into_bytes(),
            ),
            (
                "/settings/peers".into(),
                format!("10.0.2.2:{peer_port}").into_bytes(),
            ),
        ];
        files.extend_from_slice(own);
        disks_at(&path, &url, &files)
    };
    let laptop_own = [
        (
            "/data/notes/1".into(),
            b"Shopping list\nbread, cheese and apples".to_vec(),
        ),
        ("/data/notes/2".into(), b"Call the plumber on Monday".to_vec()),
        (format!("/contacts/{}", hex(&bo.key)), bo.to_bytes().to_vec()),
        (format!("/messages/{}", hex(&bo.key)), conversation),
    ];
    let laptop_disk = disk("Ada's laptop", &laptop, laptop_port, phone_port, &laptop_own)?;
    let phone_disk = disk("Ada's phone", &phone, phone_port, laptop_port, &[])?;
    let boot = |system: PathBuf, port: u16, name: &str, label: &str| {
        Session::boot(
            &Guest {
                system,
                udp_forward: Some(port),
                data: Some(root().join(format!("target/{tag}-{name}-data.img"))),
                ..Guest::default()
            },
            label,
        )
    };
    let a = boot(laptop_disk, laptop_port, "laptop", "laptop| ")?;
    let b = boot(phone_disk, phone_port, "phone", "phone | ")?;
    Ok((a, b))
}

/// Backup and sync (`docs/backup-and-sync.md`): Ada's laptop shows a code
/// in Settings → Devices, her new phone is given it, and the two link
/// through the DHT with no server. Then the laptop's vault comes over (two
/// notes, the contact Bo and the conversation with Bo), a note written on
/// the phone reaches the laptop, and one changed on the laptop reaches the
/// phone. Screenshots of both go into `target/demo-sync/`.
fn sync_demo() -> Result {
    const B: &str = "settings: button ";
    let dir = demo_dir("demo-sync")?;
    let (mut laptop, mut phone) = own_devices("sync")?;
    laptop.wait_for("launcher: ")?;
    phone.wait_for("launcher: ")?;

    // The laptop shows a code.
    laptop.tap_named("launcher: tile ", "Settings")?;
    laptop.wait_for("display: Settings connected")?;
    laptop.tap_named(B, "devices")?;
    laptop.wait_for("settings: devices")?;
    laptop.tap_named(B, "link-show")?;
    let line = laptop.wait_any(&["settings: showing link code "], boot_timeout())?;
    let code = line["settings: showing link code ".len()..].trim().to_string();
    std::thread::sleep(Duration::from_millis(800));
    laptop.shot(&dir.join("1-laptop-shows-a-code.png"))?;

    // The phone is given it.
    phone.tap_named("launcher: tile ", "Settings")?;
    phone.wait_for("display: Settings connected")?;
    phone.tap_named(B, "devices")?;
    phone.wait_for("settings: devices")?;
    phone.tap_named(B, "link-enter")?;
    std::thread::sleep(Duration::from_millis(500));
    phone.type_keys(&code)?;
    std::thread::sleep(Duration::from_millis(400));
    phone.shot(&dir.join("2-phone-types-it.png"))?;
    phone.type_keys("\n")?;
    phone.wait_for("settings: linked with Ada's laptop")?;
    laptop.wait_for("settings: linked with Ada's phone")?;

    // The laptop's vault comes over: the phone's p2p service reads the
    // contact it brought.
    phone.wait_for("sync: in step with Ada's laptop")?;
    phone.wait_for("p2p: read the contacts again")?;
    std::thread::sleep(Duration::from_millis(800));
    // The page again, now with the time of the sync.
    phone.tap_named(B, "back")?;
    phone.tap_named(B, "devices")?;
    std::thread::sleep(Duration::from_millis(800));
    phone.shot(&dir.join("3-phone-linked.png"))?;
    laptop.shot(&dir.join("4-laptop-linked.png"))?;

    // On the phone: the laptop's notes, and the conversation with Bo.
    phone.home()?;
    phone.wait_for("launcher: ")?;
    phone.tap_named("launcher: tile ", "Notes")?;
    phone.wait_for("display: Notes connected")?;
    std::thread::sleep(Duration::from_millis(800));
    phone.shot(&dir.join("5-phone-has-the-notes.png"))?;
    // A new note, written on the phone.
    phone.tap_named("notes: button ", "new")?;
    phone.wait_for("notes: new 3")?;
    phone.type_keys("Written on the phone")?;
    phone.wait_for("notes: saved 3")?;
    phone.close()?;
    phone.wait_for("display: closed Notes")?;
    phone.tap_named("launcher: tile ", "Messages")?;
    phone.wait_for("display: Messages connected")?;
    phone.tap_named("messages: button ", "contact-0")?;
    std::thread::sleep(Duration::from_millis(800));
    phone.shot(&dir.join("6-phone-has-the-conversation.png"))?;

    // It reaches the laptop.
    laptop.wait_for("sync: changed /apps/notes/3")?;
    laptop.home()?;
    laptop.wait_for("launcher: ")?;
    laptop.tap_named("launcher: tile ", "Notes")?;
    laptop.wait_for("display: Notes connected")?;
    std::thread::sleep(Duration::from_millis(800));
    laptop.shot(&dir.join("7-laptop-has-the-phones-note.png"))?;
    Ok(())
}

/// A backup to a disk of its own (`docs/backup-and-sync.md`): Ada's phone,
/// with two notes, backs its vault up to a stick labelled `backup`; then a
/// new phone, its vault empty, restores from the same stick with the old
/// phone's password, and its Notes shows both notes. Screenshots go into
/// `target/demo-backup/`.
fn backup_demo() -> Result {
    const B: &str = "settings: button ";
    let dir = demo_dir("demo-backup")?;
    let url = serve()?;
    let stick = root().join("target/backup-stick.img");
    new_image(&stick, 64, "backup")?;
    let phone = |name: &str, notes: bool| -> Result<Session> {
        let system = root().join(format!("target/backup-{name}.img"));
        let mut files = vec![("/settings/name".to_string(), name.as_bytes().to_vec())];
        if notes {
            files.push((
                "/data/notes/1".into(),
                b"Shopping list\nbread, cheese and apples".to_vec(),
            ));
            files.push(("/data/notes/2".into(), b"Call the plumber on Monday".to_vec()));
        }
        let system = disks_at(&system, &url, &files)?;
        let data = root().join(format!("target/backup-{name}-data.img"));
        let _ = std::fs::remove_file(&data);
        Session::boot(
            &Guest {
                system,
                data: Some(data),
                backup: Some(stick.clone()),
                ..Guest::default()
            },
            &format!("{name}| "),
        )
    };
    let settle = || std::thread::sleep(Duration::from_millis(800));

    let mut old = phone("old", true)?;
    old.wait_for("launcher: ")?;
    old.tap_named("launcher: tile ", "Settings")?;
    old.wait_for("display: Settings connected")?;
    old.tap_named(B, "devices")?;
    old.wait_for("settings: devices")?;
    settle();
    old.shot(&dir.join("1-before-the-backup.png"))?;
    old.tap_named(B, "backup")?;
    settle();
    old.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
    old.wait_for("settings: backed up 2 files")?;
    settle();
    old.shot(&dir.join("2-backed-up.png"))?;
    drop(old);

    // A new phone: the stick is all it shares with the old one.
    let mut new = phone("new", false)?;
    new.wait_for("launcher: ")?;
    new.tap_named("launcher: tile ", "Settings")?;
    new.wait_for("display: Settings connected")?;
    new.tap_named(B, "devices")?;
    new.wait_for("settings: devices")?;
    new.tap_named(B, "restore")?;
    settle();
    new.type_keys("not the password\n")?;
    new.wait_for("settings: no backup that password opens")?;
    new.tap_named(B, "restore")?;
    settle();
    new.type_keys(&format!("{DEMO_PASSPHRASE}\n"))?;
    new.wait_for("settings: restored 2 files, 2 written")?;
    settle();
    new.shot(&dir.join("3-restored.png"))?;
    new.home()?;
    new.wait_for("launcher: ")?;
    new.tap_named("launcher: tile ", "Notes")?;
    new.wait_for("display: Notes connected")?;
    settle();
    new.shot(&dir.join("4-the-notes-are-back.png"))?;
    Ok(())
}

/// What a WAV file QEMU's `wav` audio backend wrote holds: the frequency
/// (Hz) and length (seconds) of the longest stretch of sound in it, found
/// by its zero crossings, or None when it holds no sound.
fn wav_tone(path: &Path) -> Result<Option<(f64, f64)>> {
    let (left, rate) = wav_left(path)?;
    let longest = sounds(&left, rate).into_iter().max_by_key(|(from, to)| to - from);
    Ok(longest.map(|(from, to)| tone_of(&left[from..=to], rate)))
}

/// The last sound in a WAV file QEMU wrote: its frequency (Hz), length
/// (seconds) and loudest sample, or None when it holds no sound.
fn wav_last(path: &Path) -> Result<Option<(f64, f64, i32)>> {
    let (left, rate) = wav_left(path)?;
    Ok(sounds(&left, rate).last().map(|&(from, to)| {
        let stretch = &left[from..=to];
        let (hz, seconds) = tone_of(stretch, rate);
        (hz, seconds, stretch.iter().map(|s| s.abs()).max().unwrap_or(0))
    }))
}

/// The stretches of sound in `left`, in order: frames louder than the
/// threshold, joined across gaps shorter than 50 ms; none of two frames
/// or fewer.
fn sounds(left: &[i32], rate: usize) -> Vec<(usize, usize)> {
    const LOUD: i32 = 800;
    let gap = rate / 20;
    let mut found = Vec::new();
    let mut start = None;
    let mut last_loud = 0;
    for (i, &s) in left.iter().enumerate() {
        if s.abs() > LOUD {
            if start.is_none() {
                start = Some(i);
            }
            last_loud = i;
        } else if let Some(from) = start
            && i - last_loud > gap
        {
            found.push((from, last_loud));
            start = None;
        }
    }
    if let Some(from) = start {
        found.push((from, last_loud));
    }
    found.retain(|(from, to)| to > &(from + 2));
    found
}

/// A stretch's frequency, by its zero crossings, and its length in seconds.
fn tone_of(stretch: &[i32], rate: usize) -> (f64, f64) {
    let crossings = stretch.windows(2).filter(|w| (w[0] < 0) != (w[1] < 0)).count();
    let seconds = stretch.len() as f64 / rate as f64;
    (crossings as f64 / 2.0 / seconds, seconds)
}

/// A WAV file's left channel, 16-bit, and its rate. The header's sizes are
/// ignored: QEMU fills them in only when it exits by itself.
fn wav_left(path: &Path) -> Result<(Vec<i32>, usize)> {
    let data = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
    if data.len() < 44 || &data[..4] != b"RIFF" || &data[8..12] != b"WAVE" {
        return Err(format!("{}: not a WAV file", path.display()));
    }
    let mut at = 12;
    let (mut channels, mut rate, mut bits) = (0usize, 0usize, 0usize);
    let mut samples: Option<&[u8]> = None;
    while at + 8 <= data.len() {
        let id = &data[at..at + 4];
        let size = u32::from_le_bytes(data[at + 4..at + 8].try_into().unwrap()) as usize;
        let body = &data[at + 8..];
        match id {
            b"fmt " if body.len() >= 16 => {
                channels = u16::from_le_bytes([body[2], body[3]]) as usize;
                rate = u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize;
                bits = u16::from_le_bytes([body[14], body[15]]) as usize;
            }
            b"data" => {
                // A size of 0 (or more than there is): the rest of the file.
                let n = if size == 0 || size > body.len() {
                    body.len()
                } else {
                    size
                };
                samples = Some(&body[..n]);
                break;
            }
            _ => {}
        }
        at += 8 + size.max(1).next_multiple_of(2);
    }
    let (Some(samples), true) = (samples, channels > 0 && rate > 0 && bits == 16) else {
        return Err(format!("{}: no 16-bit samples", path.display()));
    };
    let frame = channels * 2;
    let left: Vec<i32> = samples
        .chunks_exact(frame)
        .map(|f| i32::from(i16::from_le_bytes([f[0], f[1]])))
        .collect();
    Ok((left, rate))
}

/// Checks a WAV holds a tone of about `hz` for at least `seconds`.
fn expect_tone(path: &Path, hz: f64, seconds: f64) -> Result {
    match wav_tone(path)? {
        Some((f, s)) if (f - hz).abs() <= hz * 0.03 && s >= seconds => {
            println!("ok   {}: a tone of {f:.0} Hz for {s:.2} s", path.display());
            Ok(())
        }
        Some((f, s)) => Err(format!(
            "{}: a tone of {f:.0} Hz for {s:.2} s, wanted {hz:.0} Hz for {seconds} s",
            path.display()
        )),
        None => Err(format!("{}: no sound in it", path.display())),
    }
}

/// The identity resolving key of the air's `n`th device (from 1).
fn air_irk(n: u8) -> [u8; 16] {
    [0x1d ^ n; 16]
}

/// The air a guest's Bluetooth controller is in: a simulated controller
/// behind the guest's serial port (a Unix socket QEMU serves), and devices
/// of our own beside it, each a host of its own: "Pinnacle Test" with its
/// name, a battery at 87 % and a contact card; a keyboard (HID over GATT,
/// pairing by a code typed on it, [`SimAir::type_passkey`], then typing,
/// [`SimAir::type_text`]); a heart-rate sensor whose rate ticks. Several
/// guests may share one air (`pair`).
struct SimAir {
    inner: std::sync::Arc<std::sync::Mutex<AirInner>>,
}

struct AirInner {
    air: pinnacle_bt::sim::Air,
    /// Local devices: their controller's index in the air and their host.
    devices: Vec<(usize, pinnacle_bt::Host)>,
    /// Guests: their controller's index and the socket to the guest.
    guests: Vec<(usize, std::os::unix::net::UnixStream)>,
    start: Instant,
    beats: u32,
    /// The Pinnacle's controller index and its own card.
    devices_card: (usize, Vec<u8>),
    /// The keyboard's pairing waiting for its code: its connection.
    passkey_wanted: Option<u16>,
    /// Boot reports the keyboard is still to send, one a step.
    reports: std::collections::VecDeque<[u8; 8]>,
}

/// The keyboard, of the air's own devices (from 0).
const AIR_KEYBOARD: usize = 1;

/// A character as a keyboard's boot report holds it: Shift and its usage
/// (US layout, the one Pinnacle starts with).
fn boot_usage(c: char) -> Option<(bool, u8)> {
    Some(match c {
        'a'..='z' => (false, 4 + (c as u8 - b'a')),
        'A'..='Z' => (true, 4 + (c as u8 - b'A')),
        '1'..='9' => (false, 0x1e + (c as u8 - b'1')),
        '0' => (false, 0x27),
        '\n' => (false, 0x28),
        ' ' => (false, 0x2c),
        '.' => (false, 0x37),
        ',' => (false, 0x36),
        '!' => (true, 0x1e),
        _ => return None,
    })
}

impl SimAir {
    fn new() -> SimAir {
        use pinnacle_bt::gatt::{self, Characteristic, Service, Uuid};
        let mut air = pinnacle_bt::sim::Air::default();
        let mut devices = Vec::new();
        // Each pairs as such a device would: the Pinnacle comparing numbers
        // (its person always says yes), the keyboard wanting a code typed,
        // the sensor with no screen at all.
        let mut add = |air: &mut pinnacle_bt::sim::Air, n: u8, name: &str, services: Vec<Service>, io: u8| {
            let i = air.add(pinnacle_bt::Address([n, 0x5e, 0x1d, 0x00, 0x4e, 0xd0]));
            let mut host = pinnacle_bt::Host::new(name, services);
            host.enable_pairing([n; 32], io);
            host.set_identity(air_irk(n));
            host.advertise(true);
            devices.push((i, host));
        };
        let battery = |level: u8| {
            Service::new(
                Uuid::Short(gatt::BATTERY),
                vec![Characteristic::new(
                    Uuid::Short(gatt::BATTERY_LEVEL),
                    gatt::PROP_READ | gatt::PROP_NOTIFY,
                    &[level],
                )],
            )
        };
        let test_card = pinnacle_p2p::identity::Identity::from_seed([0x7e; 32]).card("Pinnacle Test");
        add(
            &mut air,
            1,
            "Pinnacle Test",
            vec![
                battery(87),
                Service::new(
                    Uuid::Long(gatt::PINNACLE_SERVICE),
                    vec![Characteristic::new(
                        Uuid::Long(gatt::PINNACLE_CARD),
                        gatt::PROP_READ | gatt::PROP_WRITE,
                        &test_card.to_bytes(),
                    )],
                ),
            ],
            pinnacle_bt::smp::DISPLAY_YES_NO,
        );
        add(
            &mut air,
            2,
            "Keyboard K380",
            vec![pinnacle_bt::hogp::keyboard_service(), battery(62)],
            pinnacle_bt::smp::KEYBOARD_ONLY,
        );
        add(
            &mut air,
            3,
            "Heart Rate Sensor",
            vec![
                Service::new(
                    Uuid::Short(gatt::HEART_RATE),
                    vec![Characteristic::new(
                        Uuid::Short(gatt::HEART_RATE_MEASUREMENT),
                        gatt::PROP_NOTIFY,
                        &[0, 72],
                    )],
                ),
                battery(95),
            ],
            pinnacle_bt::smp::NO_INPUT_NO_OUTPUT,
        );
        // Pinnacle Test was added first.
        let pinnacle_index = devices[0].0;
        let inner = std::sync::Arc::new(std::sync::Mutex::new(AirInner {
            air,
            devices,
            guests: Vec::new(),
            start: Instant::now(),
            beats: 0,
            devices_card: (pinnacle_index, test_card.to_bytes().to_vec()),
            passkey_wanted: None,
            reports: std::collections::VecDeque::new(),
        }));
        let worker = inner.clone();
        std::thread::spawn(move || {
            loop {
                std::thread::sleep(Duration::from_millis(5));
                let Ok(mut inner) = worker.lock() else { return };
                if std::sync::Arc::strong_count(&worker) == 1 {
                    return;
                }
                inner.step();
            }
        });
        SimAir { inner }
    }

    /// The `n`th device of our own (from 0, in the order added) moves to a
    /// new private address made from its identity key, as a phone does every
    /// few minutes; the old one no longer answers. Returns the new address.
    fn move_device(&self, n: usize) -> Result<pinnacle_bt::Address> {
        let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
        let i = inner.devices.get(n).ok_or("no such device")?.0;
        let prand = (inner.start.elapsed().as_nanos() as u32).to_le_bytes();
        let address = pinnacle_bt::Address(pinnacle_bt::smp::private_address(
            &air_irk(n as u8 + 1),
            [prand[0], prand[1], prand[2]],
        ));
        inner.air.controllers[i].move_to(address);
        Ok(address)
    }

    /// The keyboard's person types the code the guest shows, then Enter.
    fn type_passkey(&self, passkey: u32) -> Result {
        let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
        let connection = inner
            .passkey_wanted
            .take()
            .ok_or("the keyboard asks for no code")?;
        inner.devices[AIR_KEYBOARD].1.enter_passkey(connection, passkey);
        Ok(())
    }

    /// Types `text` on the keyboard: a press and a release a character.
    fn type_text(&self, text: &str) -> Result {
        let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
        for c in text.chars() {
            let (shift, usage) = boot_usage(c).ok_or_else(|| format!("no key for {c:?}"))?;
            inner
                .reports
                .push_back([u8::from(shift) << 1, 0, usage, 0, 0, 0, 0, 0]);
            inner.reports.push_back([0; 8]);
        }
        Ok(())
    }

    /// The socket path for a new guest; QEMU serves it, this connects.
    fn socket_for_guest(&self) -> PathBuf {
        let n = SOCKETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        std::env::temp_dir().join(format!("pinnacle-bt-{}-{n}", std::process::id()))
    }

    /// Connects to a guest's port once QEMU listens on it.
    fn attach(&self, socket: &Path) -> Result {
        let deadline = Instant::now() + Duration::from_secs(5);
        let stream = loop {
            match std::os::unix::net::UnixStream::connect(socket) {
                Ok(s) => break s,
                Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
                Err(e) => return Err(format!("the Bluetooth port {}: {e}", socket.display())),
            }
        };
        stream.set_nonblocking(true).map_err(|e| e.to_string())?;
        let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
        let n = inner.guests.len() as u8;
        let i = inner
            .air
            .add(pinnacle_bt::Address([0x10 + n, 0x00, 0x00, 0x00, 0x7a, 0xc0]));
        inner.guests.push((i, stream));
        Ok(())
    }
}

impl AirInner {
    fn step(&mut self) {
        use std::io::{Read, Write};
        let now = self.start.elapsed().as_millis() as u64;
        let mut buffer = [0u8; 4096];
        for (i, stream) in &mut self.guests {
            loop {
                match stream.read(&mut buffer) {
                    Ok(0) => break,
                    Ok(n) => self.air.controllers[*i].receive(&buffer[..n]),
                    Err(_) => break,
                }
            }
        }
        for (i, host) in &mut self.devices {
            while let Some(bytes) = host.transmit() {
                self.air.controllers[*i].receive(&bytes);
            }
        }
        self.air.step();
        for (i, stream) in &mut self.guests {
            while let Some(bytes) = self.air.controllers[*i].transmit() {
                let _ = stream.write_all(&bytes);
            }
        }
        for (i, host) in &mut self.devices {
            while let Some(bytes) = self.air.controllers[*i].transmit() {
                host.receive(&bytes, now);
            }
            host.poll(now);
            while let Some(event) = host.event() {
                match event {
                    pinnacle_bt::Event::Confirm { connection, .. } => host.confirm(connection, true),
                    // A card handed to the Pinnacle: taken, its own kept,
                    // as the `bt` service does.
                    pinnacle_bt::Event::Changed { handle, .. } if *i == self.devices_card.0 => {
                        host.set_value(handle, &self.devices_card.1);
                    }
                    // The keyboard waits for its person to type the code.
                    pinnacle_bt::Event::Passkey {
                        connection,
                        passkey: None,
                        ..
                    } => self.passkey_wanted = Some(connection),
                    _ => {}
                }
            }
        }
        // The keyboard's keys, a report a step.
        if let Some(report) = self.reports.pop_front() {
            let keyboard = &mut self.devices[AIR_KEYBOARD].1;
            let input = keyboard.table().value_handle(
                pinnacle_bt::Uuid::Short(pinnacle_bt::gatt::HUMAN_INTERFACE_DEVICE),
                pinnacle_bt::Uuid::Short(pinnacle_bt::gatt::BOOT_KEYBOARD_INPUT),
            );
            if let Some(input) = input {
                keyboard.set_value(input, &report);
            }
        }
        // The heart-rate sensor's measurement, once a second.
        if now / 1000 > u64::from(self.beats) {
            self.beats = (now / 1000) as u32;
            let rate = 68 + (self.beats % 9) as u8;
            if let Some((_, sensor)) = self.devices.get_mut(2) {
                let handle = sensor.table().value_handle(
                    pinnacle_bt::Uuid::Short(pinnacle_bt::gatt::HEART_RATE),
                    pinnacle_bt::Uuid::Short(pinnacle_bt::gatt::HEART_RATE_MEASUREMENT),
                );
                if let Some(handle) = handle {
                    sensor.set_value(handle, &[0, rate]);
                }
            }
        }
    }
}

/// The Bluetooth app, driven like a person: the devices around (the
/// simulated air's), one of them opened (a keyboard: its make, model and
/// battery), then the Pinnacle nearby, added as a contact and paired (the
/// number compared, the link private), found again first in the list, and
/// private again when opened, with no question; then the keyboard, paired
/// by the code shown typed on it, typing a note in Notes.
fn bluetooth_demo(s: &mut Session, dir: &Path) -> Result {
    const B: &str = "bluetooth: button ";
    s.tap_named("launcher: tile ", "Bluetooth")?;
    s.wait_for("display: Bluetooth connected")?;
    // Three devices advertise in the air; the list fills within a second.
    std::thread::sleep(Duration::from_millis(1200));
    s.shot(&dir.join("bt-1-devices.png"))?;
    // The rows come in the order heard: Pinnacle Test first, the keyboard
    // second, the sensor third — the air advertises them in that order.
    s.tap_named(B, "device-1")?;
    s.wait_for("bt: connected to")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("bt-2-keyboard.png"))?;
    s.tap_named(B, "back")?;
    std::thread::sleep(Duration::from_millis(600));
    s.tap_named(B, "device-0")?;
    s.wait_for("bt: connected to")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("bt-3-pinnacle.png"))?;
    s.tap_named(B, "add-contact")?;
    s.wait_for("bluetooth: added Pinnacle Test as a contact")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("bt-4-contact-added.png"))?;
    s.tap_named(B, "pair")?;
    s.wait_for("bt: pairing with")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("bt-5-compare.png"))?;
    s.tap_named(B, "ask-yes")?;
    s.wait_for("bt: paired with Pinnacle Test")?;
    std::thread::sleep(Duration::from_millis(400));
    s.shot(&dir.join("bt-6-paired.png"))?;
    s.tap_named(B, "disconnect")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("bt-7-remembered.png"))?;
    // Opened again: private at once, nothing asked.
    s.tap_named(B, "device-0")?;
    s.wait_for("bt: connected to")?;
    s.wait_for("bt: the link to")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("bt-8-private-again.png"))?;
    s.tap_named(B, "disconnect")?;
    std::thread::sleep(Duration::from_millis(800));
    // It moves to a new private address, as a phone does every few
    // minutes: still the paired one nearby, and private again when opened,
    // with no number to compare. The old address no longer answers, so a
    // connection at all went to the new one.
    let moved = air().move_device(0)?;
    println!("xtask: Pinnacle Test moved to {}", moved.text());
    std::thread::sleep(Duration::from_millis(1200));
    s.shot(&dir.join("bt-9-moved.png"))?;
    s.tap_named(B, "device-0")?;
    s.wait_for("bt: connected to")?;
    s.wait_for("bt: the link to")?;
    std::thread::sleep(Duration::from_millis(800));
    s.shot(&dir.join("bt-10-moved-private.png"))?;
    s.tap_named(B, "disconnect")?;
    std::thread::sleep(Duration::from_millis(400));
    // The keyboard, paired by a code shown here and typed on it, then
    // typing into Notes. Its row behind the paired one depends on the order
    // heard since Pinnacle Test moved: the one that opens as the keyboard.
    let mut found = false;
    for row in ["device-1", "device-2"] {
        s.tap_named(B, row)?;
        let line = s.wait_any(&["bluetooth: connecting to "], boot_timeout())?;
        s.wait_for("bt: connected to")?;
        if line.ends_with("Keyboard K380") {
            found = true;
            break;
        }
        s.tap_named(B, "back")?;
        std::thread::sleep(Duration::from_millis(600));
    }
    if !found {
        return Err("the keyboard is not in the list".into());
    }
    std::thread::sleep(Duration::from_millis(800));
    s.tap_named(B, "pair")?;
    let line = s.wait_any(&["bt: pairing with Keyboard K380: type "], boot_timeout())?;
    let passkey: u32 = line
        .trim_start_matches("bt: pairing with Keyboard K380: type ")
        .split(' ')
        .next()
        .and_then(|digits| digits.parse().ok())
        .ok_or_else(|| format!("no code in {line:?}"))?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("bt-11-keyboard-code.png"))?;
    air().type_passkey(passkey)?;
    s.wait_for("bt: paired with Keyboard K380")?;
    s.wait_for("bt: keys from")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("bt-12-keyboard-paired.png"))?;
    // Back to the list and out of the app: the keyboard stays connected.
    s.tap_named(B, "back")?;
    std::thread::sleep(Duration::from_millis(400));
    s.home()?;
    s.tap_named("launcher: tile ", "Notes")?;
    s.wait_for("display: Notes connected")?;
    s.tap_named("notes: button ", "new")?;
    s.wait_for("notes: new ")?;
    air().type_text("Typed on a Bluetooth keyboard, paired by a code.")?;
    s.wait_for("notes: saved ")?;
    std::thread::sleep(Duration::from_millis(600));
    s.shot(&dir.join("bt-13-notes.png"))?;
    s.home()
}

/// The Bluetooth app alone, as `demo` drives it.
fn bluetooth_only_demo() -> Result {
    let dir = demo_dir("demo-bluetooth")?;
    let mut s = Session::start()?;
    s.wait_for(&home_apps(0))?;
    bluetooth_demo(&mut s, &dir)
}

/// The one air every guest of this run is in.
fn air() -> &'static SimAir {
    static AIR: std::sync::OnceLock<SimAir> = std::sync::OnceLock::new();
    AIR.get_or_init(SimAir::new)
}

/// The cell network a guest's modem is on: a simulated modem behind the
/// guest's serial port (a Unix socket QEMU serves), each guest's SIM the
/// number [`guest_number`] gives in the order they attach, and numbers
/// outside it: a landline that answers after two seconds
/// ([`LANDLINE`]), and one that is always busy. Several guests share one
/// network (`pair`), and call each other by number.
struct SimCell {
    inner: std::sync::Arc<std::sync::Mutex<CellInner>>,
}

/// The number outside that answers: what the self-check calls.
const LANDLINE: &str = "+31201234567";

/// The number of the `n`th guest's SIM (from 0).
fn guest_number(n: usize) -> String {
    format!("+316100000{:02}", n + 1)
}

/// A friend on an ordinary phone, who answers texts: what `sms-demo`
/// writes to.
const FRIEND: &str = "+31620000001";
/// Someone outside who texts unasked (`sms-demo`): a parcel service.
const PARCELS: &str = "+3197010203040";

/// What a number outside texts back to `text`, if it does: the landline
/// says what it heard (the self-check), the friend answers as a friend.
fn reply_to(to: &str, text: &str, nth: usize) -> Option<String> {
    match to {
        LANDLINE => Some(format!("heard: {text}")),
        FRIEND => Some(["Yes! I'll bring dessert", "See you at eight then", "Sure"][nth.min(2)].to_string()),
        _ => None,
    }
}

struct CellInner {
    network: pinnacle_modem::sim::Network,
    /// Guests: their modem's index and the socket to the guest.
    guests: Vec<(usize, std::os::unix::net::UnixStream)>,
    start: Instant,
    /// Texts back that are due: when, the number outside, the modem, the text.
    replies: Vec<(u64, usize, usize, String)>,
    /// How many texts each number outside has answered.
    answered: Vec<usize>,
}

impl SimCell {
    fn new() -> SimCell {
        use pinnacle_modem::sim::{Behaviour, Network};
        let mut network = Network::default();
        network.add_outside(LANDLINE, Behaviour::Answers { after_ms: 2000 });
        network.add_outside("+31207654321", Behaviour::Busy);
        network.add_outside(FRIEND, Behaviour::Silent);
        network.add_outside(PARCELS, Behaviour::Silent);
        let answered = vec![0; network.outside.len()];
        let inner = std::sync::Arc::new(std::sync::Mutex::new(CellInner {
            network,
            guests: Vec::new(),
            start: Instant::now(),
            replies: Vec::new(),
            answered,
        }));
        let worker = inner.clone();
        std::thread::spawn(move || {
            loop {
                std::thread::sleep(Duration::from_millis(5));
                let Ok(mut inner) = worker.lock() else { return };
                if std::sync::Arc::strong_count(&worker) == 1 {
                    return;
                }
                inner.step();
            }
        });
        SimCell { inner }
    }

    /// The socket path for a new guest; QEMU serves it, this connects.
    fn socket_for_guest(&self) -> PathBuf {
        let n = SOCKETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        std::env::temp_dir().join(format!("pinnacle-modem-{}-{n}", std::process::id()))
    }

    /// Connects to a guest's port once QEMU listens on it; returns the
    /// number its SIM has.
    fn attach(&self, socket: &Path) -> Result<String> {
        let deadline = Instant::now() + Duration::from_secs(5);
        let stream = loop {
            match std::os::unix::net::UnixStream::connect(socket) {
                Ok(s) => break s,
                Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
                Err(e) => return Err(format!("the modem port {}: {e}", socket.display())),
            }
        };
        stream.set_nonblocking(true).map_err(|e| e.to_string())?;
        let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
        let number = guest_number(inner.guests.len());
        let i = inner.network.add(&number, None);
        inner.guests.push((i, stream));
        Ok(number)
    }

    /// Takes the `n`th guest's modem off the network, or puts it back.
    #[allow(dead_code)]
    fn set_registered(&self, n: usize, registered: bool) {
        if let Ok(mut inner) = self.inner.lock()
            && let Some(&(i, _)) = inner.guests.get(n)
        {
            inner.network.set_registered(i, registered);
        }
    }

    /// The number outside `from` texts the `n`th guest.
    fn text_guest(&self, from: &str, n: usize, text: &str) -> Result {
        let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
        let o = inner
            .network
            .outside
            .iter()
            .position(|o| o.number == from)
            .ok_or("no such number")?;
        let &(i, _) = inner.guests.get(n).ok_or("no such guest")?;
        inner.network.text_from_outside(o, i, text);
        Ok(())
    }
}

impl CellInner {
    fn step(&mut self) {
        use std::io::{Read, Write};
        let now = self.start.elapsed().as_millis() as u64;
        let mut buffer = [0u8; 4096];
        for (i, stream) in &mut self.guests {
            loop {
                match stream.read(&mut buffer) {
                    Ok(0) => break,
                    Ok(n) => self.network.modems[*i].receive(&buffer[..n]),
                    Err(_) => break,
                }
            }
        }
        self.network.step(now);
        // Texts to numbers outside, answered a moment later.
        for o in 0..self.network.outside.len() {
            for (from, text) in std::mem::take(&mut self.network.outside[o].texts) {
                let to = &self.network.outside[o].number;
                let Some(reply) = reply_to(to, &text, self.answered[o]) else {
                    continue;
                };
                self.answered[o] += 1;
                let modem = self
                    .network
                    .modems
                    .iter()
                    .position(|m| pinnacle_modem::number::same(&m.number, &from));
                if let Some(m) = modem {
                    self.replies.push((now + 1500, o, m, reply));
                }
            }
        }
        let (due, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.replies)
            .into_iter()
            .partition(|r| r.0 <= now);
        self.replies = later;
        for (_, o, m, text) in due {
            self.network.text_from_outside(o, m, &text);
        }
        for (i, stream) in &mut self.guests {
            while let Some(bytes) = self.network.modems[*i].transmit() {
                let _ = stream.write_all(&bytes);
            }
        }
    }
}

fn cell() -> &'static SimCell {
    static CELL: std::sync::OnceLock<SimCell> = std::sync::OnceLock::new();
    CELL.get_or_init(SimCell::new)
}

/// The access points every guest's Wi-Fi radio hears: a simulated radio
/// (`pinnacle_wifi::sim`) behind each guest's port, all near the same
/// four networks: a home one behind a password ([`WIFI_HOME`]), an open
/// one, a neighbour's on WPA3, and an office's that wants an account.
struct SimWifi {
    radios:
        std::sync::Arc<std::sync::Mutex<Vec<(pinnacle_wifi::sim::Radio, std::os::unix::net::UnixStream)>>>,
}

/// The network `wifi-demo` joins, and its password.
const WIFI_HOME: (&str, &str) = ("Harbour House", "salt and pepper 7");

impl SimWifi {
    fn new() -> SimWifi {
        let radios: std::sync::Arc<
            std::sync::Mutex<Vec<(pinnacle_wifi::sim::Radio, std::os::unix::net::UnixStream)>>,
        > = Default::default();
        let worker = radios.clone();
        std::thread::spawn(move || {
            use std::io::{Read, Write};
            let mut buffer = [0u8; 4096];
            loop {
                std::thread::sleep(Duration::from_millis(5));
                if std::sync::Arc::strong_count(&worker) == 1 {
                    return;
                }
                let Ok(mut radios) = worker.lock() else { return };
                for (radio, stream) in radios.iter_mut() {
                    while let Ok(n @ 1..) = stream.read(&mut buffer) {
                        radio.receive(&buffer[..n]);
                    }
                    while let Some(bytes) = radio.transmit() {
                        let _ = stream.write_all(&bytes);
                    }
                }
            }
        });
        SimWifi { radios }
    }

    fn access_points() -> Vec<pinnacle_wifi::sim::AccessPoint> {
        use pinnacle_wifi::Security;
        use pinnacle_wifi::sim::AccessPoint;
        vec![
            AccessPoint::new(WIFI_HOME.0, -47, Security::Wpa2, WIFI_HOME.1),
            AccessPoint::new("Library", -66, Security::Open, ""),
            AccessPoint::new("Neighbours 5G", -78, Security::Wpa3, "not for you"),
            AccessPoint::new("Office", -88, Security::Enterprise, ""),
        ]
    }

    fn socket_for_guest(&self) -> PathBuf {
        let n = SOCKETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        std::env::temp_dir().join(format!("pinnacle-wifi-{}-{n}", std::process::id()))
    }

    /// Connects to a guest's port once QEMU listens on it.
    fn attach(&self, socket: &Path) -> Result {
        let deadline = Instant::now() + Duration::from_secs(5);
        let stream = loop {
            match std::os::unix::net::UnixStream::connect(socket) {
                Ok(s) => break s,
                Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
                Err(e) => return Err(format!("the Wi-Fi port {}: {e}", socket.display())),
            }
        };
        stream.set_nonblocking(true).map_err(|e| e.to_string())?;
        let radio = pinnacle_wifi::sim::Radio::new(SimWifi::access_points());
        self.radios
            .lock()
            .map_err(|e| e.to_string())?
            .push((radio, stream));
        Ok(())
    }

    /// Takes access point `ssid` out of every radio's reach, or back.
    fn set_in_reach(&self, ssid: &str, in_reach: bool) {
        if let Ok(mut radios) = self.radios.lock() {
            for (radio, _) in radios.iter_mut() {
                radio.set_in_reach(ssid, in_reach);
            }
        }
    }
}

fn wifi_air() -> &'static SimWifi {
    static WIFI: std::sync::OnceLock<SimWifi> = std::sync::OnceLock::new();
    WIFI.get_or_init(SimWifi::new)
}

/// Boots to check, the system fetching `url` over https from the
/// internet: TLS 1.3 from a program in Pinnacle, the server's chain
/// checked against the roots on its system disk. Needs the internet, so
/// it is no part of `test` or the gate.
fn https(url: &str) -> Result {
    let system = root().join("target/https-system.img");
    disks_at(
        &system,
        &serve()?,
        &[("/settings/https-test".into(), url.as_bytes().to_vec())],
    )?;
    let elf = build("qemu-virt")?;
    let guest = Guest {
        system,
        // The listening self-check is knocked on, as in `test`.
        tcp_forward: Some(free_tcp_port()?),
        ..Guest::default()
    };
    let out = boot("virt", &Load::Elf(elf), &guest)?;
    let line = out
        .lines()
        .find(|l| l.contains("https:"))
        .unwrap_or("")
        .trim()
        .to_string();
    if out.contains("https ok") {
        println!("ok   {line}");
        Ok(())
    } else {
        Err(format!("https: not fetched: {line}"))
    }
}

/// Where each core of a hung QEMU is: its PC from the monitor, as the
/// kernel's function and line. The first thing to know about a hang.
fn where_cores_are(monitor: &Path) -> String {
    use std::io::{Read, Write};
    let Ok(mut socket) = std::os::unix::net::UnixStream::connect(monitor) else {
        return "  [host] no monitor to ask where the cores are".into();
    };
    socket.set_read_timeout(Some(Duration::from_millis(1500))).ok();
    let _ = socket.write_all(b"info registers -a\n");
    let mut text = Vec::new();
    let mut buffer = [0u8; 65536];
    while let Ok(n) = socket.read(&mut buffer) {
        if n == 0 {
            break;
        }
        text.extend_from_slice(&buffer[..n]);
    }
    let text = String::from_utf8_lossy(&text);
    // "CPU#3" headers, each followed by its "PC=…".
    let mut cores: Vec<(String, String)> = Vec::new();
    let mut current = String::new();
    for line in text.lines() {
        if let Some(at) = line.find("CPU#") {
            current = line[at..].split_whitespace().next().unwrap_or("").to_string();
        }
        if let Some(at) = line.find("PC=") {
            let pc = line[at + 3..].split_whitespace().next().unwrap_or("").to_string();
            cores.push((current.clone(), pc));
        }
    }
    let elf = build("qemu-virt").ok();
    let mut out = String::from("  [host] where the cores are:\n");
    for (cpu, pc) in cores {
        let place = elf
            .as_ref()
            .and_then(|elf| {
                let o = Command::new("llvm-addr2line")
                    .args(["-f", "-C", "-i", "-e"])
                    .arg(elf)
                    .arg(format!("0x{pc}"))
                    .output()
                    .ok()?;
                let s = String::from_utf8_lossy(&o.stdout)
                    .lines()
                    .take(2)
                    .collect::<Vec<_>>()
                    .join(" at ");
                Some(s)
            })
            .unwrap_or_default();
        out += &format!("  [host]   {cpu}: {pc} {place}\n");
    }
    out
}

/// Where the stand-in for a loader's lit screen is, in the guest's RAM:
/// near the end of the self-check's 256 MiB, as U-Boot keeps its own at
/// the top of what it uses.
const LIT_AT: u64 = 0x4f00_0000;
/// A range the stand-in loader reserves besides the screen, as firmware's
/// would be: once in the header's block, once under `/reserved-memory`.
const LIT_RESERVED: [(u64, u64); 2] = [(0x4e00_0000, 0x10_0000), (0x4e40_0000, 0x10_0000)];

/// The lit screen's width, height and stride: the screen's size, its rows
/// 64 bytes longer than a row's pixels, as a controller's alignment makes
/// them.
fn lit_layout() -> (u32, u32, u32) {
    let (width, height) = screen();
    (width as u32, height as u32, width as u32 * 4 + 64)
}

/// QEMU's device tree for `machine`, as a loader that lit the screen would
/// pass it (U-Boot's `fdt_simplefb_enable_and_mem_rsv`): a
/// `simple-framebuffer` node at [`LIT_AT`] and its memory in the header's
/// reservation block, and two ranges of firmware reserved, one each way.
/// Written to `target/lit-screen.dtb`.
fn lit_tree(machine: &str) -> Result<PathBuf> {
    let dumped = root().join("target/qemu.dtb");
    let image = image("qemu-virt")?;
    let status = qemu_guest(machine, &Load::Image(image, ""), true, &Guest::default())
        .args(["-machine", &format!("dumpdtb={}", dumped.display())])
        .args(["-display", "none"])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map_err(|e| format!("qemu-system-aarch64: {e}"))?;
    if !status.success() {
        return Err(format!("dumping QEMU's device tree: {status}"));
    }
    let tree = std::fs::read(&dumped).map_err(|e| format!("{}: {e}", dumped.display()))?;
    let (width, height, stride) = lit_layout();
    let size = u64::from(stride) * u64::from(height);
    let mut fdt = Fdt::parse(&tree)?;
    fdt.reserve.push((LIT_AT, size));
    fdt.reserve.push(LIT_RESERVED[0]);
    let cells = |a: u64, s: u64| {
        [a >> 32, a & 0xffff_ffff, s >> 32, s & 0xffff_ffff]
            .iter()
            .flat_map(|&c| (c as u32).to_be_bytes())
            .collect::<Vec<u8>>()
    };
    let word = |n: u32| n.to_be_bytes().to_vec();
    let text = |s: &str| [s.as_bytes(), &[0]].concat();
    fdt.add_node(
        &format!("framebuffer@{LIT_AT:x}"),
        &[
            ("compatible", text("simple-framebuffer")),
            ("reg", cells(LIT_AT, size)),
            ("width", word(width)),
            ("height", word(height)),
            ("stride", word(stride)),
            ("format", text("a8r8g8b8")),
            ("status", text("okay")),
        ],
        &[],
    );
    let (address, length) = LIT_RESERVED[1];
    fdt.add_node(
        "reserved-memory",
        &[
            ("#address-cells", word(2)),
            ("#size-cells", word(2)),
            ("ranges", Vec::new()),
        ],
        &[(
            &format!("firmware@{address:x}"),
            &[("reg", cells(address, length)), ("no-map", Vec::new())],
        )],
    );
    let out = root().join("target/lit-screen.dtb");
    std::fs::write(&out, fdt.write()).map_err(|e| format!("{}: {e}", out.display()))?;
    Ok(out)
}

/// A flattened device tree taken apart just enough to add to it: its
/// reservation block, its structure, its strings.
struct Fdt {
    reserve: Vec<(u64, u64)>,
    /// The structure block up to the root's END_NODE (not included).
    structure: Vec<u8>,
    strings: Vec<u8>,
    boot_cpu: u32,
}

impl Fdt {
    fn parse(bytes: &[u8]) -> Result<Fdt> {
        let word = |at: usize| -> Result<u32> {
            Ok(u32::from_be_bytes(
                bytes
                    .get(at..at + 4)
                    .ok_or("a truncated device tree")?
                    .try_into()
                    .unwrap(),
            ))
        };
        if word(0)? != 0xd00d_feed {
            return Err("not a device tree".into());
        }
        let (structure_at, strings_at, reserve_at) =
            (word(8)? as usize, word(12)? as usize, word(16)? as usize);
        let (strings_len, structure_len) = (word(32)? as usize, word(36)? as usize);
        let mut reserve = Vec::new();
        let mut at = reserve_at;
        loop {
            let entry = (
                u64::from(word(at)?) << 32 | u64::from(word(at + 4)?),
                u64::from(word(at + 8)?) << 32 | u64::from(word(at + 12)?),
            );
            if entry == (0, 0) {
                break;
            }
            reserve.push(entry);
            at += 16;
        }
        let mut structure = bytes[structure_at..structure_at + structure_len].to_vec();
        // ... END_NODE (the root's), END.
        if structure.len() < 8 || structure[structure.len() - 8..] != [0, 0, 0, 2, 0, 0, 0, 9] {
            return Err("the device tree does not end with the root".into());
        }
        structure.truncate(structure.len() - 8);
        Ok(Fdt {
            reserve,
            structure,
            strings: bytes[strings_at..strings_at + strings_len].to_vec(),
            boot_cpu: word(28)?,
        })
    }

    /// The offset of `name` in the strings block, added when missing.
    fn string(&mut self, name: &str) -> u32 {
        let wanted = [name.as_bytes(), &[0]].concat();
        let mut at = 0;
        for s in self.strings.split_inclusive(|&b| b == 0) {
            if s == wanted.as_slice() {
                return at as u32;
            }
            at += s.len();
        }
        let at = self.strings.len();
        self.strings.extend_from_slice(&wanted);
        at as u32
    }

    /// Adds a node under the root, with its properties and children (each
    /// with properties only).
    #[allow(clippy::type_complexity)]
    fn add_node(
        &mut self,
        name: &str,
        properties: &[(&str, Vec<u8>)],
        children: &[(&str, &[(&str, Vec<u8>)])],
    ) {
        self.begin(name);
        for (property, value) in properties {
            self.property(property, value);
        }
        for (child, properties) in children {
            self.begin(child);
            for (property, value) in *properties {
                self.property(property, value);
            }
            self.structure.extend_from_slice(&2u32.to_be_bytes());
        }
        self.structure.extend_from_slice(&2u32.to_be_bytes());
    }

    fn begin(&mut self, name: &str) {
        self.structure.extend_from_slice(&1u32.to_be_bytes());
        self.structure.extend_from_slice(name.as_bytes());
        self.structure.push(0);
        while !self.structure.len().is_multiple_of(4) {
            self.structure.push(0);
        }
    }

    fn property(&mut self, name: &str, value: &[u8]) {
        let at = self.string(name);
        self.structure.extend_from_slice(&3u32.to_be_bytes());
        self.structure
            .extend_from_slice(&(value.len() as u32).to_be_bytes());
        self.structure.extend_from_slice(&at.to_be_bytes());
        self.structure.extend_from_slice(value);
        while !self.structure.len().is_multiple_of(4) {
            self.structure.push(0);
        }
    }

    fn write(&self) -> Vec<u8> {
        let mut structure = self.structure.clone();
        structure.extend_from_slice(&[0, 0, 0, 2, 0, 0, 0, 9]);
        let reserve_at = 40;
        let structure_at = reserve_at + (self.reserve.len() + 1) * 16;
        let strings_at = structure_at + structure.len();
        let total = strings_at + self.strings.len();
        let mut out = Vec::with_capacity(total);
        for field in [
            0xd00d_feed,
            total as u32,
            structure_at as u32,
            strings_at as u32,
            reserve_at as u32,
            17,
            16,
            self.boot_cpu,
            self.strings.len() as u32,
            structure.len() as u32,
        ] {
            out.extend_from_slice(&u32::to_be_bytes(field));
        }
        for &(address, size) in self.reserve.iter().chain([&(0, 0)]) {
            out.extend_from_slice(&address.to_be_bytes());
            out.extend_from_slice(&size.to_be_bytes());
        }
        out.extend_from_slice(&structure);
        out.extend_from_slice(&self.strings);
        out
    }
}

/// `cargo xtask lit-shot [png]`: the system booted as on a board whose
/// loader lit the screen (`lit_tree`), and that screen's memory, as the
/// display controller would scan it out, written as a PNG once the
/// first screen (choosing a password for the data) is up.
fn lit_shot(out: &Path) -> Result {
    disks(&serve()?)?;
    let image = image("qemu-virt")?;
    let tree = lit_tree("virt")?;
    let (width, height, stride) = lit_layout();
    let memory = LitMemory {
        address: LIT_AT,
        width,
        height,
        stride,
    };
    shot_with(
        qemu("virt", &Load::ImageTree(image, "", tree)),
        out,
        "display: choose a password",
        boot_timeout(),
        Some(memory),
    )
}

/// A screen's memory, to photograph from the guest's RAM rather than from
/// QEMU's display: XRGB8888 rows `stride` bytes apart.
struct LitMemory {
    address: u64,
    width: u32,
    height: u32,
    stride: u32,
}

impl LitMemory {
    /// Reads what QEMU's `pmemsave` wrote as a binary PPM.
    fn to_ppm(&self, raw: &Path, ppm: &Path) -> Result {
        let bytes = std::fs::read(raw).map_err(|e| format!("{}: {e}", raw.display()))?;
        let mut out = format!("P6\n{} {}\n255\n", self.width, self.height).into_bytes();
        for y in 0..self.height as usize {
            let row = &bytes[y * self.stride as usize..][..self.width as usize * 4];
            for pixel in row.as_chunks::<4>().0 {
                out.extend_from_slice(&[pixel[2], pixel[1], pixel[0]]);
            }
        }
        std::fs::write(ppm, out).map_err(|e| format!("{}: {e}", ppm.display()))
    }
}