#!/usr/bin/env bash # One-time spindle setup for the Homura/Sayaka fleet: # 1. create or validate the spindle signing key, # 2. switch Homura, # 3. build, sign, and switch Sayaka, # 4. verify the spindle and cache endpoints. # # Run as the normal user callie on Homura. sudo prompts interactively. set +x set -euo pipefail umask 077 readonly KEY_DIR=/var/lib/secrets readonly KEY_PATH=$KEY_DIR/spindle-key.pem readonly SAYAKA_TARGET=callie@100.77.12.60 readonly DIRECT_HEALTH=http://100.116.202.116:6555/_health readonly CACHE_INFO=http://100.116.202.116:5000/nix-cache-info readonly PUBLIC_HEALTH=https://spindle.on-her.computer/_health readonly SERVICE_TIMEOUT=60 readonly PROBE_TIMEOUT=60 readonly PUBLIC_TIMEOUT=120 dry_run=0 tmp_key= script_dir= repo= cleanup() { if [ -n "${tmp_key:-}" ]; then sudo rm -f -- "$tmp_key" 2>/dev/null || true tmp_key= fi } trap cleanup EXIT log() { printf '\n==> %s\n' "$*"; } info() { printf ' %s\n' "$*"; } warn() { printf 'warning: %s\n' "$*" >&2; } die() { printf 'error: %s\n' "$*" >&2; exit 1; } usage() { cat <<'EOF' Usage: scripts/fleet-setup.sh [--dry-run | --help] Create or validate the spindle signing key, switch Homura, build and sign the Sayaka closure and switch Sayaka to it, then check the spindle and cache. Run as the normal user callie on Homura. sudo prompts interactively. Re-running is safe: an existing valid key is preserved, never rotated. Options: --dry-run Print the intended commands and checks without changing anything. --help Show this help. Prerequisites: - Host homura, inside this repository's git worktree. - The required spindle modules are tracked by git (the flake only sees tracked files). - /dev/kvm is present and /mnt/hdd is mounted. - Working SSH to callie@100.77.12.60 on port 22 and a healthy tailnet. - Homura's agenix Nix signing key is materialized (nix-signing-homura). - git, nix, nixos-rebuild, openssl, curl, findmnt, systemctl, and sudo. The script does not install CI secrets, register the repository spindle, prime the cache, reboot, or run any git command that changes state. EOF } require_cmd() { local path if ! path=$(command -v "$1" 2>/dev/null) || [ -z "$path" ]; then die "required command not found: $1" fi printf '%s\n' "$path" } optional_cmd() { command -v "$1" 2>/dev/null || printf '%s\n' "$1" } signing_key_optional() { local path= if command -v nix >/dev/null 2>&1; then path=$(nix config show secret-key-files 2>/dev/null | awk 'NF {print $1; exit}') || true fi printf '%s\n' "${path:-/run/agenix/nix-signing-homura}" } preflight() { [ "$(uname -n)" = homura ] || die "run this on Homura (current host: $(uname -n))" [ "$(id -u)" -ne 0 ] || die "run as the normal user callie, not root; this script invokes sudo itself" if [ "$(id -un)" != callie ]; then warn "this setup is written for user callie; continuing as $(id -un)" fi NIX_BIN=$(require_cmd nix) NIXOS_REBUILD_BIN=$(require_cmd nixos-rebuild) OPENSSL_BIN=$(require_cmd openssl) CURL_BIN=$(require_cmd curl) FINDMNT_BIN=$(require_cmd findmnt) for cmd in git sudo systemctl; do command -v "$cmd" >/dev/null 2>&1 || die "required command not found: $cmd" done if ! repo=$(git -C "$script_dir" rev-parse --show-toplevel 2>/dev/null); then die "$script_dir is not inside a git worktree; run the script from the fleet repository" fi [ -f "$repo/flake.nix" ] || die "$repo/flake.nix not found" [ -d "$repo/hosts/homura" ] || die "$repo/hosts/homura not found" [ -d "$repo/hosts/sayaka" ] || die "$repo/hosts/sayaka not found" local required for required in \ hosts/homura/modules/spindle.nix \ hosts/homura/modules/nix-cache-proxy.nix \ modules/ci/spindle.nix do if ! git -C "$repo" ls-files --error-unmatch -- "$required" >/dev/null 2>&1; then die "required flake file is not tracked by git: $required (stage it so the flake can see it)" fi done if [ -n "$(git -C "$repo" status --porcelain --untracked-files=no 2>/dev/null)" ]; then warn "tracked files have uncommitted changes; the flake build will include them" fi [ -c /dev/kvm ] || die "/dev/kvm is missing; the spindle microVM runner requires KVM" "$FINDMNT_BIN" -rn -M /mnt/hdd >/dev/null 2>&1 \ || die "/mnt/hdd is not mounted; mount the spindle/cache disk before running" } key_exists() { sudo test -e "$KEY_PATH" || sudo test -L "$KEY_PATH" } validate_key() { if sudo test -L "$KEY_PATH"; then die "refusing symlink at $KEY_PATH; replace it with the real key file" fi if ! sudo test -f "$KEY_PATH"; then die "refusing non-regular key path $KEY_PATH" fi if ! sudo test -s "$KEY_PATH"; then die "existing key is empty: $KEY_PATH" fi # -passin pass: makes an encrypted or otherwise unreadable key fail instead # of prompting. No command below prints private key material. if ! sudo "$OPENSSL_BIN" pkey -in "$KEY_PATH" -noout -check -passin pass: >/dev/null 2>&1; then die "existing key is not a valid unencrypted private key; refusing to overwrite or rotate it" fi if ! sudo "$OPENSSL_BIN" pkey -in "$KEY_PATH" -pubout -passin pass: 2>/dev/null \ | "$OPENSSL_BIN" pkey -pubin -noout -text 2>/dev/null \ | grep -Eq 'ASN1 OID: prime256v1|NIST CURVE: P-256' then die "existing key is not an EC P-256 key; refusing to overwrite or rotate it" fi local perms perms=$(sudo stat -c '%u:%g:%a' -- "$KEY_PATH") || die "could not inspect key permissions" if [ "$perms" != "0:0:600" ]; then info "Correcting key ownership/mode from $perms to root:root 0600" sudo chown root:root -- "$KEY_PATH" || die "failed to set key ownership to root:root" sudo chmod 0600 -- "$KEY_PATH" || die "failed to set key mode to 0600" fi info "Key validated (EC P-256, root:root 0600)" } create_key() { local tmp created=0 info "No key found; generating an EC P-256 private key" tmp=$(sudo mktemp -- "$KEY_DIR/.spindle-key.XXXXXX") || die "failed to create a temporary key file" tmp_key=$tmp if ! sudo "$OPENSSL_BIN" ecparam -name prime256v1 -genkey -noout -out "$tmp_key" >/dev/null 2>&1; then die "openssl failed to generate the EC P-256 key" fi sudo chown root:root -- "$tmp_key" || die "failed to set temporary key ownership" sudo chmod 0600 -- "$tmp_key" || die "failed to set temporary key permissions" if sudo ln -T -- "$tmp_key" "$KEY_PATH" 2>/dev/null; then created=1 elif key_exists; then info "Another process installed the key first; preserving it" else die "failed to install the key atomically at $KEY_PATH" fi if ! sudo rm -f -- "$tmp_key"; then die "failed to remove temporary key file $tmp; cleanup will retry" fi tmp_key= if [ "$created" -eq 1 ]; then info "Created a new spindle signing key" fi validate_key } ensure_spindle_key() { log "Ensuring the spindle signing key at $KEY_PATH" sudo install -d -m 0700 -o root -g root -- "$KEY_DIR" \ || die "failed to create or secure $KEY_DIR" if key_exists; then info "Existing key found; validating it without rotating" validate_key else create_key fi } switch_homura() { log "Switching Homura (local rebuild)" printf ' %s switch --flake %q#homura --no-update-lock-file --elevate sudo --ask-elevate-password\n' \ "$NIXOS_REBUILD_BIN" "$repo" "$NIXOS_REBUILD_BIN" switch --flake "$repo#homura" --no-update-lock-file \ --elevate sudo --ask-elevate-password \ || die "Homura switch failed; fix the build error and rerun (the key is preserved)" } resolve_signing_key() { local path path=$("$NIX_BIN" config show secret-key-files 2>/dev/null | awk 'NF {print $1; exit}') \ || die "failed to read Nix secret-key-files" if [ -z "$path" ]; then die "no Nix signing key is configured on Homura; enable myNixOS.nix.signing" fi case "$path" in /*) ;; *) die "Nix secret-key-files did not return an absolute path: $path" ;; esac printf '%s\n' "$path" } switch_sayaka() { log "Preparing Sayaka (build and sign on Homura)" local sign_key closure sign_key=$(resolve_signing_key) if ! sudo test -s "$sign_key" || ! sudo test -r "$sign_key"; then die "Nix signing key $sign_key is missing or unreadable; ensure agenix has materialized it" fi info "Building the Sayaka toplevel on Homura" closure=$("$NIX_BIN" build --no-link --print-out-paths --no-update-lock-file \ "$repo#nixosConfigurations.sayaka.config.system.build.toplevel") \ || die "failed to build the Sayaka toplevel" case "$closure" in /nix/store/*) ;; *) die "unexpected closure path from nix build: $closure" ;; esac case "$closure" in *$'\n'*|*' '*) die "nix build returned an unexpected multi-path result" ;; esac info "Signing the Sayaka closure (required before the remote copy)" printf ' sudo %s store sign --key-file %s --recursive %s\n' \ "$NIX_BIN" "$sign_key" "$closure" sudo "$NIX_BIN" store sign --key-file "$sign_key" --recursive "$closure" \ || die "failed to sign the Sayaka closure; remote activation would reject unsigned paths" log "Switching Sayaka (remote)" printf ' %s switch --store-path %s --target-host %s --elevate sudo --ask-elevate-password\n' \ "$NIXOS_REBUILD_BIN" "$closure" "$SAYAKA_TARGET" "$NIXOS_REBUILD_BIN" switch --store-path "$closure" --target-host "$SAYAKA_TARGET" \ --elevate sudo --ask-elevate-password \ || die "Sayaka switch failed; inspect the target's activation error" } wait_service() { local unit=$1 timeout=$2 start=$SECONDS while ! systemctl is-active --quiet "$unit"; do if (( SECONDS - start >= timeout )); then return 1 fi sleep 2 done } wait_url() { local url=$1 pattern=$2 timeout=$3 start=$SECONDS body while :; do if body=$("$CURL_BIN" -fsS --max-time 8 "$url" 2>/dev/null) \ && printf '%s' "$body" | grep -Eq -- "$pattern" then return 0 fi if (( SECONDS - start >= timeout )); then return 1 fi sleep 2 done } check_health() { log "Verifying services and endpoints" local unit for unit in spindle.service nix-cache-s3-signer.service nginx.service; do wait_service "$unit" "$SERVICE_TIMEOUT" \ || die "$unit did not become active within ${SERVICE_TIMEOUT}s; inspect: systemctl status $unit" info "$unit is active" done info "Direct spindle health: $DIRECT_HEALTH" wait_url "$DIRECT_HEALTH" '"status"[[:space:]]*:[[:space:]]*"ok"' "$PROBE_TIMEOUT" \ || die "direct spindle health check failed; inspect: curl -v $DIRECT_HEALTH and systemctl status spindle.service" info "Private cache metadata: $CACHE_INFO" wait_url "$CACHE_INFO" '^StoreDir: /nix/store' "$PROBE_TIMEOUT" \ || die "cache metadata check failed; inspect: curl -v $CACHE_INFO and systemctl status nix-cache-s3-signer.service nginx.service" info "Public spindle health (TLS/ACME may need a moment): $PUBLIC_HEALTH" wait_url "$PUBLIC_HEALTH" '"status"[[:space:]]*:[[:space:]]*"ok"' "$PUBLIC_TIMEOUT" \ || die "public spindle health check failed; inspect DNS/TLS and: curl -v $PUBLIC_HEALTH" } print_dry_run() { local nix nr openssl sign_key nix=$(optional_cmd nix) nr=$(optional_cmd nixos-rebuild) openssl=$(optional_cmd openssl) sign_key=$(signing_key_optional) printf 'Dry run on %s; no changes will be made.\n\n' "$(uname -n)" cat < $nr switch --store-path /nix/store/ --target-host $SAYAKA_TARGET --elevate sudo --ask-elevate-password 4. Verify (bounded readiness retries, no TLS bypass) systemctl is-active --quiet spindle.service systemctl is-active --quiet nix-cache-s3-signer.service systemctl is-active --quiet nginx.service curl -fsS $DIRECT_HEALTH curl -fsS $CACHE_INFO curl -fsS $PUBLIC_HEALTH No CI secrets, repository registration, cache priming, git mutation, or reboot. EOF } main() { ensure_spindle_key switch_homura switch_sayaka check_health log "All automated setup steps completed and health checks passed" cat < Pipelines and select this spindle. - Install CI repository secrets separately with scripts/spindle-bootstrap.py if needed. - Keep a backup of $KEY_PATH; losing it changes the spindle identity. EOF } while (($#)); do case "$1" in --help) usage exit 0 ;; --dry-run) dry_run=1 shift ;; *) die "unknown argument: $1 (try --help)" ;; esac done script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) \ || die "could not resolve the script directory" repo=$(git -C "$script_dir" rev-parse --show-toplevel 2>/dev/null || true) repo=${repo:-$script_dir} if [ "$dry_run" -eq 1 ]; then print_dry_run exit 0 fi preflight main