#!/usr/bin/env bash
# AI Admin Panel Installer — universal, multi-distro (AI-349)
#
# NOTE: scripts/install.sh is GENERATED from scripts/install.sh.in + scripts/lib/*.sh
# by scripts/build-installer.sh. Edit the .in template and the lib modules, then
# run scripts/build-installer.sh to regenerate — do not hand-edit install.sh.
#
# Usage:
#   curl -fsSL https://get.aiadminpanel.com -o install.sh && bash install.sh
#   bash install.sh [--dry-run] [--verbose] [--unattended] [--no-firewall]
#   bash install.sh --refresh-updater   (existing install: rewrite only the host files:
#                                        updater, egress guard, backup, private access)
#   bash install.sh --new-setup-token   (existing install: replace a lost setup code)
#   bash install.sh --docker-address-pools (existing install: let Docker hold
#                                        thousands of networks; restarts Docker)
#   bash install.sh --bake              (cloud image build: set the machine up
#                                        and pull every image, no secret, no stack)
#   bash install.sh --first-boot        (each server made from a baked image: its
#                                        own secrets, .env and stack, once)
#
# Certified:    Ubuntu 22.04/24.04, Debian 12/13, Rocky/AlmaLinux/CentOS Stream 9/10
# Best-effort:  Fedora, Oracle Linux, Amazon Linux 2023
# Document-only: openSUSE Leap/SLES, Arch  (detection is by package-manager
#               capability + version floor, so newer releases auto-classify)
# Architectures: x86_64 (amd64), aarch64/arm64
#
# --dry-run:      Log all actions without executing them (safe for testing)
# --verbose:      Enable debug output
# --refresh-updater: On an existing install, write /opt/aiadminpanel/aap-update.sh
#                 and its systemd units from this installer, install and apply
#                 the container egress guard (aap-egress-guard.sh, its service
#                 and timer; this changes the host firewall, AI-1104), and stop.
#                 A panel update never replaces these host files, so this is how
#                 a host gets the ones of the release it is running (AI-832). It
#                 also writes the nightly backup scripts and enables
#                 aap-backup.timer (AI-925). It waits (up to 10 minutes) for a
#                 running update or nightly backup to finish, writes each file
#                 by rename, never in place, and writes update/updater.json
#                 (AI-1471). It also writes the private-access script and its
#                 units (aap-private-access.sh; AI-2194), enabling nothing.
# --new-setup-token: DEPRECATED (AI-2792): the signed-in admin opens the setup
#                 wizard; the panel accepts a setup code for one more release.
#                 On an existing install, write a new setup code, restart
#                 only the panel container and print the new setup link
#                 (AI-1184). For a lost link, or a panel updated before its
#                 owner finished the setup wizard. Update the panel first.
#                 Off a terminal it prints only the root-only file that holds
#                 the link, ${SECRETS_DIR}/setup_link (AI-2331).
# --docker-address-pools: On an existing install, merge the panel's
#                 default-address-pools into /etc/docker/daemon.json (other keys
#                 kept, original backed up as daemon.json.aap-backup-<time>,
#                 refused if the file is not JSON) and restart Docker when the
#                 file changed. The restart stops and starts EVERY container on
#                 the host. A re-run changes nothing (AI-1446).
# --bake:         Cloud image build (AWS AMI, Vultr snapshot; AI-2745). Runs
#                 only the machine setup of the install (packages, Docker, host
#                 firewall, host files), downloads this release's Compose file,
#                 pulls every image it names, and writes the bake marker
#                 /etc/aiadminpanel/baked.json (version, Compose file SHA-256,
#                 each image's digest, AAP_INSTALL_SOURCE as the channel, time).
#                 It creates no secret, no .env, no Docker volume and starts no
#                 container; it claims no domain and calls no licence or
#                 telemetry service. Exit 2, before anything changes, when
#                 PANEL_DOMAIN, ADMIN_PASSWORD, SETUP_TOKEN or LICENSE_KEY is
#                 set, or when this server already holds an install: the
#                 secrets directory, .env, or an aiadminpanel_* Docker volume
#                 or container. Each server gets its secrets at its first boot.
#                 On the Vultr Marketplace channel (AAP_INSTALL_SOURCE=
#                 vultr-marketplace; vultr is an old alias) it also installs
#                 the Vultr first-boot hook that cloud-init runs once per new
#                 server (/var/lib/cloud/scripts/per-instance/; AI-2747).
# --first-boot:   The per-server half of a baked image (AI-2747, spec 2.3). Runs
#                 the first-boot rows of the install plan: domain, secrets, .env,
#                 setup code, the stack (docker compose up --pull never: the
#                 images are already on disk), admin, firewall ports, guard.
#                 Unattended; never prints a password, setup code or recovery
#                 key. Progress and result in /opt/aiadminpanel/update/
#                 first-boot.json (no secrets) and the login banner. Binds the
#                 secrets to this server's instance ID (Vultr metadata, else
#                 /etc/machine-id). Exit 0 done (or already done), 1 a step
#                 failed (run it again: secrets made by this server are kept),
#                 2 wrong invocation (no bake marker: run --bake first), 3 this
#                 disk holds another server's secrets (nothing changed).
# --no-firewall:  Same as FIREWALL=skip: do not install or turn on a host
#                 firewall when none is running (AI-2199). For servers behind a
#                 provider or external firewall.
# --admin-email <address>: Same as ADMIN_EMAIL=<address> (below): your e-mail,
#                 which becomes your admin sign-in e-mail (AI-2792).
# --upgrade-url <url>: Same as UPGRADE_URL=<url> (below): the address the
#                 panel's Upgrade button opens, e.g. a hosting provider's shop.
# --unattended:   Non-interactive mode (claims a free temporary domain when PANEL_DOMAIN is unset; set MANAGED_DOMAIN=off to require it)
#                 The final screen then shows where the admin password is
#                 (a root-only file in /opt/aiadminpanel/secrets/),
#                 never the values; the same happens whenever stdout is not a
#                 terminal (cloud-init, marketplace scripts, CI; AI-2331).
# --gpu-driver=auto|skip|install: Same as AAP_GPU_DRIVER (below). The NVIDIA
#                 GPU driver check that runs after the pre-flight checks
#                 (AI-2330). It prints what was found and the driver plan.
#                 On Ubuntu 22.04/24.04, Debian 12/13 and Rocky Linux,
#                 AlmaLinux, CentOS Stream and RHEL 9/10 (x86_64), auto
#                 (default) and install also install the headless NVIDIA
#                 driver when it is missing. A loaded driver, and a
#                 provider-managed cloud GPU (vGPU, Vultr, AWS g6f/gr6f), are
#                 never touched. On other systems auto continues without a
#                 driver, as before, and install stops with exit 1. skip turns
#                 the check off.
#                 On an NVSwitch (HGX) board it also installs NVIDIA Fabric
#                 Manager at the driver's version and turns its service on,
#                 next to a new or an existing driver (AI-2320).
#                 Exit 20: restart needed (the driver loads after a reboot;
#                 the installer prints the command to run again).
#                 Exit 21: Secure Boot is on; enrol the driver's signing key
#                 at the next boot (the steps are printed), then run again.
#
# Environment variables (skip interactive prompts when set):
#   PANEL_DOMAIN   - Domain for the panel (e.g., panel.example.com)
#   ACME_EMAIL     - Email for Let's Encrypt certificates
#   PANEL_VERSION  - Version to install (default: latest). A release, either as
#                    the image tag (2.22.0) or the GitHub release name (v2.22.0)
#                    A release also downloads its Compose file, Keycloak realm
#                    and theme from <get server>/v<version>/, checked against
#                    that folder's SHA256SUMS (AI-2327)
#   UPGRADE_URL    - Your own buy page for the panel's Upgrade button and links
#                    (optional, AI-2218; default https://aiadminpanel.com). An
#                    absolute https:// address; plain http:// only on localhost,
#                    127.0.0.1 or [::1]. Written to .env; a re-run without it
#                    keeps the value already there. Same as --upgrade-url <url>.
#   CF_DNS_API_TOKEN - Cloudflare DNS API token for wildcard certs (optional)
#   ADMIN_PASSWORD - Override auto-generated admin password (optional)
#   ADMIN_EMAIL    - Your e-mail; it becomes your admin sign-in e-mail (AI-2792).
#                    Same as --admin-email <address>. An interactive install
#                    asks for it; an unattended one without it uses
#                    admin@<domain>, and the setup wizard then asks once. A
#                    re-run keeps the address the panel was installed with.
#   SETUP_TOKEN    - DEPRECATED (AI-2792): override the auto-generated setup
#                    code, at least 32 characters (optional, AI-1184). The
#                    wizard opens for the signed-in admin; the panel accepts
#                    the code in X-Setup-Token for one more release only.
#   LICENSE_KEY    - License key for activation (optional, skip for 14-day trial)
#   GOMEMLIMIT     - Go memory limit (optional)
#   TLS_MODE       - letsencrypt (default: certificate over port 80, HTTP-01) |
#                    letsencrypt-dns (certificate through a DNS record, DNS-01,
#                    with the DNS provider saved in Settings: Cloudflare,
#                    PowerDNS or manual; skips the DNS A-record pre-flight
#                    check). cloudflare is the old name for letsencrypt-dns and
#                    still works. Any other value stops the installer.
#   AAP_FIX_ROUTING - set to 1 to auto-fix a detected dual-default-route hazard
#                    (multi-homed VPS such as OVH/Hetzner: a private NIC's DHCP
#                    default route at a metric <= the public default breaks Docker
#                    container networking). netplan hosts only; otherwise warn.
#   AAP_PROVIDER_AI_API_KEY  - bundle a central "Provider AI" inference endpoint
#                    (§6.6). When set, the panel seeds a Provider AI source on
#                    first boot so deployed AI apps have a working upstream with
#                    no key pasting. Always editable in Settings afterwards.
#   AAP_PROVIDER_AI_BASE_URL - the OpenAI-compatible base URL for the above
#                    (e.g. https://inference.example.com/v1).
#   AAP_PROVIDER_AI_MODEL    - default model id for the bundled Provider AI.
#   AAP_PROVIDER_AI_PROVIDER_TYPE - openai (default) | openrouter | anthropic | ollama.
#   AAP_INSTALL_OLLAMA - set to "true" to download and start the bundled local
#                    AI engine (Ollama, an 8.5 GB image) during the install.
#                    Default: it starts on demand, when an admin pulls the
#                    first local model on the AI Models page (AI-2746), so a
#                    fresh install neither pulls nor starts it. A re-run on a
#                    server where the engine already exists keeps it.
#   AAP_SKIP_MODEL_PULL - set to "true" to skip auto-pulling the bundled metered
#                    model at install (AI-622). Only applies when the engine
#                    starts at install (AAP_INSTALL_OLLAMA=true); otherwise no
#                    model is pulled at install anyway. The RAM-gated
#                    litellm-config is still written; only the download is
#                    skipped, so the first metered call fails until the model
#                    is pulled from the AI Models page. For air-gapped installs
#                    and CI (the installer matrix sets it so jobs don't
#                    download multi-GB models).
#   FIREWALL      - unset (default): when no host firewall is running, install
#                    and turn on the distro's own one before Docker (firewalld on
#                    Rocky/Alma/RHEL/Fedora/SUSE, ufw on Debian/Ubuntu): inbound
#                    denied except SSH (the port sshd -T reports, and the current
#                    session's), 80/tcp and 443/tcp (AI-2199). A firewall that is
#                    already running is kept as it is. "skip" turns this off.
#   AAP_HARDEN_FAIL2BAN, AAP_HARDEN_PANEL_JAIL, AAP_HARDEN_SSHD,
#   AAP_HARDEN_UPGRADES - on (default) | off: the SSH and server hardening
#                    (lib/hardening.sh, AI-2776): fail2ban with an sshd jail and
#                    a panel sign-in jail, an sshd drop-in, automatic security
#                    updates. Also read from /opt/aiadminpanel/.env. "off"
#                    removes what an earlier install wrote for that part.
#   AAP_HARDEN_SSH_PASSWORDS - on (default) | keep: "keep" never turns off SSH
#                    password login, even when a working authorized key exists.
#   AAP_HARDEN_IGNOREIP - extra addresses/CIDRs fail2ban never bans.
#   AAP_GPU_DRIVER - auto (default) | skip | install: the GPU driver check
#                    (AI-2330). Same as --gpu-driver; the flag wins.
#   MANAGED_DOMAIN - set to "off" to disable the temporary-domain claim path:
#                    a missing PANEL_DOMAIN then fails exactly as before AI-544.
#                    Any other value (or unset) leaves the claim path enabled.
#   MANAGED_DNS_URL - claim service base URL (default
#                    https://dns.aiadminpanel.com; staging override for testing).
#                    Claims are IPv4-only; the installer never sets
#                    CF-Connecting-IP (Cloudflare manages that header itself).

set -euo pipefail

# ── Constants ─────────────────────────────────────────────────────────────────

PANEL_DIR="/opt/aiadminpanel"
CONFIG_DIR="/etc/aiadminpanel"
LOG_DIR="/var/log/aiadminpanel"
# Secret SOURCE files live on PERSISTENT storage under the panel dir, NOT the
# tmpfs /run/secrets (which is wiped on every reboot). Docker still mounts them
# into each container at /run/secrets/<name> via docker-compose.yml — that is the
# in-container target and is unaffected. Sourcing from /run pre-AI-397 left
# postgres/panel/keycloak unable to start after any host reboot. (AI-397)
SECRETS_DIR="${PANEL_DIR}/secrets"
INSTALL_LOG="${LOG_DIR}/install.log"

# AI-752: get.aiadminpanel.com (Cloudflare R2) is the ONLY remote asset source,
# and there is deliberately no GitHub base constant to fall back to. This repo is
# private, so every anonymous https://github.com/aiadminpanel/ai-admin-panel/
# releases/download/… request 404s — including the /latest/ alias. A customer box
# has no GitHub credential, so the old GitHub-first arm never once succeeded; it
# only cost every install a wasted round-trip before the R2 fetch it always needed.
# Do not re-add it: making it work would mean shipping and rotating a credential on
# every box, which is strictly worse than a public read-only bucket for assets that
# are public by design. Releases still carry these assets for authenticated humans
# and CI — that is a convenience, never an install-time source.
GET_BASE="https://get.aiadminpanel.com"

# AI-2747: --first-boot takes the baked version unless one is given.
PANEL_VERSION_GIVEN="${PANEL_VERSION:-}"
PANEL_VERSION="${PANEL_VERSION:-latest}"
# AI-2747: this installer's own file, which --bake keeps for the first boot.
INSTALLER_SELF="$(readlink -f "${BASH_SOURCE[0]:-}" 2>/dev/null || true)"
PANEL_DOMAIN="${PANEL_DOMAIN:-}"
ACME_EMAIL="${ACME_EMAIL:-}"
# AI-2792: the owner's e-mail, the admin account's sign-in name. Resolved by
# resolve_admin_email (end of prompt_domain); ADMIN_EMAIL_FALLBACK=true means
# nobody gave one and the account is admin@<domain> until the wizard asks.
ADMIN_EMAIL="${ADMIN_EMAIL:-}"
ADMIN_EMAIL_FALLBACK=false
# AI-2218: the hosting provider's own buy page for the Upgrade button (optional).
UPGRADE_URL="${UPGRADE_URL:-}"

CURRENT_STEP=0
INSTALL_START=$(date +%s)

# ── Flags ─────────────────────────────────────────────────────────────────────

DRY_RUN=false
VERBOSE=false
UNATTENDED=false
REFRESH_UPDATER=false
NEW_SETUP_TOKEN=false
DOCKER_ADDRESS_POOLS=false
BAKE=false
FIRST_BOOT=false
# AI-2745: which part of the install plan this run is in: all (a normal
# install), bake or first-boot. Steps that span both phases read it.
INSTALL_PHASE=all
# AI-2330: the GPU driver check (lib/gpu.sh). The environment sets the default;
# --gpu-driver overrides it.
AAP_GPU_DRIVER="${AAP_GPU_DRIVER:-auto}"
# The GPU step's reboot stop prints the command to run again with these flags.
AAP_INSTALL_ARGS=("$@")

# tests/installer/upgrade_url.bats runs the loop between these markers on its own.
# @AAP_ARGS_BEGIN@
while [ "$#" -gt 0 ]; do
  case "$1" in
    --dry-run) DRY_RUN=true ;;
    --refresh-updater) REFRESH_UPDATER=true ;;
    --new-setup-token) NEW_SETUP_TOKEN=true ;;
    --docker-address-pools) DOCKER_ADDRESS_POOLS=true ;;
    --bake) BAKE=true ;;
    --first-boot) FIRST_BOOT=true ;;
    --no-firewall) FIREWALL=skip ;;
    --verbose) VERBOSE=true ;;
    --unattended) UNATTENDED=true ;;
    --admin-email=*) ADMIN_EMAIL="${1#--admin-email=}" ;;
    --admin-email)
      if [ "$#" -lt 2 ]; then echo "--admin-email needs your e-mail address, for example --admin-email you@example.com" >&2; exit 1; fi
      ADMIN_EMAIL="$2"; shift ;;
    --upgrade-url=*) UPGRADE_URL="${1#--upgrade-url=}" ;;
    --upgrade-url)
      if [ "$#" -lt 2 ]; then echo "--upgrade-url needs an address, for example --upgrade-url https://example.com/pricing" >&2; exit 1; fi
      UPGRADE_URL="$2"; shift ;;
    --gpu-driver=*) AAP_GPU_DRIVER="${1#--gpu-driver=}" ;;
    --gpu-driver)
      if [ "$#" -lt 2 ]; then echo "--gpu-driver needs a value: auto, skip or install" >&2; exit 1; fi
      AAP_GPU_DRIVER="$2"; shift ;;
    *) echo "Unknown argument: $1" >&2; exit 1 ;;
  esac
  shift
done
# @AAP_ARGS_END@

# ── Bundled libraries: logging, platform detection, secrets, docker, firewall,
#    preflight — inlined from scripts/lib/*.sh by scripts/build-installer.sh.
#    Edit the lib modules or install.sh.in, NOT the generated install.sh.
# ─────────────────────────────────────────────────────────────────────────
# BUNDLED LIBRARY CODE — generated from scripts/lib/*.sh by build-installer.sh.
# DO NOT EDIT below this banner. Edit scripts/lib/<module>.sh or
# scripts/install.sh.in, then run scripts/build-installer.sh to regenerate.
# ─────────────────────────────────────────────────────────────────────────

# ===== scripts/lib/log.sh =====
# scripts/lib/log.sh — shared logging, colors, step counter, and the dry-run
# `run` wrapper for the AI Admin Panel installer (AI-349). Single source of these
# helpers for install.sh and every sibling lib module (their guarded fallbacks go
# inert once this is sourced/inlined first).
#
# Consumes globals owned by the installer main section: DRY_RUN, VERBOSE,
# INSTALL_LOG, TOTAL_STEPS, CURRENT_STEP. Pure function definitions + color setup.

# ── Color support ─────────────────────────────────────────────────────────────
COLOR_GREEN=""
COLOR_YELLOW=""
COLOR_RED=""
COLOR_CYAN=""
COLOR_BOLD=""
COLOR_RESET=""

setup_colors() {
  if [ -t 1 ] && command -v tput &>/dev/null && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]; then
    COLOR_GREEN=$(tput setaf 2)
    COLOR_YELLOW=$(tput setaf 3)
    COLOR_RED=$(tput setaf 1)
    COLOR_CYAN=$(tput setaf 6)
    COLOR_BOLD=$(tput bold)
    COLOR_RESET=$(tput sgr0)
  fi
}

# ── Logging ───────────────────────────────────────────────────────────────────
log() {
  local level="$1"
  shift
  local msg="$*"
  local ts
  ts=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
  local line="[$ts] [$level] $msg"

  case "$level" in
    "INFO ") echo "${COLOR_GREEN}${line}${COLOR_RESET}" ;;
    "WARN ") echo "${COLOR_YELLOW}${line}${COLOR_RESET}" ;;
    "ERROR") echo "${COLOR_RED}${line}${COLOR_RESET}" ;;
    "DRY  ") echo "${COLOR_CYAN}${line}${COLOR_RESET}" ;;
    *) echo "$line" ;;
  esac

  if [ -n "${INSTALL_LOG:-}" ] && [ -d "$(dirname "$INSTALL_LOG")" ]; then
    echo "$line" >>"$INSTALL_LOG" 2>/dev/null || true
  fi
}

info() { log "INFO " "$@"; }
warn() { log "WARN " "$@"; }
error() {
  log "ERROR" "$@"
  exit 1
}
debug() { [ "${VERBOSE:-false}" = "true" ] && log "DEBUG" "$@" || true; }
dryrun() { log "DRY  " "[WOULD] $*"; }

# ── Step timing (AI-2777) ─────────────────────────────────────────────────────
# Each step logs how long the step before it took; step_timing_finish logs the
# last one and the total. The lines go to the install log too (info), so a
# slow install shows where its time went. _step_now is the tests' clock.
STEP_STARTED_AT=""
STEP_TITLE=""
_step_now() { date +%s; }

# step_timing_close <now>: the "Step N (title) took X s" line for the step
# that is ending, if one is running.
step_timing_close() {
  [ -n "${STEP_STARTED_AT:-}" ] && [ "${CURRENT_STEP:-0}" -gt 0 ] || return 0
  info "Step ${CURRENT_STEP} (${STEP_TITLE}) took $(($1 - STEP_STARTED_AT)) s"
}

# step_timing_finish: the last step's line, then the total since the first
# step (INSTALL_TIMER_START). Call it once, after the last step.
step_timing_finish() {
  local now total
  [ -n "${STEP_STARTED_AT:-}" ] || return 0
  now="$(_step_now)"
  step_timing_close "$now"
  total=$((now - ${INSTALL_TIMER_START:-$STEP_STARTED_AT}))
  info "All steps took ${total} s ($((total / 60))m $((total % 60))s)"
  STEP_STARTED_AT=""
}

step() {
  local now
  now="$(_step_now)"
  step_timing_close "$now"
  [ -n "${STEP_STARTED_AT:-}" ] || INSTALL_TIMER_START="${INSTALL_TIMER_START:-$now}"
  STEP_STARTED_AT="$now"
  STEP_TITLE="${*%...}"
  CURRENT_STEP=$((${CURRENT_STEP:-0} + 1))
  echo ""
  echo "${COLOR_BOLD}[${CURRENT_STEP}/${TOTAL_STEPS:-?}] $*${COLOR_RESET}"
  # AI-2747: install.sh --first-boot names a function here that records the
  # step in its status file and login banner. Unset everywhere else.
  [ -z "${STEP_HOOK:-}" ] || "$STEP_HOOK" "$*"
}

# run — execute a command, or just narrate it under --dry-run. Used by the lib
# modules' side-effecting functions (docker.sh, firewall.sh) and the main script.
run() {
  if [ "${DRY_RUN:-false}" = "true" ]; then
    dryrun "$@"
  else
    debug "Running: $*"
    "$@"
  fi
}

# ===== scripts/lib/platform.sh =====
# shellcheck disable=SC2034  # this library's job is to SET globals (OS_*, OS_FAMILY,
# PLATFORM_TIER/REASON, PKG_MANAGER, ARCH, BINARY_SUFFIX) consumed by install.sh and
# sibling lib modules — shellcheck can't see those cross-file reads.
# scripts/lib/platform.sh — universal distro / package-manager / architecture
# detection for the AI Admin Panel installer (AI-349).
#
# Replaces install.sh's Ubuntu/Debian-only allowlist with capability + family
# detection driven by /etc/os-release ID/ID_LIKE/VERSION_ID and a `command -v`
# package-manager probe. Pure function definitions only — no side effects at
# source time; the bootstrap (install.sh) owns `set -euo pipefail`.
#
# Public functions (set shell globals, bash-style):
#   detect_platform   → OS_ID OS_ID_LIKE OS_VERSION_ID OS_VERSION_MAJOR OS_PRETTY
#                       OS_FAMILY (debian|rhel|suse|arch|alpine|unknown)
#                       PLATFORM_TIER (certified|best-effort|document|reject)
#                       PLATFORM_REASON (human-readable)
#   detect_pm         → PKG_MANAGER (apt|dnf|yum|zypper|pacman|apk|unknown)
#   detect_arch       → ARCH BINARY_SUFFIX (amd64|arm64); returns 1 on unsupported
#
# Test override hooks: OS_RELEASE_FILE (path), ARCH_OVERRIDE (uname -m value).

# ── os-release parsing (no `source` of the file — avoid executing/clobbering) ──
_osr_get() {
  # $1=file $2=key → echo the unquoted value of KEY=... (last match wins)
  local file="$1" key="$2" line val=""
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      "$key="*) val="${line#*=}" ;;
      *) continue ;;
    esac
  done <"$file"
  val="${val%\"}"; val="${val#\"}"
  val="${val%\'}"; val="${val#\'}"
  printf '%s' "$val"
}

# ── family from ID, then ID_LIKE fall-through ─────────────────────────────────
_family_of() {
  local id="$1" id_like="$2"
  case "$id" in
    debian | ubuntu | raspbian | linuxmint | pop | zorin | elementary | devuan | kali | mx | neon) echo debian; return ;;
    rhel | centos | rocky | almalinux | fedora | ol | oracle | amzn | scientific | cloudlinux | virtuozzo | rocky-linux) echo rhel; return ;;
    opensuse | opensuse-leap | opensuse-tumbleweed | opensuse-slowroll | sles | sled | suse) echo suse; return ;;
    arch | manjaro | endeavouros | artix | cachyos | garuda | arcolinux) echo arch; return ;;
    alpine) echo alpine; return ;;
  esac
  # Unknown ID — classify by ID_LIKE (space-delimited list per os-release spec).
  local hay=" $id_like "
  case "$hay" in
    *" ubuntu "* | *" debian "*) echo debian; return ;;
    *" rhel "* | *" centos "* | *" fedora "*) echo rhel; return ;;
    *" suse "* | *" opensuse "*) echo suse; return ;;
    *" arch "*) echo arch; return ;;
    *" alpine "*) echo alpine; return ;;
  esac
  echo unknown
}

# ── tier classification (pure: id, family, numeric-major → globals) ───────────
_classify() {
  local id="$1" family="$2" major="$3"
  PLATFORM_TIER=""; PLATFORM_REASON=""

  if [ "$family" = "alpine" ]; then
    PLATFORM_TIER="reject"
    PLATFORM_REASON="Alpine/musl/OpenRC is unsupported: the panel stack needs systemd-managed Docker. Use Ubuntu 22.04+, Debian 12+, or Rocky/AlmaLinux 9+."
    return
  fi

  case "$id" in
    ubuntu)
      if [ "${major:-0}" -ge 22 ]; then
        PLATFORM_TIER="certified"; PLATFORM_REASON="Ubuntu ${major}.x (>= 22.04 supported)"
      else
        PLATFORM_TIER="reject"; PLATFORM_REASON="Ubuntu ${major}.x is below the 22.04 floor and out of support — upgrade to Ubuntu 22.04 LTS or newer."
      fi
      return ;;
    debian)
      if [ "${major:-0}" -ge 12 ]; then
        PLATFORM_TIER="certified"; PLATFORM_REASON="Debian ${major} (>= 12 supported)"
      else
        PLATFORM_TIER="reject"; PLATFORM_REASON="Debian ${major} is below the 12 floor and out of support — upgrade to Debian 12 or newer."
      fi
      return ;;
    rocky | almalinux | rhel | centos)
      if [ "${major:-0}" -ge 9 ]; then
        PLATFORM_TIER="certified"; PLATFORM_REASON="${id} ${major} (RHEL-family >= 9 certified)"
      elif [ "${major:-0}" -eq 8 ]; then
        PLATFORM_TIER="best-effort"; PLATFORM_REASON="${id} 8 is below the certified floor (9); best-effort only — prefer 9 or 10."
      else
        PLATFORM_TIER="reject"; PLATFORM_REASON="${id} ${major} is EOL/unsupported (CentOS Linux 7/8, RHEL < 8). Use Rocky/AlmaLinux/RHEL 9 or newer."
      fi
      return ;;
    fedora)
      PLATFORM_TIER="best-effort"; PLATFORM_REASON="Fedora ${major}: best-effort (short EOL cadence — prefer Rocky/AlmaLinux for long-lived servers)."
      return ;;
    ol | oracle)
      if [ "${major:-0}" -ge 8 ]; then
        PLATFORM_TIER="best-effort"; PLATFORM_REASON="Oracle Linux ${major}: best-effort (RHEL-compatible)."
      else
        PLATFORM_TIER="reject"; PLATFORM_REASON="Oracle Linux ${major} is EOL."
      fi
      return ;;
    amzn)
      if [ "${major:-0}" -ge 2023 ]; then
        PLATFORM_TIER="best-effort"; PLATFORM_REASON="Amazon Linux 2023: best-effort."
      else
        PLATFORM_TIER="reject"; PLATFORM_REASON="Amazon Linux ${major} (AL2) is EOL in 2026 — use Amazon Linux 2023."
      fi
      return ;;
    opensuse | opensuse-leap | opensuse-tumbleweed | opensuse-slowroll | sles | sled | suse)
      PLATFORM_TIER="document"; PLATFORM_REASON="SUSE family: partially supported (no official Docker CE repo) — see docs for manual steps."
      return ;;
    arch | manjaro | endeavouros | artix | cachyos | garuda | arcolinux)
      PLATFORM_TIER="document"; PLATFORM_REASON="Arch family: best-effort/document-only (rolling release) — see docs."
      return ;;
  esac

  # ID not specifically known — fall back to family (matched via ID_LIKE).
  case "$family" in
    debian | rhel)
      PLATFORM_TIER="best-effort"
      PLATFORM_REASON="'${id}' is not explicitly tested but looks ${family}-compatible (ID_LIKE) — proceeding best-effort."
      ;;
    suse | arch)
      PLATFORM_TIER="document"; PLATFORM_REASON="'${id}' (${family}-like): document-only."
      ;;
    *)
      PLATFORM_TIER="reject"
      PLATFORM_REASON="Unrecognized distribution '${id}'. Supported: Ubuntu 22.04+, Debian 12+, Rocky/AlmaLinux/RHEL 9+ (best-effort: Fedora, Oracle Linux, Amazon Linux 2023)."
      ;;
  esac
}

detect_platform() {
  local osr="${OS_RELEASE_FILE:-/etc/os-release}"
  if [ ! -r "$osr" ]; then
    OS_FAMILY="unknown"; PLATFORM_TIER="reject"
    PLATFORM_REASON="Cannot detect OS: ${osr} not found or unreadable."
    return 1
  fi
  OS_ID="$(_osr_get "$osr" ID)"; OS_ID="${OS_ID,,}"
  OS_ID_LIKE="$(_osr_get "$osr" ID_LIKE)"; OS_ID_LIKE="${OS_ID_LIKE,,}"
  OS_VERSION_ID="$(_osr_get "$osr" VERSION_ID)"
  OS_PRETTY="$(_osr_get "$osr" PRETTY_NAME)"
  [ -n "$OS_PRETTY" ] || OS_PRETTY="${OS_ID} ${OS_VERSION_ID}"

  local maj="${OS_VERSION_ID%%.*}"
  case "$maj" in *[!0-9]* | "") maj=0 ;; esac
  OS_VERSION_MAJOR="$maj"

  OS_FAMILY="$(_family_of "$OS_ID" "$OS_ID_LIKE")"
  _classify "$OS_ID" "$OS_FAMILY" "$OS_VERSION_MAJOR"
  return 0
}

# ── package manager (ordered probe; dnf preferred over yum) ───────────────────
detect_pm() {
  local pm
  for pm in apt-get dnf yum zypper pacman apk; do
    if command -v "$pm" >/dev/null 2>&1; then
      case "$pm" in
        apt-get) PKG_MANAGER="apt" ;;
        *) PKG_MANAGER="$pm" ;;
      esac
      return 0
    fi
  done
  PKG_MANAGER="unknown"
  return 1
}

# ── apt lock (AI-2777) ───────────────────────────────────────────────────────
# A fresh Ubuntu or Debian server runs its automatic updates (apt-daily,
# apt-daily-upgrade) in its first minutes, and they hold apt's lock. apt-get,
# also inside get.docker.com, then fails with "Could not get lock". The
# installer waits for them instead, and says so.

# apt_lock_holder → prints what holds apt's lock and returns 0, or returns 1.
# fuser (psmisc) names any process on the lock files; the apt-daily units are
# checked too, for servers without fuser. unattended-upgrades.service is not:
# it is a shutdown helper that is active all the time.
apt_lock_holder() {
  local f unit
  if command -v fuser >/dev/null 2>&1; then
    for f in /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock; do
      [ -e "$f" ] || continue
      if fuser "$f" >/dev/null 2>&1; then
        echo "a process holds ${f}"
        return 0
      fi
    done
  fi
  if command -v systemctl >/dev/null 2>&1; then
    for unit in apt-daily.service apt-daily-upgrade.service; do
      if systemctl is-active --quiet "$unit" 2>/dev/null; then
        echo "${unit} is running"
        return 0
      fi
    done
  fi
  return 1
}

# wait_for_apt_lock: on apt systems, waits until nothing holds apt's lock,
# for at most APT_LOCK_TIMEOUT seconds (default 900), checking every
# APT_LOCK_POLL seconds (default 5) and saying so every 30 seconds. Returns 1
# with an error line when the time is up; the caller stops the install.
wait_for_apt_lock() {
  [ "${PKG_MANAGER:-}" = "apt" ] || return 0
  [ "${DRY_RUN:-false}" != "true" ] || return 0
  local limit="${APT_LOCK_TIMEOUT:-900}" poll="${APT_LOCK_POLL:-5}" waited=0 holder
  holder="$(apt_lock_holder)" || return 0
  info "Waiting for the automatic updates (${holder}) to finish: the installer needs the package manager after them (up to $((limit / 60)) minutes)..."
  while holder="$(apt_lock_holder)"; do
    if [ "$waited" -ge "$limit" ]; then
      warn "The automatic updates still hold the package lock after ${waited} s (${holder}). Let them finish (systemctl status apt-daily-upgrade.service), then run the installer again; APT_LOCK_TIMEOUT=<seconds> allows a longer wait."
      return 1
    fi
    sleep "$poll"
    waited=$((waited + poll))
    if [ $((waited % 30)) -lt "$poll" ] && [ "$waited" -lt "$limit" ]; then
      info "... still waiting for the automatic updates (${waited} s)"
    fi
  done
  info "The automatic updates are done after ${waited} s; the install goes on."
  return 0
}

# ── architecture ─────────────────────────────────────────────────────────────
detect_arch() {
  ARCH="${ARCH_OVERRIDE:-$(uname -m)}"
  case "$ARCH" in
    x86_64 | amd64) ARCH="x86_64"; BINARY_SUFFIX="amd64" ;;
    aarch64 | arm64) ARCH="aarch64"; BINARY_SUFFIX="arm64" ;;
    *)
      echo "Unsupported architecture: ${ARCH} (need x86_64 or aarch64/arm64)" >&2
      return 1
      ;;
  esac
  return 0
}

# ===== scripts/lib/secrets.sh =====
# scripts/lib/secrets.sh — portable, hardened CSPRNG secret generation and
# .env mutation for the AI Admin Panel universal installer (AI-349).
#
# Replaces install.sh's generate_secrets / create_admin_user password gen /
# generate_env_file with implementations that fix the audited findings
# (.planning/universal-installer/AUDIT.md):
#
#   gomemlimit-env-clobber  (CRITICAL): `echo X > .env` truncates the whole
#       file, wiping every OIDC/DB/Keycloak/domain var install.sh wrote.
#       env_set() appends-or-replaces a single line in place — never truncates.
#   db-password-644-leak    (HIGH): db_password + keycloak_admin_password were
#       chmod 644 (world-readable). generate_secrets chmod 600 EVERY secret.
#   base64-w0-busybox / xxd-not-default: `base64 -w0` is GNU-only and `xxd`
#       (vim) is absent on minimal installs. We use openssl/od/POSIX tr only.
#   admin-pw-restricted-alphabet: fragile base64|tr|head admin-pw pattern
#       replaced by unbiased `tr -dc 'A-Za-z0-9' </dev/urandom`.
#   litellm-master-key-default: installer must GENERATE the LiteLLM master key,
#       not ship the shared `sk-litellm-master-key` default.
#
# Pure function definitions only — no side effects at source time; the
# bootstrap (install.sh) owns `set -euo pipefail`.
#
# Public functions:
#   gen_secret_hex   nbytes        → echo nbytes of CSPRNG randomness, hex.
#   gen_secret_alnum [nchars=24]   → echo nchars of unbiased [A-Za-z0-9].
#   generate_secrets secrets_dir   → idempotently create master_key,
#                                     db_password, keycloak_admin_password,
#                                     litellm_master_key (all chmod 600).
#   env_set          env_file KEY VALUE → append-or-replace KEY in place.
#   sha256_hex                     → SHA-256 of stdin as lowercase hex.
#   setup_token_ensure secrets_dir env_file → create or reuse the setup code
#                                     and write its fingerprint to .env (AI-1184).
#   setup_token_rotate secrets_dir env_file → replace the setup code (AI-1184).
#   harden_perms     secrets_dir env_file → re-assert 700 dir / 600 files.

# ── CSPRNG primitives ─────────────────────────────────────────────────────────

# gen_secret_hex nbytes → nbytes of randomness as lowercase hex (2*nbytes chars).
# Prefers openssl; falls back to /dev/urandom via od (both POSIX-portable).
# NEVER uses xxd (vim, not default) or base64 -w0 (GNU-only).
gen_secret_hex() {
  local nbytes="$1"
  if command -v openssl >/dev/null 2>&1; then
    openssl rand -hex "$nbytes"
    return 0
  fi
  # Portable fallback: od emits space/newline-separated hex bytes; strip both.
  od -An -tx1 -N "$nbytes" /dev/urandom | tr -d ' \n'
  printf '\n'
}

# gen_secret_alnum [nchars=24] → nchars of unbiased [A-Za-z0-9] from /dev/urandom.
# `tr -dc` rejects (not maps) non-matching bytes, so the alphabet is uniform —
# no modulo bias. LC_ALL=C keeps the byte classes ASCII regardless of locale.
gen_secret_alnum() {
  local nchars="${1:-24}" out="" chunk
  # Read BOUNDED chunks from /dev/urandom with head as the FIRST pipeline stage
  # (reading a device, no upstream writer) so nothing ever gets SIGPIPE'd — the
  # naive `tr </dev/urandom | head -c N` form SIGPIPEs tr and trips
  # `set -o pipefail` in install.sh. ~24% of random bytes survive tr -dc, so
  # oversample 8x per round and loop until we have enough; then truncate.
  while [ "${#out}" -lt "$nchars" ]; do
    chunk="$(head -c "$((nchars * 8))" /dev/urandom | LC_ALL=C tr -dc 'A-Za-z0-9' || true)"
    out="${out}${chunk}"
  done
  printf '%s\n' "${out:0:nchars}"
}

# ── secret files ──────────────────────────────────────────────────────────────

# _write_secret_file path value → write value to path, no trailing newline,
# chmod 600, idempotent (existing file is left untouched). Returns 0 always.
_write_secret_file() {
  local path="$1" value="$2"
  if [ -f "$path" ]; then
    # Idempotent: never overwrite an existing secret (rotation is out of scope).
    chmod 600 "$path" 2>/dev/null || true
    return 0
  fi
  # Create with restrictive perms BEFORE writing content (no 644 window).
  ( umask 077; printf '%s' "$value" >"$path" )
  chmod 600 "$path"
}

# generate_secrets secrets_dir → idempotently create every panel secret.
#   master_key             : 32 random bytes hex-encoded (64 hex chars)
#   db_password            : 32 unbiased alnum chars
#   keycloak_admin_password: 32 unbiased alnum chars
#   litellm_master_key     : sk-<40 unbiased alnum chars>
#   managed_domain_token   : empty placeholder (real token written by
#                             manageddns.sh on managed installs)
#   openbao_unseal_key     : 32 random bytes hex-encoded (64 hex chars),
#                             chmod 644 — see the in-function comment
#   legacy_closed          : empty marker (AI-1345); root appends to it later
#   dns01_bridge_secret    : 32 random bytes hex-encoded; Traefik's password
#                             for the panel's DNS-01 bridge (AI-2295), copied
#                             into a new .env as DNS01_BRIDGE_SECRET
# Directory is created 0700; every secret file is chmod 600 except
# openbao_unseal_key (644 — the in-container non-root server must read it
# through the ro secret mount; host confidentiality comes from the 0700 dir).
generate_secrets() {
  local secrets_dir="$1"
  ( umask 077; mkdir -p "$secrets_dir" )
  chmod 700 "$secrets_dir"

  _write_secret_file "$secrets_dir/master_key"              "$(gen_secret_hex 32)"
  _write_secret_file "$secrets_dir/db_password"             "$(gen_secret_alnum 32)"
  _write_secret_file "$secrets_dir/keycloak_admin_password" "$(gen_secret_alnum 32)"
  _write_secret_file "$secrets_dir/litellm_master_key"      "sk-$(gen_secret_alnum 40)"
  _write_secret_file "$secrets_dir/dns01_bridge_secret"     "$(gen_secret_hex 32)"

  # AI-553 (AI-544 plan 3): the panel container mounts managed_domain_token as
  # a compose secret, and compose hard-fails on a missing secret file. Managed
  # installs wrote the real token earlier (md_acquire_domain runs before us);
  # BYO installs get an empty 0600 placeholder, which the panel reads as
  # "not a managed install". Never overwrite an existing token.
  if [ ! -f "$secrets_dir/managed_domain_token" ]; then
    ( umask 077; : > "$secrets_dir/managed_domain_token" )
    chmod 600 "$secrets_dir/managed_domain_token"
  fi

  # OpenBao static-seal unseal key (AI-557 OpenBao Phase 1). 32 random bytes
  # hex-encoded; mounted into the openbao container as a compose secret.
  #
  # 0644, NOT 0600: compose file-secrets are ro bind mounts that preserve the
  # host inode's perms, and the openbao image su-execs to its non-root
  # `openbao` user BEFORE the server parses the seal config — a 0600
  # root:root key is unreadable in-container and the server exits with
  # "error reading file at file:///run/secrets/openbao_unseal_key:
  # permission denied" (crash-loop, panel blocked on service_healthy;
  # reproduced against openbao/openbao:2.5.5 — the PR #458 install-matrix
  # failure on all 9 distros). postgres never hits this because its
  # entrypoint reads db_password while still root. Host confidentiality
  # comes from the untraversable 0700 secrets dir above, not the file bits.
  # chmod runs unconditionally to self-heal pre-fix 0600 keys on re-install.
  #
  # AI-2146: a protected host has only openbao_unseal_key.cred (the key,
  # encrypted with systemd-creds). A new clear key there would not open the
  # existing vault, so none is made.
  if [ -s "$secrets_dir/openbao_unseal_key.cred" ] && [ ! -f "$secrets_dir/openbao_unseal_key" ]; then
    :
  else
    if [ ! -f "$secrets_dir/openbao_unseal_key" ]; then
      ( umask 022; printf '%s' "$(gen_secret_hex 32)" > "$secrets_dir/openbao_unseal_key" )
    fi
    chmod 644 "$secrets_dir/openbao_unseal_key"
  fi

  # AI-1345: the kinds of stored secret that refuse the old encryption format,
  # one per line, appended later only by root (aap-update.sh after a healthy
  # update, or close-legacy-secret-format.sh). The panel mounts it read-only as
  # a compose file secret; empty closes nothing (and so does a missing file,
  # which the panel warns about). Never overwrite an existing file: it may
  # already hold lines.
  if [ ! -f "$secrets_dir/legacy_closed" ]; then
    ( umask 077; : > "$secrets_dir/legacy_closed" )
    chmod 600 "$secrets_dir/legacy_closed"
  fi
}

# migrate_legacy_secrets dest_dir [legacy_dir=/run/secrets] → one-time migration
# for installs created before AI-397, when secrets lived in the tmpfs
# /run/secrets (wiped on every reboot). If the persistent dest_dir is missing a
# secret but the legacy dir still holds it — a box that hasn't rebooted yet —
# copy the value across so the password the postgres data volume was initialized
# with is preserved instead of being regenerated into a mismatch.
#
# Idempotent and safe to call before generate_secrets: a no-op when dest_dir
# already has the secret, when the legacy dir is gone (already rebooted, nothing
# to recover), or when dest_dir IS the legacy dir (unchanged install).
migrate_legacy_secrets() {
  local dest_dir="$1" legacy_dir="${2:-/run/secrets}" name
  [ "$dest_dir" = "$legacy_dir" ] && return 0
  [ -d "$legacy_dir" ] || return 0
  ( umask 077; mkdir -p "$dest_dir" )
  chmod 700 "$dest_dir" 2>/dev/null || true
  for name in master_key db_password keycloak_admin_password litellm_master_key admin_password; do
    if [ -f "$legacy_dir/$name" ] && [ ! -f "$dest_dir/$name" ]; then
      cp -p "$legacy_dir/$name" "$dest_dir/$name"
      chmod 600 "$dest_dir/$name"
    fi
  done
}

# ── setup code (AI-1184) ──────────────────────────────────────────────────────
# The setup code binds the setup wizard to whoever ran the installer: the panel
# accepts wizard saves only from a browser that presents it. The code itself
# stays root-only in secrets_dir/setup_token; the panel gets only its SHA-256
# fingerprint (SETUP_TOKEN_SHA256 in .env), so the panel never holds the code.

# sha256_hex → SHA-256 of stdin as 64 lowercase hex characters. sha256sum
# (coreutils), else openssl; neither present fails, like gen_secret_hex's
# portability rule.
sha256_hex() {
  local out
  if command -v sha256sum >/dev/null 2>&1; then
    out="$(sha256sum)"
  elif command -v openssl >/dev/null 2>&1; then
    out="$(openssl dgst -sha256 -r)"
  else
    echo "sha256_hex: neither sha256sum nor openssl is installed" >&2
    return 1
  fi
  printf '%s\n' "${out%% *}"
}

# _setup_token_valid code → 0 when the code is long enough to be a secret.
_setup_token_valid() {
  [ "${#1}" -ge 32 ]
}

# _write_setup_token secrets_dir env_file code → store the code (0600) and its
# fingerprint in .env, replacing both.
_write_setup_token() {
  local secrets_dir="$1" env_file="$2" code="$3" fp
  fp="$(printf '%s' "$code" | sha256_hex)" || return 1
  ( umask 077; mkdir -p "$secrets_dir"; printf '%s' "$code" >"$secrets_dir/setup_token.tmp" )
  chmod 600 "$secrets_dir/setup_token.tmp"
  mv "$secrets_dir/setup_token.tmp" "$secrets_dir/setup_token"
  env_set "$env_file" SETUP_TOKEN_SHA256 "$fp"
}

# setup_token_ensure secrets_dir env_file → the install step. Uses SETUP_TOKEN
# when supplied (minimum 32 characters), else generates 16 random bytes as hex.
# A re-run reuses the stored code and re-derives the fingerprint, so a link
# printed by an earlier run keeps working; a supplied SETUP_TOKEN that differs
# from the stored code stops instead of silently replacing it.
setup_token_ensure() {
  local secrets_dir="$1" env_file="$2" code=""
  if [ -n "${SETUP_TOKEN:-}" ] && ! _setup_token_valid "$SETUP_TOKEN"; then
    echo "SETUP_TOKEN must be at least 32 characters" >&2
    return 1
  fi
  if [ -s "$secrets_dir/setup_token" ]; then
    code="$(cat "$secrets_dir/setup_token")"
    if [ -n "${SETUP_TOKEN:-}" ] && [ "$SETUP_TOKEN" != "$code" ]; then
      echo "a setup code already exists; use --new-setup-token to replace it" >&2
      return 1
    fi
  elif [ -n "${SETUP_TOKEN:-}" ]; then
    code="$SETUP_TOKEN"
  else
    code="$(gen_secret_hex 16)" || return 1
  fi
  _write_setup_token "$secrets_dir" "$env_file" "$code"
}

# setup_token_rotate secrets_dir env_file → --new-setup-token: always writes a
# new code (SETUP_TOKEN when supplied, else generated) and its fingerprint.
setup_token_rotate() {
  local secrets_dir="$1" env_file="$2" code
  if [ -n "${SETUP_TOKEN:-}" ]; then
    _setup_token_valid "$SETUP_TOKEN" || { echo "SETUP_TOKEN must be at least 32 characters" >&2; return 1; }
    code="$SETUP_TOKEN"
  else
    code="$(gen_secret_hex 16)" || return 1
  fi
  _write_setup_token "$secrets_dir" "$env_file" "$code"
}

# ── .env mutation (NEVER truncate) ────────────────────────────────────────────

# env_set env_file KEY VALUE → set KEY=VALUE in env_file.
# If a line `^KEY=` exists, replace ONLY that line (preserving every other line
# and its order); otherwise append `KEY=VALUE`. The file is created 600 if
# missing. This is the fix for gomemlimit-env-clobber: callers must use this
# instead of `echo KEY=VALUE > .env`, which wipes the file.
env_set() {
  local env_file="$1" key="$2" value="$3"

  # Create with restrictive perms if absent so we never widen perms later.
  if [ ! -f "$env_file" ]; then
    ( umask 077; : >"$env_file" )
    chmod 600 "$env_file"
  fi

  local newline="${key}=${value}"

  # Does the key already exist? Match the literal `KEY=` prefix at line start.
  if grep -q "^${key}=" "$env_file" 2>/dev/null; then
    # Replace just that line. Build the new file in a temp, then atomic mv.
    # We avoid sed/awk metacharacter pitfalls in VALUE by reading line by line
    # and substituting the matching line with the pre-built literal.
    local tmp
    tmp="$(mktemp "${env_file}.XXXXXX")"
    local line replaced=0
    while IFS= read -r line || [ -n "$line" ]; do
      case "$line" in
        "${key}="*)
          if [ "$replaced" -eq 0 ]; then
            printf '%s\n' "$newline" >>"$tmp"
            replaced=1
          fi
          # Drop any duplicate KEY= lines beyond the first.
          ;;
        *)
          printf '%s\n' "$line" >>"$tmp"
          ;;
      esac
    done <"$env_file"
    chmod 600 "$tmp"
    mv "$tmp" "$env_file"
  else
    printf '%s\n' "$newline" >>"$env_file"
  fi
}

# ── permission self-healing ───────────────────────────────────────────────────

# harden_perms secrets_dir env_file → re-assert restrictive perms.
# Idempotent and re-runnable: 700 on the secrets dir, 600 on every secret file
# inside it and on the env file. Safe to call repeatedly (self-healing).
# Exception: openbao_unseal_key stays 644 — harden_perms runs AFTER
# generate_secrets in the install flow, and sweeping the key to 600 would
# re-break the openbao boot in the same run (the image's non-root server
# reads it through the ro secret mount; see generate_secrets). The 0700 dir
# is what keeps it host-confidential.
harden_perms() {
  local secrets_dir="$1" env_file="$2" f
  if [ -d "$secrets_dir" ]; then
    chmod 700 "$secrets_dir"
    for f in "$secrets_dir"/*; do
      [ -f "$f" ] || continue
      if [ "$(basename "$f")" = "openbao_unseal_key" ]; then
        chmod 644 "$f"
      else
        chmod 600 "$f"
      fi
    done
  fi
  [ -f "$env_file" ] && chmod 600 "$env_file"
  return 0
}

# ===== scripts/lib/openbao.sh =====
# OpenBao config rendering. Sourced by install.sh (bundled via build-installer.sh).
# The unseal key itself is generated by generate_secrets (secrets.sh) so all
# secret material lives in one place with one permission model.

# write_openbao_config <config_dir>
# Renders the OpenBao server HCL. Idempotent: rewrites only when content differs.
#
# Permissions are deliberately world-readable (dir 755, file 644): the
# openbao/openbao image's entrypoint drops privileges to its non-root
# `openbao` user, and its chown -R of /openbao/config silently fails on our
# :ro bind mount — a root-only 640 config makes `bao server` crash-loop on
# "permission denied" and the panel (depends_on: service_healthy) never
# starts. This is safe: the config contains NO secret material, only a
# file:// pointer to the separately-protected 0600
# /run/secrets/openbao_unseal_key. (BAO_SKIP_DROP_ROOT would also "fix" it,
# but running OpenBao as root is a worse posture than a world-readable
# pointer file.)
write_openbao_config() {
  local config_dir="$1"
  mkdir -p "${config_dir}"
  chmod 755 "${config_dir}"
  local target="${config_dir}/openbao.hcl"
  local tmp
  # mktemp NEXT TO the target (same filesystem): a /tmp temp file breaks the
  # final mv with "Invalid cross-device link" when /tmp is a separate mount
  # (tmpfs, hardened hosts). Same idiom as secrets.sh env_set().
  tmp="$(mktemp "${target}.XXXXXX")"
  cat > "${tmp}" <<'EOF'
# Generated by the AAP installer. Managed file - do not edit by hand.
# static seal: unattended auto-unseal from the compose-mounted key file.
# Protects data-at-rest (stolen volume/backup); NOT a defense against full
# host compromise - see docs/runbooks/openbao.md for the threat model.
ui = false

listener "tcp" {
  address     = "0.0.0.0:8200"
  tls_disable = true
}

# Raft lives in /openbao/file: it's the ONLY storage dir the image
# pre-creates (openbao:openbao) and its entrypoint chowns for the non-root
# server user. The image ships no /openbao/data - mounting a volume there
# creates a root-owned mountpoint the dropped-privilege server can't write
# ("open /openbao/data/node-id: permission denied" crash-loop).
storage "raft" {
  path = "/openbao/file"
}

seal "static" {
  current_key_id = "install-1"
  current_key    = "file:///run/secrets/openbao_unseal_key"
}

# Declarative audit device: OpenBao (unlike upstream Vault) hard-rejects
# API-based audit creation (400 "use declarative, config-based audit device
# management instead" - verified against a live 2.5.5 container, AI-558), so
# the spec-mandated file audit device must be declared here; the panel's
# Bootstrapper only verifies it exists at first boot. The log lives under
# /openbao/logs - alongside /openbao/file it's one of only two dirs the image
# pre-creates for (and its entrypoint chowns to) the non-root server user;
# anywhere else is unwritable (same failure class as the raft /openbao/data
# crash-loop above). Compose mounts a named volume there so the audit trail
# survives container recreation.
audit "file" "file" {
  description = "AAP file audit device"
  options {
    file_path = "/openbao/logs/audit.log"
  }
}

cluster_addr = "http://openbao:8201"
api_addr     = "http://openbao:8200"
disable_mlock = true
EOF
  if [ -f "${target}" ] && cmp -s "${tmp}" "${target}"; then
    rm -f "${tmp}"
    return 0
  fi
  mv "${tmp}" "${target}"
  chmod 644 "${target}"
}

# write_openbao_log_rotate_script <openbao_dir>
# Renders the audit-log rotation script the compose `openbao_log_rotator`
# sidecar runs. Idempotent: rewrites only when content differs.
#
# WHY (AI-611): OpenBao's declarative file audit device appends every audited
# request to /openbao/logs/audit.log with NO built-in rotation or size cap.
# On a long-running box that file grows unbounded — the demo hit 128 GB, filled
# the disk, and crash-looped Postgres + OpenBao ("No space left on device").
# OpenBao has no native size limit and rejects API-based audit management
# (AI-558), so the file must be bounded externally.
#
# The rotator uses copytruncate (cp then `: >`) rather than a rename: the audit
# device holds audit.log open with O_APPEND, so truncating the SAME inode in
# place keeps its open fd writing to the now-small live file. A mv/rename would
# leave the device writing to the rotated-away inode until a SIGHUP — which we
# can't send across containers without the Docker socket. Written NEXT TO the
# config dir (not inside it) so the ":ro config holds only openbao.hcl" contract
# and `bao server -config=<file>` (which ignores siblings) both stay intact.
write_openbao_log_rotate_script() {
  local openbao_dir="$1"
  mkdir -p "${openbao_dir}"
  local target="${openbao_dir}/openbao-log-rotate.sh"
  local tmp
  tmp="$(mktemp "${target}.XXXXXX")"
  cat > "${tmp}" <<'EOF'
#!/bin/sh
# Generated by the AAP installer. Managed file - do not edit by hand.
# Bounds the OpenBao file audit device's audit.log (AI-611). Runs in the
# openbao_log_rotator compose sidecar (reusing the openbao image). Config via
# env: AUDIT_LOG_PATH, AUDIT_LOG_MAX_BYTES, AUDIT_LOG_KEEP, AUDIT_LOG_INTERVAL.
set -u
# AI-2341: the audit trail is owner-only. Files this script creates are 0600.
umask 077

# rotate_once: if the audit log exceeds the cap, shift the kept backups
# (.N-1 -> .N ... .1 -> .2), copy the live log to .1, then truncate it IN PLACE
# so the audit device's open O_APPEND fd keeps writing to the same (now-empty)
# inode. Reads config from the environment on every call.
rotate_once() {
  f="${AUDIT_LOG_PATH:-/openbao/logs/audit.log}"
  max="${AUDIT_LOG_MAX_BYTES:-104857600}"
  keep="${AUDIT_LOG_KEEP:-5}"
  [ -f "$f" ] || return 0
  sz="$(stat -c %s "$f" 2>/dev/null || wc -c < "$f" 2>/dev/null || echo 0)"
  [ "$sz" -le "$max" ] && return 0
  i="$keep"
  while [ "$i" -gt 1 ]; do
    prev=$((i - 1))
    [ -f "$f.$prev" ] && mv -f "$f.$prev" "$f.$i"
    i="$prev"
  done
  if [ "$keep" -ge 1 ]; then
    cp "$f" "$f.1"          # copytruncate step 1: snapshot current log
  fi
  : > "$f"                  # copytruncate step 2: empty in place (same inode)
  # AI-2341: cp copies the live file's mode, so a rotated copy (and one left
  # by an older rotator) is made owner-only explicitly.
  i=1
  while [ "$i" -le "$keep" ]; do
    [ -f "$f.$i" ] && chmod 600 "$f.$i"
    i=$((i + 1))
  done
  return 0
}

# AUDIT_LOG_DEFINE_ONLY lets the bats suite source this file for rotate_once
# without entering the daemon loop.
if [ "${AUDIT_LOG_DEFINE_ONLY:-0}" = "1" ]; then
  # shellcheck disable=SC2317  # reachable when EXECUTED (not sourced) with the flag
  return 0 2>/dev/null || exit 0
fi

while :; do
  rotate_once
  sleep "${AUDIT_LOG_INTERVAL:-120}"
done
EOF
  if [ -f "${target}" ] && cmp -s "${tmp}" "${target}"; then
    rm -f "${tmp}"
    chmod 755 "${target}"
    return 0
  fi
  mv "${tmp}" "${target}"
  chmod 755 "${target}"
}

# ===== scripts/lib/manageddns.sh =====
# scripts/lib/manageddns.sh — temporary-domain claim path (AI-544 plan 2).
# When the user has no domain, claims an aap-…aiadminpanel.host name from the
# managed-dns claim service (infra/managed-dns/ — FROZEN API contract in its
# README; this module encodes but never drifts it) and persists the claim token
# for the panel backend's lease renewal (plan 3).
#
# Contract facts encoded here:
#   POST /v1/claims        no auth, rate limit 3/day/IP, IPv4 only (curl -4),
#                          201 {"domain","token","leaseExpiresAt"}
#   GET  /v1/claims/status Authorization: Bearer <token>,
#                          200 {"domain","emailVerified","leaseExpiresAt","lastRenewedAt"}
#                          401/410 = the claim is dead (lapsed/released)
#   NEVER send CF-Connecting-IP — Cloudflare rejects spoofed copies of its
#   managed header (edge error 1000/403). Real callers just POST; CF sets it.
#
# SECURITY (Rule 11): the token is shown exactly once by the API. It is written
# 0600 under SECRETS_DIR immediately and NEVER logged — no debug/info of any
# response body in this module.
#
# Consumes: info/warn (lib/log.sh); _resolve_domain, _box_public_ip,
# dns_matches and tls_mode_is_dns01 (lib/preflight.sh) from
# md_wait_for_dns — bundle order is irrelevant, functions resolve at call time.
# Consumed by: prompt_domain / generate_env_file / print_success (install.sh.in).

# Guarded logging fallback: inert once log.sh is bundled/sourced first (real
# installer), active when this module is unit-tested in isolation. Mirrors
# scripts/lib/docker.sh + preflight.sh so the bats file never sources log.sh
# (whose run() would clobber bats' own run() test helper).
if ! declare -F info >/dev/null 2>&1; then
  info() { printf '[INFO] %s\n' "$*"; }
  warn() { printf '[WARN] %s\n' "$*" >&2; }
fi

MANAGED_DNS_URL="${MANAGED_DNS_URL:-https://dns.aiadminpanel.com}"
# Sleep seconds between claim attempts (1 initial + one retry per entry ≈ 2 min
# total, per spec). Tests override with "0 0 0".
MD_RETRY_DELAYS="${MD_RETRY_DELAYS:-20 40 60}"

# Forward-declared cross-file state consumed by sibling bundled modules
# (install.sh.in prompt_domain/generate_env_file/print_success, Tasks 2-3).
# Exported (docker.sh:238 AAP_NVIDIA_RUNTIME_READY precedent) so the SC2034
# "appears unused" warning stays clean — the linter can't see cross-file reads.
# Secret-safe: MD_TOKEN_FILE is a path; the token itself stays a local in Task 2.
export MD_CLAIMED=false     # true once this run claimed (or reused) a managed domain
export MD_BASE_URL=""       # base URL the claim actually used → .env MANAGED_DNS_URL
export MD_LEASE_EXPIRES=""  # leaseExpiresAt from the claim/status response → success text
export MD_FAIL_REASON=""    # human-readable failure for the caller to warn/error with
export MD_REUSED_DOMAIN=""  # set by md_reuse_claim
export MD_TOKEN_FILE=""     # set by md_acquire_domain from SECRETS_DIR

# md_json_field <json> <key> — extract a string field from a flat JSON object
# without jq (not installed at domain-prompt time; ensure_updater_deps runs much
# later). Safe ONLY for our own Worker's responses: values are URL/hostname/ISO
# material and never contain escaped quotes.
md_json_field() {
  local json="$1" key="$2"
  printf '%s' "$json" | sed -n 's/.*"'"$key"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p'
}

# md_claim — POST /v1/claims. Prints the 201 body on success.
# Returns: 0 claimed · 1 unreachable/5xx after all retries · 2 rate-limited
#          3 ipv6-unsupported · 4 other 400. Only network errors / 5xx retry.
md_claim() {
  local out code body delay
  # shellcheck disable=SC2086  # intentional word-split of the delay list
  for delay in 0 $MD_RETRY_DELAYS; do
    if [ "$delay" -gt 0 ]; then
      info "Claim service not reachable — retrying in ${delay}s..."
      sleep "$delay"
    fi
    out=$(curl -4 -sS --max-time 15 -X POST "${MANAGED_DNS_URL}/v1/claims" \
      -H 'Content-Type: application/json' -d '{}' \
      -w $'\n%{http_code}' 2>/dev/null) || out=""
    code="${out##*$'\n'}"
    body="${out%$'\n'*}"
    case "$code" in
      201) printf '%s' "$body"; return 0 ;;
      429) return 2 ;;
      400)
        case "$body" in
          *ipv6_unsupported*) return 3 ;;
          *) return 4 ;;
        esac
        ;;
      *) : ;; # empty (network error) or 5xx — retry
    esac
  done
  return 1
}

# md_reuse_claim — if a token from a previous run exists, ask the service which
# domain it belongs to and reuse it: installer re-runs after a mid-install
# failure must never burn the 3/day/IP quota or orphan the earlier claim.
# rc 0: sets MD_REUSED_DOMAIN + MD_LEASE_EXPIRES. rc 1: nothing reusable
# (a dead token — 401/410 — is deleted; transient errors fall through to the
# claim path, which carries the retry/fail-loud policy).
md_reuse_claim() {
  MD_REUSED_DOMAIN=""
  [ -f "$MD_TOKEN_FILE" ] || return 1
  local token out code body
  token="$(cat "$MD_TOKEN_FILE")"
  if [ -z "$token" ]; then
    rm -f "$MD_TOKEN_FILE"
    return 1
  fi
  out=$(curl -4 -sS --max-time 15 "${MANAGED_DNS_URL}/v1/claims/status" \
    -H "Authorization: Bearer ${token}" -w $'\n%{http_code}' 2>/dev/null) || out=""
  code="${out##*$'\n'}"
  body="${out%$'\n'*}"
  case "$code" in
    200)
      MD_REUSED_DOMAIN="$(md_json_field "$body" domain)"
      MD_LEASE_EXPIRES="$(md_json_field "$body" leaseExpiresAt)"
      [ -n "$MD_REUSED_DOMAIN" ] || return 1
      return 0
      ;;
    401 | 410)
      warn "Stored temporary-domain token is no longer valid — claiming a fresh domain."
      rm -f "$MD_TOKEN_FILE"
      return 1
      ;;
    *) return 1 ;;
  esac
}

# md_acquire_domain — reuse-or-claim a managed temporary domain.
# rc 0: PANEL_DOMAIN set, MD_CLAIMED=true, MD_BASE_URL set, token persisted 0600.
# rc 1: MD_FAIL_REASON set; the caller decides re-prompt (interactive) vs
#       error (unattended/piped).
# Call DIRECTLY, never in $(…) — it sets globals. Call it only in an
# errexit-exempt context (a bare `md_acquire_domain || …` or an `if`/`elif`
# condition, as both current callers do): under `set -e` the internal
# `body="$(md_claim)"; rc=$?` capture would abort the script on a non-zero
# claim before the MD_FAIL_REASON logic runs, silently breaking the
# fail-reason UX. bash disables -e for the whole dynamic extent of a function
# invoked in those contexts, which is why the current call sites are safe.
md_acquire_domain() {
  MD_TOKEN_FILE="${SECRETS_DIR:-/opt/aiadminpanel/secrets}/managed_domain_token"
  MD_BASE_URL="$MANAGED_DNS_URL"
  MD_FAIL_REASON=""
  local body rc domain token

  if md_reuse_claim; then
    PANEL_DOMAIN="$MD_REUSED_DOMAIN"
    MD_CLAIMED=true
    info "Reusing temporary domain from a previous run: ${PANEL_DOMAIN}"
    md_wait_for_dns "$PANEL_DOMAIN"
    return 0
  fi

  info "Claiming a free temporary domain from ${MANAGED_DNS_URL} ..."
  body="$(md_claim)"
  rc=$?
  if [ "$rc" -ne 0 ]; then
    case "$rc" in
      2) MD_FAIL_REASON="Temporary-domain limit reached (3 per IP per day). Enter your own domain, or retry after 24 hours." ;;
      3) MD_FAIL_REASON="This box has no IPv4 egress (temporary domains are IPv4-only for now). Use your own domain instead." ;;
      4) MD_FAIL_REASON="The claim service rejected the request. Re-run the installer, or set PANEL_DOMAIN to your own domain." ;;
      *) MD_FAIL_REASON="Claim service unreachable after 3 retries (~2 min). Re-run the installer, or set PANEL_DOMAIN to your own domain." ;;
    esac
    return 1
  fi

  domain="$(md_json_field "$body" domain)"
  token="$(md_json_field "$body" token)"
  MD_LEASE_EXPIRES="$(md_json_field "$body" leaseExpiresAt)"
  if [ -z "$domain" ] || [ -z "$token" ]; then
    MD_FAIL_REASON="Claim service returned an unexpected response. Re-run the installer, or set PANEL_DOMAIN to your own domain."
    return 1
  fi

  # Persist the token IMMEDIATELY — the API shows it exactly once and losing it
  # loses lease renewal. create_directories runs later in main(), so make the
  # secrets dir ourselves. Never log the token (Rule 11).
  mkdir -p "$(dirname "$MD_TOKEN_FILE")"
  chmod 700 "$(dirname "$MD_TOKEN_FILE")"
  printf '%s' "$token" > "$MD_TOKEN_FILE"
  chmod 600 "$MD_TOKEN_FILE"

  PANEL_DOMAIN="$domain"
  MD_CLAIMED=true
  info "Claimed temporary domain: ${PANEL_DOMAIN}"
  info "Claim token stored at ${MD_TOKEN_FILE} (root-only; used for lease renewal — keep it)."
  md_wait_for_dns "$PANEL_DOMAIN"
  return 0
}

# md_wait_for_dns <domain> — absorb resolver lag on a seconds-old record so the
# unchanged check_dns preflight doesn't hard-fail. Skips in DNS-01 TLS mode
# (check_dns skips there too). Warn-and-continue on timeout — check_dns stays
# the hard gate. MD_DNS_WAIT_INTERVAL exists for tests (default 5s × 12 = 60s).
md_wait_for_dns() {
  local domain="$1" i resolved box_ip
  tls_mode_is_dns01 && return 0
  box_ip="$(_box_public_ip || true)"
  if [ -z "$box_ip" ]; then
    warn "Could not determine this box's public IPv4 — DNS readiness is unconfirmed. Continuing to pre-flight, which retries public-IP detection."
    return 0
  fi
  info "Waiting for ${domain} to resolve to ${box_ip} (up to 60s of retry delays)..."
  for ((i = 1; i <= 12; i++)); do
    resolved="$(_resolve_domain "$domain" || true)"
    if dns_matches "$resolved" "$box_ip"; then
      info "DNS ready: ${domain} resolves to ${box_ip} (this box)."
      return 0
    fi
    sleep "${MD_DNS_WAIT_INTERVAL:-5}"
  done
  warn "${domain} does not resolve to ${box_ip} yet — continuing; the pre-flight DNS check is the hard gate. Keep the saved claim token and re-run the installer to reuse this domain."
  return 0
}

# ===== scripts/lib/docker.sh =====
# scripts/lib/docker.sh — universal Docker Engine + Compose/Buildx install (AI-349).
#
# Replaces install.sh's get.docker.com + apt-only-plugin path (which is redundant
# where get.docker.com works and broken everywhere else). Strategy:
#   1. Fast-path: real Docker >= 24 with compose + buildx and NOT a podman shim.
#   2. get.docker.com for the IDs it supports (it bundles compose + buildx).
#   3. Native per-package-manager repo branches for the IDs it refuses
#      (AlmaLinux, Oracle, Amazon Linux, SUSE, Arch).
#   4. Always `systemctl enable --now docker`, then ASSERT tooling.
#
# Relies on platform.sh globals: OS_ID, OS_FAMILY, OS_VERSION_MAJOR, OS_PRETTY.
# Pure function definitions only (the bootstrap owns `set -euo pipefail`).

# Self-contained logging fallbacks for standalone use — install.sh provides
# richer versions and (because these are guarded) its definitions win when this
# is sourced into it. NOTE: deliberately does NOT define `run` — that would
# clobber bats's own `run` helper in unit tests; the side-effecting functions
# get `run` from install.sh (lib/log.sh) at integration time.
if ! declare -F info >/dev/null 2>&1; then
  info() { printf '[INFO] %s\n' "$*"; }
  warn() { printf '[WARN] %s\n' "$*" >&2; }
  error() {
    printf '[ERROR] %s\n' "$*" >&2
    return 1
  }
fi

# ── Strategy selection (pure) ────────────────────────────────────────────────
# Strategy by ID. get.docker.com cleanly handles the apt family (ubuntu/debian/
# raspbian) and Fedora (clean $releasever major). For the RHEL family we
# DELIBERATELY use our own native dnf branch instead of get.docker.com: Docker's
# repo file embeds $releasever, which on a POINT release (Rocky 9.7, RHEL 9.4, …)
# resolves to e.g. "9.7" and 404s download.docker.com — empty repodata, then
# `Error: Unable to find a match: docker-ce`. get.docker.com does NOT pin it, so
# it breaks on point releases (observed on Rocky 9.7). Our dnf branch pins
# $releasever to the major (AI-349).
docker_repo_strategy() {
  case "$OS_ID" in
    ubuntu | debian | raspbian | fedora) echo "getdocker"; return ;;
    centos | rhel | rocky | almalinux | ol | oracle | scientific | cloudlinux | virtuozzo) echo "dnf"; return ;;
    amzn) echo "amzn2023"; return ;;
    opensuse | opensuse-leap | opensuse-tumbleweed | opensuse-slowroll | sles | sled | suse) echo "zypper"; return ;;
    arch | manjaro | endeavouros | artix | cachyos | garuda | arcolinux) echo "pacman"; return ;;
  esac
  # ID not explicitly known — fall back to the family's native package manager.
  case "$OS_FAMILY" in
    debian) echo "apt" ;;
    rhel) echo "dnf" ;;
    suse) echo "zypper" ;;
    arch) echo "pacman" ;;
    *) echo "unsupported" ;;
  esac
}

# Docker's RHEL-family repos: centos repo for el9, rhel repo for el10 / RHEL.
_dnf_docker_repo_url() {
  local id="$1" major="$2"
  if [ "$id" = "rhel" ] || [ "${major:-0}" -ge 10 ]; then
    echo "https://download.docker.com/linux/rhel/docker-ce.repo"
  else
    echo "https://download.docker.com/linux/centos/docker-ce.repo"
  fi
}

# ── Fast-path predicate ──────────────────────────────────────────────────────
docker_tooling_ok() {
  command -v docker >/dev/null 2>&1 || return 1
  # podman-docker shim presents `docker` but is not real Docker.
  if docker version 2>/dev/null | grep -qi podman; then return 1; fi
  local major
  major="$(docker --version 2>/dev/null | grep -oE '[0-9]+' | head -1)"
  [ -n "$major" ] || return 1
  [ "$major" -ge 24 ] || return 1
  docker compose version >/dev/null 2>&1 || return 1
  docker buildx version >/dev/null 2>&1 || return 1
  return 0
}

# ── Native install branches (side-effecting; exercised in Layer-B matrix) ─────
_curl_https() { curl --proto '=https' --tlsv1.2 -fsSL "$@"; }

_docker_install_convenience() {
  info "Installing Docker via get.docker.com (engine + compose + buildx)..."
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] curl --proto '=https' --tlsv1.2 -fsSL https://get.docker.com | sh"
    return 0
  fi
  local tmp="/tmp/aap-get-docker.sh"
  _curl_https https://get.docker.com -o "$tmp" || error "Failed to download get.docker.com" || return 1
  sh "$tmp" || error "get.docker.com install failed on ${OS_PRETTY:-$OS_ID}" || return 1
  rm -f "$tmp"
}

_dnf_add_docker_repo() {
  local url="$1"
  run dnf -y install dnf-plugins-core
  # dnf4 uses `config-manager --add-repo`; dnf5 uses `config-manager addrepo --from-repofile`.
  if ! run dnf config-manager --add-repo "$url" 2>/dev/null; then
    run dnf config-manager addrepo --from-repofile="$url"
  fi
  # Pin $releasever to the major so a point-release (e.g. 9.5) can't 404.
  run sed -i "s/\$releasever/${OS_VERSION_MAJOR}/g" /etc/yum.repos.d/docker-ce.repo
}

_docker_install_dnf() {
  info "Installing Docker from the native dnf repo for ${OS_PRETTY:-$OS_ID}..."
  _dnf_add_docker_repo "$(_dnf_docker_repo_url "$OS_ID" "$OS_VERSION_MAJOR")"
  _ensure_kernel_modules_extra
  run dnf -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
}

# el10 (Rocky/AlmaLinux/RHEL 10) minimal & cloud images ship WITHOUT
# kernel-modules-extra. Without it dockerd fails to start: iptables can't load
# the xt_addrtype module Docker needs for its NAT rules. Install the package
# matched to the RUNNING kernel (an unversioned install could pull a different
# kernel). Only attempted on el10+; a no-op on el8/el9 where it's already present.
# Matched-only so it's harmless inside CI containers (host kernel ≠ repo). (AI-349)
_ensure_kernel_modules_extra() {
  [ "${OS_VERSION_MAJOR:-0}" -ge 10 ] || return 0
  info "Ensuring kernel-modules-extra for the running kernel (el10 needs xt_addrtype for Docker's NAT)..."
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info '[dry] dnf -y install kernel-modules-extra-$(uname -r)'
    return 0
  fi
  dnf -y install "kernel-modules-extra-$(uname -r)" >/dev/null 2>&1 ||
    warn "kernel-modules-extra-$(uname -r) not installable from the repo; if dockerd fails to start (xt_addrtype error), install kernel-modules-extra matching your kernel and reboot."
}

_docker_install_amzn() {
  info "Installing Docker from the Amazon Linux docker-ce repo (best-effort)..."
  _dnf_add_docker_repo "https://download.docker.com/linux/amazonlinux/docker-ce.repo"
  run dnf -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
}

_docker_install_zypper() {
  info "Installing Docker on SUSE (document-only / best-effort)..."
  # Prefer the distro's own packages (versions lag but are integrated); fall back
  # to docker.com's SLES repo.
  if ! run zypper --non-interactive install -y docker docker-compose docker-buildx; then
    run zypper --non-interactive addrepo https://download.docker.com/linux/sles/docker-ce.repo
    run zypper --non-interactive --gpg-auto-import-keys refresh
    run zypper --non-interactive install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin docker-buildx-plugin
  fi
}

_docker_install_pacman() {
  info "Installing Docker on Arch (document-only / best-effort)..."
  run pacman -Sy --noconfirm docker docker-compose docker-buildx
}

_docker_install_apt_native() {
  info "Installing Docker from Docker's apt repo (debian-derivative, best-effort)..."
  local codename="${UBUNTU_CODENAME:-${VERSION_CODENAME:-}}"
  if [ -z "$codename" ]; then
    # Last resort: try the convenience script (it may still match via os-release).
    _docker_install_convenience
    return
  fi
  run apt-get update -y
  run apt-get install -y ca-certificates curl
  run install -m 0755 -d /etc/apt/keyrings
  local base="https://download.docker.com/linux/ubuntu"
  [ "$OS_FAMILY" = "debian" ] && case "$OS_ID_LIKE" in *debian*) base="https://download.docker.com/linux/debian" ;; esac
  run sh -c "curl --proto '=https' --tlsv1.2 -fsSL ${base}/gpg -o /etc/apt/keyrings/docker.asc"
  run chmod a+r /etc/apt/keyrings/docker.asc
  run sh -c "echo 'deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] ${base} ${codename} stable' > /etc/apt/sources.list.d/docker.list"
  run apt-get update -y
  run apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
}

# ── Daemon start + tooling assertion ─────────────────────────────────────────
_docker_enable_daemon() {
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] systemctl enable --now docker"
    return 0
  fi
  run systemctl enable --now docker || warn "systemctl enable --now docker returned non-zero"
  local i=0
  while [ "$i" -lt 30 ]; do
    docker info >/dev/null 2>&1 && return 0
    sleep 1
    i=$((i + 1))
  done
  warn "Docker daemon did not become ready within 30s"
}

# Asserts compose + buildx + an active daemon. NEVER apt-get the plugins (the old
# bug): get.docker.com / the native repo already install them, so a miss here is
# a real failure, not something to paper over.
verify_docker_tooling() {
  if [ "${DRY_RUN:-false}" = "true" ]; then return 0; fi
  docker compose version >/dev/null 2>&1 ||
    error "Docker Compose v2 plugin missing after install on ${OS_PRETTY:-$OS_ID}. Install 'docker-compose-plugin' from Docker's repo and re-run."
  docker buildx version >/dev/null 2>&1 ||
    error "Docker Buildx plugin missing after install on ${OS_PRETTY:-$OS_ID}. Install 'docker-buildx-plugin' from Docker's repo and re-run."
  systemctl is-active --quiet docker 2>/dev/null || warn "docker.service is not active"
  info "Docker tooling verified: $(docker compose version 2>/dev/null | head -1)"
}

# ── Orchestrator ─────────────────────────────────────────────────────────────
install_docker() {
  if docker_tooling_ok; then
    info "Docker $(docker --version 2>/dev/null) already present with compose+buildx — skipping install"
  else
    # Read by docker_install_time_pools: a Docker this run installed is fresh.
    AAP_DOCKER_INSTALLED_NOW=true
    local strat
    strat="$(docker_repo_strategy)"
    info "Installing Docker via strategy '${strat}' for ${OS_PRETTY:-$OS_ID}"
    case "$strat" in
      getdocker) _docker_install_convenience ;;
      dnf) _docker_install_dnf ;;
      amzn2023) _docker_install_amzn ;;
      zypper) _docker_install_zypper ;;
      pacman) _docker_install_pacman ;;
      apt) _docker_install_apt_native ;;
      *) error "No Docker install path for '${OS_ID}' (${OS_FAMILY}). Install Docker Engine 24+ with the compose & buildx plugins manually, then re-run." || return 1 ;;
    esac
  fi
  _docker_enable_daemon
  verify_docker_tooling
}

# ── Docker 28 for the egress guard's host-port rule (AI-2141) ────────────────
# The container egress guard (aap-egress-guard.sh) keeps customer apps off this
# server's own ports with a rule that needs the platform's gateway priority,
# which the Docker DAEMON supports from release 28. On an older daemon the
# guard applies only its metadata block and reports unsupported; this says so
# at setup in words an operator can act on. The convenience script and
# Docker's own repositories install the current release (29 on 2026-11-06);
# distribution packages (openSUSE's zypper `docker`, some derivatives) can be
# older, which is why a fresh install is checked too. A warning, not a stop:
# the panel works, one protection is off, and the operator decides when to
# upgrade Docker.
AAP_DOCKER_HOST_RULE_MIN=28

docker_host_rule_check() {
  if [ "${DRY_RUN:-false}" = "true" ]; then return 0; fi
  local version
  # The server version: a newer client against an older daemon is still old.
  version="$(docker version --format '{{.Server.Version}}' 2>/dev/null)" || return 0
  [[ "$version" =~ ^([0-9]+)\. ]] || return 0
  [ "${BASH_REMATCH[1]}" -ge "$AAP_DOCKER_HOST_RULE_MIN" ] && return 0
  if [ "${AAP_DOCKER_INSTALLED_NOW:-false}" = "true" ]; then
    warn "The Docker package of ${OS_PRETTY:-this distribution} installed Docker ${version}."
  fi
  warn "Docker ${version} is older than Docker ${AAP_DOCKER_HOST_RULE_MIN}: the egress guard's host-port rule is off, so customer apps can reach this server's own ports. The cloud-metadata block still applies."
  warn "To turn the rule on: upgrade Docker Engine to ${AAP_DOCKER_HOST_RULE_MIN} or later (https://docs.docker.com/engine/install/), then run: sudo bash install.sh --refresh-updater"
  return 0
}

# ── Address pools for many small networks (AI-1446) ──────────────────────────
# Docker's built-in pools hand out fifteen /16 networks from 172.17–31 and
# sixteen /20 from 192.168.0.0/16: about 31 networks per host. The panel uses
# one per customer (AI-832) and one more per multi-container app (AI-1424), so a
# host with ten customers runs out and deploys fail with Docker's raw "all
# predefined address pools have been fully subnetted".
#
# These pools cut 172.18.0.0–172.31.255.255 into /24 networks: 3,584 of them,
# 254 addresses each. Why this range: it is the one Docker already uses on
# every host, so it adds no new clash with a LAN, VPN or cloud network. It
# leaves out 192.168.0.0/16 (the usual home and office LAN), 172.16.0.0/16
# (common for VPNs) and 172.17.0.0/16 (docker0's usual address), and keeps
# clear of the 10.x ranges that cloud networks use (for example Google's
# 10.128.0.0/9 and Hetzner's 10.0.0.0/16). Networks created before the change
# keep their subnets; Docker skips the /24s inside them (checked on Docker 29).
AAP_DOCKER_ADDRESS_POOLS='[{"base":"172.18.0.0/15","size":24},{"base":"172.20.0.0/14","size":24},{"base":"172.24.0.0/13","size":24}]'

# Seconds to wait for the daemon after a restart. Generous, because a rollback
# on a slow host would restart every container a second time for nothing.
AAP_DOCKER_READY_WAIT="${AAP_DOCKER_READY_WAIT:-90}"

# Where ensure_jq downloads jq. Looked up by absolute path because sudo's
# secure_path on RHEL-family hosts (Rocky, Alma) leaves /usr/local/bin out of
# PATH, so a jq downloaded there is not found by name.
AAP_JQ_FALLBACK="${AAP_JQ_FALLBACK:-/usr/local/bin/jq}"

# aap_find_jq — print the jq to use: the one on PATH, else the downloaded one.
aap_find_jq() {
  local j
  if j="$(command -v jq 2>/dev/null)" && [ -n "$j" ]; then
    printf '%s\n' "$j"
    return 0
  fi
  if [ -x "$AAP_JQ_FALLBACK" ]; then
    printf '%s\n' "$AAP_JQ_FALLBACK"
    return 0
  fi
  return 1
}

# docker_daemon_apply_pools FILE [fresh] — put AAP_DOCKER_ADDRESS_POOLS into
# FILE and set DOCKER_POOLS_RESULT to what happened:
#   created   FILE did not exist; written with the pools only. Until AI-1330
#             a new file on a fresh Docker also pinned "storage-driver":
#             "overlay2" (see configure_docker_daemon in install.sh.in for why
#             that was removed). The optional second argument ("fresh") is
#             still accepted and changes nothing.
#   merged    FILE existed; the pools were added, every other key kept, and
#             the original copied to DOCKER_POOLS_BACKUP first. An empty or
#             whitespace-only file counts as {} (Docker accepts it), and so
#             does a pools key set to null
#   unchanged FILE already has exactly these pools
#   kept      FILE has other pools the operator chose; left alone
# A symlinked FILE is written through: the link stays, its target is merged,
# and the backup and the temporary file sit next to the target.
# Returns 1 without touching FILE when it is not a JSON object, jq is missing,
# or FILE is a symlink to nothing.
docker_daemon_apply_pools() {
  local file="$1" mode="${2:-}" target jq tmp stamp
  DOCKER_POOLS_RESULT=""
  DOCKER_POOLS_BACKUP=""
  if [ -L "$file" ]; then
    target="$(readlink -f "$file")"
    if [ -z "$target" ] || [ ! -f "$target" ]; then
      warn "${file} is a symlink to a missing file; it was not changed."
      return 1
    fi
  else
    target="$file"
  fi
  if [ ! -e "$target" ]; then
    mkdir -p "$(dirname "$target")" || return 1
    : "$mode" # accepted for callers; no longer changes the file (AI-1330)
    printf '{\n  "default-address-pools": %s\n}\n' "$AAP_DOCKER_ADDRESS_POOLS" >"$target" || return 1
    DOCKER_POOLS_RESULT="created"
    return 0
  fi
  if ! jq="$(aap_find_jq)"; then
    warn "jq is not installed, so ${file} cannot be merged safely; it was not changed."
    return 1
  fi
  # Docker reads an empty or whitespace-only file as no settings at all.
  local input="$target"
  if ! grep -q '[^[:space:]]' "$target"; then
    input="$(mktemp)" || return 1
    echo '{}' >"$input"
  fi
  if ! "$jq" -e 'type == "object"' "$input" >/dev/null 2>&1; then
    warn "${file} is not valid JSON (or not a JSON object); it was not changed. Docker refuses to start with it too: fix it, then run this again."
    [ "$input" = "$target" ] || rm -f "$input"
    return 1
  fi
  if "$jq" -e --argjson p "$AAP_DOCKER_ADDRESS_POOLS" '."default-address-pools" == $p' "$input" >/dev/null; then
    DOCKER_POOLS_RESULT="unchanged"
    return 0
  fi
  if "$jq" -e '."default-address-pools" != null' "$input" >/dev/null; then
    warn "${file} already sets its own default-address-pools; left as it is. The panel's capacity follows those pools."
    DOCKER_POOLS_RESULT="kept"
    return 0
  fi
  stamp="$(date -u '+%Y%m%dT%H%M%SZ')"
  DOCKER_POOLS_BACKUP="${target}.aap-backup-${stamp}"
  cp -p "$target" "$DOCKER_POOLS_BACKUP" || { DOCKER_POOLS_BACKUP=""; return 1; }
  # Write next to the target, check the result, then swap it in with one
  # rename, so Docker never sees a half-written file. cp -p carries the mode.
  tmp="$(mktemp "${target}.aap-tmp.XXXXXX")" || return 1
  cp -p "$target" "$tmp" || return 1
  if ! "$jq" --argjson p "$AAP_DOCKER_ADDRESS_POOLS" '. + {"default-address-pools": $p}' "$input" >"$tmp" ||
    ! "$jq" -e 'type == "object"' "$tmp" >/dev/null 2>&1; then
    rm -f "$tmp"
    [ "$input" = "$target" ] || rm -f "$input"
    warn "Could not write the merged ${file}; it was not changed."
    return 1
  fi
  [ "$input" = "$target" ] || rm -f "$input"
  mv "$tmp" "$target" || return 1
  info "Added default-address-pools to ${target}; the original is ${DOCKER_POOLS_BACKUP}"
  DOCKER_POOLS_RESULT="merged"
  return 0
}

_docker_restart_and_wait() {
  systemctl restart docker >/dev/null 2>&1 || true
  local i=0
  while [ "$i" -lt "$AAP_DOCKER_READY_WAIT" ]; do
    docker info >/dev/null 2>&1 && return 0
    sleep 1
    i=$((i + 1))
  done
  return 1
}

# docker_configure_address_pools [FILE] [fresh] — apply the pools and restart
# Docker only when FILE changed. A restart stops and starts EVERY container on
# the host (the panel, its database and all customer apps). If Docker does not
# come back, the previous file is put back (or a created one moved away),
# Docker is restarted again and this returns 1. The rejected file stays next to
# the original as <file>.aap-rejected-<UTC time>.
docker_configure_address_pools() {
  local file="${1:-/etc/docker/daemon.json}" mode="${2:-}" target stamp
  docker_daemon_apply_pools "$file" "$mode" || return 1
  case "$DOCKER_POOLS_RESULT" in
    created | merged) ;;
    *) return 0 ;;
  esac
  info "Restarting Docker to load the new address pools. Every container on this host restarts."
  if _docker_restart_and_wait; then
    info "Docker address pools: $(docker info --format '{{json .DefaultAddressPools}}' 2>/dev/null)"
    return 0
  fi
  target="$file"
  [ -L "$file" ] && target="$(readlink -f "$file")"
  if [ "$DOCKER_POOLS_RESULT" = "merged" ] && [ ! -f "$DOCKER_POOLS_BACKUP" ]; then
    # Never leave Docker with no settings at all: keep the merged file.
    warn "Docker did not start with the new ${file}, and its backup is missing; the file was left in place. Check 'journalctl -u docker'."
    return 1
  fi
  stamp="$(date -u '+%Y%m%dT%H%M%SZ')"
  warn "Docker did not start with the new ${file}. Putting the previous one back; the rejected file is ${target}.aap-rejected-${stamp}."
  if [ "$DOCKER_POOLS_RESULT" = "merged" ]; then
    cp -p "$target" "${target}.aap-rejected-${stamp}"
    cp -p "$DOCKER_POOLS_BACKUP" "$target"
  else
    mv "$target" "${target}.aap-rejected-${stamp}"
  fi
  _docker_restart_and_wait || warn "Docker still does not start. Check 'journalctl -u docker' and ${file}."
  return 1
}

# docker_host_is_fresh — true when this run installed Docker
# (AAP_DOCKER_INSTALLED_NOW=true, set by install_docker) or Docker has no
# container at all. A failing `docker ps` counts as in use.
docker_host_is_fresh() {
  [ "${AAP_DOCKER_INSTALLED_NOW:-false}" = "true" ] && return 0
  local ids
  ids="$(docker ps -aq 2>/dev/null)" || return 1
  [ -z "$ids" ]
}

# docker_install_time_pools [FILE] — the full installer's step. It sets the
# pools only on a fresh Docker. On a host whose
# Docker already runs containers, a re-run of the installer must not restart
# them all: it changes nothing, sets DOCKER_POOLS_RESULT=skipped, and points to
# --docker-address-pools.
docker_install_time_pools() {
  local file="${1:-/etc/docker/daemon.json}"
  if ! docker_host_is_fresh; then
    DOCKER_POOLS_RESULT="skipped"
    DOCKER_POOLS_BACKUP=""
    info "Docker already runs containers on this host, so ${file} was not changed and Docker was not restarted. To let Docker hold more networks, run in a maintenance window: sudo bash install.sh --docker-address-pools (restarts every container)."
    return 0
  fi
  docker_configure_address_pools "$file" fresh
}

# ── NVIDIA Container Toolkit (AI-419) ─────────────────────────────────────────
# A GPU-aware deploy (AI-416 P2) emits Docker DeviceRequests + NVIDIA_VISIBLE_
# DEVICES, which only work once the NVIDIA Container Toolkit is installed AND
# Docker is configured with its `nvidia` runtime. The installer does this
# automatically on a host with an NVIDIA GPU so the operator never touches a
# terminal (Secure · Sovereign · Simple). Idempotent; a no-op on CPU-only hosts.
#
# Relies on platform.sh globals (OS_FAMILY/OS_ID) and preflight.sh
# host_has_nvidia_gpu / host_has_nvidia_driver. Sets AAP_NVIDIA_RUNTIME_READY=true
# when Docker's `nvidia` runtime ends up configured — generate_env_file consumes
# that to give the panel container its own GPU visibility (AI-420 opt 1).
# Set true once Docker's nvidia runtime is configured. Read by install.sh.in
# generate_env_file (AI-420) to give the panel container its own GPU visibility.
# Exported (not merely assigned) to document the cross-module read AND satisfy
# SC2034 — the linter can't see the consumer in another bundled file.
export AAP_NVIDIA_RUNTIME_READY=false

NVIDIA_TOOLKIT_DOC_URL="https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html"
_NVIDIA_GPGKEY="https://nvidia.github.io/libnvidia-container/gpgkey"
_NVIDIA_KEYRING="/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg"
_NVIDIA_DEB_LIST="https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list"
_NVIDIA_RPM_REPO="https://nvidia.github.io/libnvidia-container/stable/rpm/nvidia-container-toolkit.repo"

# nvidia_toolkit_strategy → install path by package-manager family. NVIDIA
# publishes a libnvidia-container repo for deb (apt), rpm (dnf/yum), and SUSE
# (zypper). Arch is AUR-only → unsupported (warn + manual link). Pure.
nvidia_toolkit_strategy() {
  case "$OS_FAMILY" in
    debian) echo "apt" ;;
    rhel) echo "dnf" ;;
    suse) echo "zypper" ;;
    *) echo "unsupported" ;;
  esac
}

_nvidia_toolkit_install_apt() {
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] curl ${_NVIDIA_GPGKEY} | gpg --dearmor -o ${_NVIDIA_KEYRING}"
    info "[dry] write ${_NVIDIA_DEB_LIST} → /etc/apt/sources.list.d/nvidia-container-toolkit.list"
    info "[dry] apt-get update && apt-get install -y nvidia-container-toolkit"
    return 0
  fi
  run install -m 0755 -d /usr/share/keyrings
  run sh -c "curl --proto '=https' --tlsv1.2 -fsSL ${_NVIDIA_GPGKEY} | gpg --dearmor -o ${_NVIDIA_KEYRING}"
  run chmod a+r "${_NVIDIA_KEYRING}"
  run sh -c "curl --proto '=https' --tlsv1.2 -fsSL ${_NVIDIA_DEB_LIST} | sed 's#deb https://#deb [signed-by=${_NVIDIA_KEYRING}] https://#g' > /etc/apt/sources.list.d/nvidia-container-toolkit.list"
  run apt-get update -y
  run apt-get install -y nvidia-container-toolkit
}

_nvidia_toolkit_install_dnf() {
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] curl ${_NVIDIA_RPM_REPO} → /etc/yum.repos.d/nvidia-container-toolkit.repo"
    info "[dry] dnf install -y nvidia-container-toolkit"
    return 0
  fi
  run curl --proto '=https' --tlsv1.2 -fsSL "${_NVIDIA_RPM_REPO}" -o /etc/yum.repos.d/nvidia-container-toolkit.repo
  run dnf install -y nvidia-container-toolkit
}

_nvidia_toolkit_install_zypper() {
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] zypper addrepo ${_NVIDIA_RPM_REPO} && zypper install -y nvidia-container-toolkit"
    return 0
  fi
  run zypper --non-interactive addrepo "${_NVIDIA_RPM_REPO}" nvidia-container-toolkit || true
  run zypper --non-interactive --gpg-auto-import-keys refresh
  run zypper --non-interactive install -y nvidia-container-toolkit
}

# Configure Docker's `nvidia` runtime + restart, then confirm it registered.
# Sets AAP_NVIDIA_RUNTIME_READY=true on success (or in dry-run, so the env-file
# branch is exercised).
_nvidia_ctk_configure_docker() {
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] nvidia-ctk runtime configure --runtime=docker && systemctl restart docker"
    AAP_NVIDIA_RUNTIME_READY=true
    return 0
  fi
  if ! command -v nvidia-ctk >/dev/null 2>&1; then
    warn "nvidia-ctk not found after install; cannot configure Docker's nvidia runtime. See ${NVIDIA_TOOLKIT_DOC_URL}"
    return 0
  fi
  run nvidia-ctk runtime configure --runtime=docker
  run systemctl restart docker || warn "systemctl restart docker returned non-zero after nvidia runtime configure"
  local i=0
  while [ "$i" -lt 30 ]; do
    docker info >/dev/null 2>&1 && break
    sleep 1
    i=$((i + 1))
  done
  if docker info 2>/dev/null | grep -qiE 'runtimes:.*nvidia'; then
    AAP_NVIDIA_RUNTIME_READY=true
    info "Docker nvidia runtime configured — GPU containers (and the panel's live GPU view) are ready."
  else
    warn "The nvidia runtime is not visible in 'docker info' after configure; GPU passthrough may not work. See ${NVIDIA_TOOLKIT_DOC_URL}"
  fi
}

# install_nvidia_container_toolkit — detect an NVIDIA GPU; if present, install +
# configure the toolkit idempotently. A no-op (success) on CPU-only hosts.
install_nvidia_container_toolkit() {
  if ! host_has_nvidia_gpu; then
    info "No NVIDIA GPU detected on the PCI bus — skipping NVIDIA Container Toolkit (CPU-only host)."
    return 0
  fi
  info "NVIDIA GPU detected — ensuring the NVIDIA Container Toolkit is installed and Docker's nvidia runtime is configured."

  if ! host_has_nvidia_driver; then
    warn "An NVIDIA GPU is present but no driver is loaded (nvidia-smi unavailable). Installing the container toolkit anyway, but GPU containers need the driver too: on Ubuntu run 'ubuntu-drivers install' (or 'apt install -y nvidia-driver-<ver>'); on Rocky/AlmaLinux/RHEL 9 or 10 run the installer again with --gpu-driver=install, which installs it (AI-2330); elsewhere see https://docs.nvidia.com/datacenter/tesla/driver-installation-guide/ and reboot."
  fi

  if command -v nvidia-ctk >/dev/null 2>&1; then
    info "NVIDIA Container Toolkit already installed — re-asserting Docker runtime configuration (idempotent)."
    _nvidia_ctk_configure_docker
    return 0
  fi

  local strat
  strat="$(nvidia_toolkit_strategy)"
  info "Installing NVIDIA Container Toolkit via '${strat}' for ${OS_PRETTY:-${OS_ID:-$OS_FAMILY}}..."
  case "$strat" in
    apt) _nvidia_toolkit_install_apt ;;
    dnf) _nvidia_toolkit_install_dnf ;;
    zypper) _nvidia_toolkit_install_zypper ;;
    *)
      warn "No automated NVIDIA Container Toolkit install path for '${OS_ID:-$OS_FAMILY}'. Install it manually, then run 'nvidia-ctk runtime configure --runtime=docker': ${NVIDIA_TOOLKIT_DOC_URL}"
      return 0
      ;;
  esac
  _nvidia_ctk_configure_docker
}

# nvidia_panel_env_block — env-file lines that give the PANEL container its own
# GPU visibility (AI-420 opt 1). Emitted by generate_env_file ONLY when Docker's
# nvidia runtime was configured (AAP_NVIDIA_RUNTIME_READY=true). With the panel
# container under the nvidia runtime + NVIDIA_VISIBLE_DEVICES, the toolkit injects
# nvidia-smi into it, so detection shows the rich live model/VRAM/driver view
# instead of the degraded PCI-only fallback. NVIDIA_DRIVER_CAPABILITIES=utility
# is the minimal capability that provides nvidia-smi + NVML (no compute/graphics).
# On every other host this emits nothing, so docker-compose.yml's safe defaults
# (runtime runc, NVIDIA_VISIBLE_DEVICES=void) apply and the panel is unchanged.
nvidia_panel_env_block() {
  [ "${AAP_NVIDIA_RUNTIME_READY:-false}" = "true" ] || return 0
  printf '%s\n' \
    "# GPU visibility for the panel container (NVIDIA runtime detected at install)." \
    "PANEL_RUNTIME=nvidia" \
    "NVIDIA_VISIBLE_DEVICES=all" \
    "NVIDIA_DRIVER_CAPABILITIES=utility"
}

# ollama_gpu_override_yaml — the docker-compose overlay that hands the bundled
# Ollama the host GPU (AI-428). Emitted ONLY when Docker's nvidia runtime was
# configured (AAP_NVIDIA_RUNTIME_READY=true); nothing on CPU-only hosts.
#
# Why an overlay and not the panel's env-var trick: the panel container gets GPU
# *visibility* via runtime:nvidia (above), which is enough for nvidia-smi. But
# Ollama is shown in the AI Models page, whose honest per-model badge (AI-427)
# reads HostConfig.DeviceRequests — a field ONLY the structured
# `deploy.resources.reservations.devices` block populates (runtime:nvidia leaves
# it null → the badge would read CPU even while the GPU is in use). That block
# can't sit unconditionally in docker-compose.yml: on a CPU host `docker compose
# up` then fails ("could not select device driver nvidia"). So on a GPU host the
# installer writes this as a separate file and merges it with an extra `-f`; on a
# CPU host the file is absent and the base compose stays CPU-safe.
#
# `count: all` → DeviceRequests:[{Driver:nvidia,Count:-1,Capabilities:[[gpu]]}],
# exactly the reservation hand-verified on the OVH Quadro RTX 5000 box.
ollama_gpu_override_yaml() {
  [ "${AAP_NVIDIA_RUNTIME_READY:-false}" = "true" ] || return 0
  cat <<'YAML'
# AI Admin Panel — GPU overlay. GENERATED by install.sh on an NVIDIA host (AI-428).
# Gives the bundled Ollama the host GPU so Local AI runs accelerated. Merged via
# `docker compose -f docker-compose.yml -f docker-compose.gpu.yml up`. Absent on
# CPU-only hosts, so the base compose stays CPU-safe. Regenerated on every
# install/upgrade — edit docker-compose.yml or the installer, not this file.
services:
  ollama:
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: all
              capabilities: [gpu]
YAML
}

# ===== scripts/lib/firewall.sh =====
# scripts/lib/firewall.sh — distro-portable host firewall handling for the AI
# Admin Panel installer (AI-349). Fixes audit id `ufw-rhel-portability`: the old
# `apt-get install ufw` path is Debian/Ubuntu-only, so on RHEL/Fedora/SUSE
# (firewalld) and Arch (nftables) the installer never opened Traefik's ports and
# Let's Encrypt HTTP-01 validation failed on a box that "looked" up.
#
# We detect the *running* firewall by command presence + live state — never by
# distro name — and idempotently allow inbound 22/80/443 for that backend.
#
# Pure function definitions only — nothing executes at source time; the
# bootstrap (install.sh) owns `set -euo pipefail`.
#
# Ordering (from docs/research/universal-installer.md §5, firewalld row):
#   run AFTER `docker compose up`, BEFORE the Let's Encrypt HTTP-01 smoke.
#   Fully idempotent — safe to re-run on every install/upgrade.
#
# This module never touches Docker's own iptables/nft chains: Docker manages its
# DNAT for published ports itself, and this only opens the host firewall in front
# of it. The one rule set that hangs off Docker's chains (DOCKER-USER, and INPUT
# for traffic from container bridges) is the container egress guard,
# scripts/aap-egress-guard.sh (AI-1104), which the installer sets up after this.
#
# Public functions:
#   detect_firewall        → FIREWALL_BACKEND (firewalld|ufw|nftables|none)
#   firewall_cmds_for BK   → echoes the exact shell commands open_firewall_ports
#                            would run for backend BK, one per line (pure; no
#                            side effects — bats asserts on this)
#   open_firewall_ports    → idempotently allow 22/80/443 for FIREWALL_BACKEND;
#                            honors DRY_RUN=true (prints "[would] …", runs nothing);
#                            on firewalld also close_preset_cockpit (AI-2546)
#   ensure_host_firewall   → AI-2199: when NO firewall is running, install and
#                            turn on the distro's own one (firewalld or ufw):
#                            SSH allowed first, then 80/443, inbound denied by
#                            default. FIREWALL=skip turns it off; DRY_RUN prints
#   ssh_ports              → SSH port(s) to keep open (sshd -T + the current
#                            session's port, else 22)
#   host_firewall_cmds_for → the exact commands ensure_host_firewall runs (pure)
#
# Test override / mock surface: detection is driven entirely by `firewall-cmd`,
# `ufw`, and `nft` resolved via PATH, so bats can shim them as fake executables.
# ensure_host_firewall also resolves sshd, systemctl, dnf/yum, zypper, apt-get
# and firewall-offline-cmd via PATH, and reads OS_FAMILY (detect_platform).

# ── tiny INFO shim ────────────────────────────────────────────────────────────
# install.sh defines info(); when this lib is sourced standalone (bats) it isn't,
# so fall back to a plain stderr line. Never redefine an existing info().
_fw_info() {
  if command -v info >/dev/null 2>&1; then
    info "$@"
  else
    printf 'INFO  %s\n' "$*" >&2
  fi
}

# ── detection ─────────────────────────────────────────────────────────────────
# Probe order matters: a box can have firewall-cmd AND nft installed (firewalld
# is an nftables front-end), so prefer the higher-level manager that is actually
# *running*. ufw likewise sits on top of iptables/nft.
#   1. firewalld  — `firewall-cmd` present AND `firewall-cmd --state` == running
#   2. ufw        — `ufw` present AND `ufw status` reports active
#   3. nftables   — `nft` present (rules exist or not — we still won't write any)
#   4. none       — nothing managing the host firewall
detect_firewall() {
  if command -v firewall-cmd >/dev/null 2>&1 \
    && firewall-cmd --state >/dev/null 2>&1; then
    FIREWALL_BACKEND="firewalld"
    return 0
  fi

  if command -v ufw >/dev/null 2>&1 \
    && ufw status 2>/dev/null | grep -qi 'Status: active'; then
    FIREWALL_BACKEND="ufw"
    return 0
  fi

  if command -v nft >/dev/null 2>&1; then
    FIREWALL_BACKEND="nftables"
    return 0
  fi

  FIREWALL_BACKEND="none"
  return 0
}

# ── pure command planner ──────────────────────────────────────────────────────
# Echo the exact commands open_firewall_ports would execute for backend $1, one
# per line. Pure: no side effects, runs nothing. Backends with no managed
# firewall (nftables/none) print nothing — the caller emits an INFO instead.
firewall_cmds_for() {
  local backend="$1"
  case "$backend" in
    firewalld)
      # AI-2200: add to the running config and to the saved one, never
      # `--reload`. A reload rebuilds firewalld's whole rule set, Docker's
      # docker zone and docker-forwarding policy included, and container
      # traffic fails until Docker puts them back (about a second; 4 of 5
      # DNS lookups failed right after a reload on CI's almalinux-10 image).
      # A runtime add only adds rules, and it also keeps any runtime-only rule
      # the operator made. Both are idempotent: an already-allowed service is
      # ALREADY_ENABLED, exit 0.
      echo "firewall-cmd --add-service=ssh --add-service=http --add-service=https"
      echo "firewall-cmd --permanent --add-service=ssh --add-service=http --add-service=https"
      ;;
    ufw)
      echo "ufw allow 22/tcp"
      echo "ufw allow 80/tcp"
      echo "ufw allow 443/tcp"
      ;;
    nftables | none)
      : # no managed-firewall commands — handled as an INFO no-op
      ;;
    *)
      : # unknown backend — emit nothing, treated as no-op
      ;;
  esac
}

# ── AI-2546: close the preset cockpit on a firewalld that was already running ─
# The RHEL family's default zone allows cockpit (9090/tcp, the Cockpit web
# console login), and some hosting images (Vultr's AlmaLinux) ship firewalld
# running with Cockpit listening. AI-2202 removes it when the install turns
# firewalld on itself; a firewalld that was already running kept it, so the
# console stayed on the internet next to the panel. Remove cockpit, and only
# cockpit, from the default zone's running config and its saved config, each
# only where it is allowed. No reload (AI-2200). dhcpv6-client stays (a UDP
# client port for IPv6 addressing). FIREWALL=skip leaves it alone. A failure
# warns and the install goes on.
close_preset_cockpit() {
  [ "${FIREWALL:-auto}" = "skip" ] && return 0
  local scope cmd removed=false
  for scope in "" "--permanent "; do
    # shellcheck disable=SC2086 # scope is "" or one fixed flag
    firewall-cmd ${scope}--query-service=cockpit >/dev/null 2>&1 || continue
    cmd="firewall-cmd ${scope}--remove-service=cockpit"
    if [ "${DRY_RUN:-false}" = "true" ]; then
      printf '[would] %s\n' "$cmd"
      continue
    fi
    # shellcheck disable=SC2086 # cmd is our own fixed string
    if $cmd >/dev/null 2>&1; then
      removed=true
    else
      _fw_warn "Could not remove cockpit (9090/tcp) from firewalld (${cmd}); the Cockpit web console port may still be open. Remove it by hand: firewall-cmd --permanent --remove-service=cockpit && firewall-cmd --remove-service=cockpit"
    fi
  done
  if [ "$removed" = true ]; then
    _fw_info "Closed cockpit (9090/tcp) in firewalld: the panel allows only SSH, 80 and 443. To use the Cockpit console, allow it from your own address only (a firewalld rich rule)."
  fi
  return 0
}

# ── apply ─────────────────────────────────────────────────────────────────────
# Idempotently open 22/80/443 for the detected backend. firewalld and ufw are
# both natively idempotent (re-adding a service / an existing allow rule is a
# no-op), so this is safe to re-run on every install and upgrade. firewalld is
# changed without a reload, so Docker's rules stay in place (AI-2200).
#
# DRY_RUN=true prints "[would] <cmd>" for each planned command and executes
# nothing — matches install.sh's dry-run so the module is unit-testable.
open_firewall_ports() {
  # Detect on demand if the caller didn't already.
  [ -n "${FIREWALL_BACKEND:-}" ] || detect_firewall

  local backend="${FIREWALL_BACKEND}"

  # AI-2199: ensure_host_firewall turned this firewall on in this run with
  # SSH, 80 and 443 already allowed, so there is nothing to add.
  if [ "${HOST_FIREWALL_TURNED_ON:-}" = "$backend" ]; then
    _fw_info "Host firewall (${backend}) was turned on by this install; SSH, 80 and 443 are already open."
    return 0
  fi

  case "$backend" in
    firewalld | ufw)
      _fw_info "Opening host firewall (${backend}) for inbound 22/80/443"
      local cmd
      while IFS= read -r cmd; do
        [ -n "$cmd" ] || continue
        if [ "${DRY_RUN:-false}" = "true" ]; then
          printf '[would] %s\n' "$cmd"
        else
          # word-splitting is intentional: cmd is our own fixed, trusted string.
          # shellcheck disable=SC2086
          eval "$cmd"
        fi
      done <<EOF
$(firewall_cmds_for "$backend")
EOF
      if [ "$backend" = "firewalld" ]; then close_preset_cockpit; fi
      ;;
    nftables)
      _fw_info "nftables present but no firewalld/ufw managing the host firewall; not writing raw nft rules (Docker manages its own DNAT). Ensure inbound 80/443 reach this host."
      ;;
    none | *)
      _fw_info "No managed host firewall detected; nothing to open. Ensure inbound 80/443 reach this host for Let's Encrypt HTTP-01 and panel access."
      ;;
  esac
  return 0
}

# ── AI-2199: turn on a host firewall when none is running ─────────────────────
# Owner decision 2026-11-09: a fresh server must not stay open on every port it
# listens on. When detect_firewall finds nothing (or nftables with an EMPTY
# ruleset, which is the same thing), install the distro's own firewall, allow
# SSH, 80/tcp and 443/tcp, deny every other inbound connection, and turn it on.
#
# WHEN. The installer calls this BEFORE Docker is installed. Docker creates its
# firewalld zone ("docker", target ACCEPT, every Docker bridge in it) and its
# "docker-forwarding" policy when it starts with firewalld running. If Docker is
# already running here (a host that had Docker before the panel), it is
# restarted once so it sets those up; without that, firewalld would drop
# container traffic.
#
# NEVER LOCK THE OWNER OUT. The SSH port(s) are allowed before the firewall is
# turned on, and the commands stop at the first failure, so a failed allow is
# never followed by the enable. Established connections (the current session)
# stay up: firewalld and ufw both accept established traffic first.
#
# firewalld is configured with firewall-offline-cmd while it is still stopped,
# then started: no reload, so nothing else on the host is flushed. Its default
# zone's preset cockpit service (9090/tcp) is removed (AI-2202); dhcpv6-client
# is kept.
#
# What it leaves alone: a firewall that is already running (open_firewall_ports
# handles that one: it opens SSH/80/443 and, on firewalld, closes cockpit,
# AI-2546), nftables with rules in it (the operator's own
# firewall), FIREWALL=skip (a provider or external firewall), and distros with
# no supported firewall (warned). A failure warns and the install goes on: the
# panel still works, and the server is only as open as it was before.
#
# Docker and ufw: Docker routes published ports past ufw's rules, so the
# panel's 80/443 work either way, and so does any port a container publishes
# (Docker's behaviour on every ufw host). The container egress guard
# (aap-egress-guard.sh) inserts its jumps first in DOCKER-USER and INPUT, so it
# works with either firewall.

# The SSH port(s) to allow, space separated: every `port` sshd -T reports, plus
# the server port of the current session (SSH_CONNECTION's 4th field), so a
# session on a port sshd -T does not show (socket activation) survives too.
# Falls back to 22 when neither gives a valid port.
ssh_ports() {
  local raw="" key val out="" p sshd_out=""
  if command -v sshd >/dev/null 2>&1; then
    sshd_out="$(sshd -T 2>/dev/null)" || sshd_out=""
    while read -r key val _; do
      [ "$key" = "port" ] && raw="${raw} ${val}"
    done <<<"$sshd_out"
  fi
  if [ -n "${SSH_CONNECTION:-}" ]; then
    # shellcheck disable=SC2086 # split "client_ip client_port server_ip server_port"
    set -- $SSH_CONNECTION
    raw="${raw} ${4:-}"
  fi
  for p in $raw; do
    case "$p" in '' | *[!0-9]*) continue ;; esac
    if [ "$p" -lt 1 ] || [ "$p" -gt 65535 ]; then continue; fi
    case " ${out} " in *" ${p} "*) ;; *) out="${out} ${p}" ;; esac
  done
  [ -n "$out" ] || out=" 22"
  echo "${out# }"
}

# Which firewall this distro gets: firewalld for the RHEL family (Rocky, Alma,
# RHEL, CentOS Stream, Fedora, Oracle, Amazon Linux) and SUSE, ufw for Debian
# and Ubuntu. Empty for anything else.
host_firewall_for_family() {
  case "${1:-}" in
    rhel | suse) echo "firewalld" ;;
    debian) echo "ufw" ;;
    *) echo "" ;;
  esac
}

# Pure planner: the commands ensure_host_firewall runs to install and turn on
# BACKEND for OS family FAMILY, keeping PORTS (space separated) open for SSH.
# The package is installed only when its tool is missing. Every allow comes
# before the enable.
host_firewall_cmds_for() {
  local backend="$1" family="$2" ports="$3" p pm
  case "$backend" in
    firewalld)
      if ! command -v firewall-offline-cmd >/dev/null 2>&1; then
        if [ "$family" = "suse" ]; then
          echo "zypper --non-interactive install -y firewalld"
        else
          pm="dnf"
          if ! command -v dnf >/dev/null 2>&1 && command -v yum >/dev/null 2>&1; then pm="yum"; fi
          echo "${pm} install -y firewalld"
        fi
      fi
      for p in $ports; do
        if [ "$p" = "22" ]; then
          echo "firewall-offline-cmd --add-service=ssh"
        else
          echo "firewall-offline-cmd --add-port=${p}/tcp"
        fi
      done
      echo "firewall-offline-cmd --add-service=http --add-service=https"
      # AI-2202: the RHEL family's default zone (public, or FedoraServer)
      # already allows cockpit, the 9090/tcp web console login. Installing
      # Cockpit later would put that login on the internet, against "only SSH,
      # 80 and 443". Remove it. When the zone does not list it (SUSE),
      # firewall-offline-cmd says NOT_ENABLED and exits 0. dhcpv6-client stays:
      # it is the UDP port IPv6 address configuration answers on, not a service.
      echo "firewall-offline-cmd --remove-service=cockpit"
      # firewalld and Docker talk over the system bus: without it firewalld
      # loads its rules but nothing can reach it, and Docker never adds its
      # docker zone, so container traffic is rejected. Real servers run it;
      # stripped images (CI's systemd containers) ship dbus.socket off.
      [ -e "${AAP_DBUS_SOCKET:-/run/dbus/system_bus_socket}" ] || echo "systemctl start dbus.socket"
      echo "systemctl enable --now firewalld"
      ;;
    ufw)
      if ! command -v ufw >/dev/null 2>&1; then
        echo "apt-get update -qq"
        echo "DEBIAN_FRONTEND=noninteractive apt-get install -y ufw"
      fi
      echo "ufw default deny incoming"
      echo "ufw default allow outgoing"
      for p in $ports; do
        echo "ufw allow ${p}/tcp"
      done
      echo "ufw allow 80/tcp"
      echo "ufw allow 443/tcp"
      echo "ufw --force enable"
      ;;
  esac
}

# True when `nft list ruleset` succeeds and holds no table, or only the
# `inet firewalld` table a firewalld that is not running left behind (a start
# that failed; detect_firewall already found firewalld not running). A failing
# nft is treated as "has rules": never take over a firewall this cannot read.
_fw_nft_ruleset_empty() {
  local rs line
  rs="$(nft list ruleset 2>/dev/null)" || return 1
  while IFS= read -r line; do
    case "$line" in
      "table inet firewalld"*) ;;
      "table "*) return 1 ;;
    esac
  done <<<"$rs"
  return 0
}

# Turn BACKEND off again after a start that failed or does not answer, so a
# half-alive firewall never sits in front of Docker. firewalld stopped without
# a working system bus can leave its nft table behind; that table rejects
# forwarded container traffic, so it is deleted too.
_fw_rollback() {
  case "$1" in
    firewalld)
      systemctl disable --now firewalld >/dev/null 2>&1 || true
      if command -v nft >/dev/null 2>&1 \
        && nft list ruleset 2>/dev/null | grep -q '^table inet firewalld'; then
        nft delete table inet firewalld >/dev/null 2>&1 || true
      fi
      ;;
    ufw)
      command -v ufw >/dev/null 2>&1 && ufw --force disable >/dev/null 2>&1
      ;;
  esac
  return 0
}

_fw_warn() {
  if command -v warn >/dev/null 2>&1; then
    warn "$@"
  else
    printf 'WARN  %s\n' "$*" >&2
  fi
}

ensure_host_firewall() {
  local mode="${FIREWALL:-auto}"
  case "$mode" in
    skip)
      _fw_info "FIREWALL=skip: not installing a host firewall. Keep inbound ports closed with your provider's firewall."
      return 0
      ;;
    auto) ;;
    *)
      printf 'ERROR FIREWALL=%s is not valid: use FIREWALL=skip (or --no-firewall) to opt out, or leave it unset.\n' "$mode" >&2
      return 1
      ;;
  esac

  detect_firewall
  case "$FIREWALL_BACKEND" in
    firewalld | ufw)
      _fw_info "Host firewall ${FIREWALL_BACKEND} is already running; its rules are kept (80/443 are opened later)."
      return 0
      ;;
    nftables)
      if ! _fw_nft_ruleset_empty; then
        _fw_info "nftables has rules on this host; treating them as your firewall and adding none. Ensure inbound 80/443 reach this host."
        return 0
      fi
      ;;
  esac

  local backend
  backend="$(host_firewall_for_family "${OS_FAMILY:-}")"
  if [ -z "$backend" ]; then
    _fw_warn "No host firewall is running and none is supported on this distribution (${OS_FAMILY:-unknown}). Every port a service listens on is reachable; set one up, or use your provider's firewall."
    return 0
  fi

  local ports
  ports="$(ssh_ports)"
  _fw_info "No host firewall is running: installing and turning on ${backend} (inbound denied except SSH ${ports// /, }, 80/tcp and 443/tcp)."

  local cmd plan started=false
  plan="$(host_firewall_cmds_for "$backend" "${OS_FAMILY:-}" "$ports")"
  while IFS= read -r cmd; do
    [ -n "$cmd" ] || continue
    if [ "${DRY_RUN:-false}" = "true" ]; then
      printf '[would] %s\n' "$cmd"
      continue
    fi
    case "$cmd" in "systemctl enable --now firewalld" | "ufw --force enable") started=true ;; esac
    # cmd is our own fixed string; eval keeps the VAR=value prefix working.
    if ! eval "$cmd"; then
      [ "$started" = false ] || _fw_rollback "$backend"
      _fw_warn "Host firewall setup stopped at '${cmd}'; ${backend} was not turned on. Set it up by hand, or re-run with FIREWALL=skip."
      FIREWALL_BACKEND="none"
      return 0
    fi
  done <<<"$plan"

  # It must answer, not just be started: see _fw_rollback.
  if [ "${DRY_RUN:-false}" != "true" ]; then
    detect_firewall
    if [ "$FIREWALL_BACKEND" != "$backend" ]; then
      _fw_rollback "$backend"
      _fw_warn "${backend} was started but did not come up (no answer from it); turned it off again so it cannot block containers. Check 'systemctl status ${backend}' and D-Bus, or re-run with FIREWALL=skip."
      FIREWALL_BACKEND="none"
      return 0
    fi
  fi

  # Docker sets up its firewalld zone when it starts with firewalld running.
  if [ "$backend" = "firewalld" ] && command -v systemctl >/dev/null 2>&1 \
    && systemctl is-active --quiet docker 2>/dev/null; then
    if [ "${DRY_RUN:-false}" = "true" ]; then
      printf '[would] %s\n' "systemctl restart docker"
    else
      _fw_warn "Docker was already running; restarting it once so it adds its bridges to firewalld's docker zone (running containers restart)."
      systemctl restart docker \
        || _fw_warn "Docker did not restart; run 'systemctl restart docker' so containers can reach the network."
    fi
  fi

  if [ "${DRY_RUN:-false}" != "true" ]; then
    FIREWALL_BACKEND="$backend"
    HOST_FIREWALL_TURNED_ON="$backend"
  fi
  return 0
}

# ===== scripts/lib/preflight.sh =====
# scripts/lib/preflight.sh — pre-mutation environment gate for the AI Admin
# Panel universal installer (AI-349).
#
# Runs BEFORE the installer touches the box (no Docker pulls, no secret-gen, no
# package installs). Goal: fail in ~5 seconds with a SPECIFIC, actionable
# message naming the blocker AND the exact fix command — never a generic
# "install failed" five minutes into the run. See docs/research/universal-
# installer.md §2 (pre-flight gate), §5 (ports/DNS/time/cgroup/virt), §10
# (risks #3 the curl|bash hang, #5 the Let's Encrypt rate-limit lockout).
#
# Pure function definitions only — NO `set -euo pipefail`, nothing executes at
# source time. The bootstrap (install.sh) owns shell strictness and calls
# preflight_checks() once flags/env are parsed.
#
# Public entrypoint:
#   preflight_checks   → orchestrates every gate below; returns 2 on the first
#                        HARD failure (exit code 2 = missing prerequisite),
#                        0 if every hard gate passes (warnings are non-fatal).
#
# Resolver gate (AI-2319, run by install.sh BEFORE the domain prompt):
#                         check_resolver → the box's own DNS resolves
#                         get.aiadminpanel.com, or stop (2) with the fix when
#                         DNS answers nothing but 1.1.1.1 is reachable.
# Hard gates (return 2):  root, systemd, 64-bit arch, virt type, disk >= 5GiB,
#                         ports 80/443 free, DNS A-record matches box IP,
#                         panel image tag exists on GHCR (AI-2172), a supplied
#                         ADMIN_PASSWORD passes the realm policy (AI-2521).
# Soft gates (WARN only): outbound reachability, NTP sync, cgroup v2.
#
# The decision logic of each gate is split into a PURE predicate (no I/O, no
# globals) so bats can exercise it directly with crafted inputs — mirrors
# platform.sh's `_classify` split. Pure predicates:
#   arch_supported <uname-m>          → 0 if 64-bit x86_64/aarch64
#   virt_supported <virt-type>        → 0 unless openvz / unprivileged lxc
#   disk_ok <free-bytes>              → 0 if >= 5 GiB
#   port_in_use <ss-or-netstat-out> <port> → 0 if something LISTENs on <port>
#   dns_matches <resolved-ip-list> <box-ip> → 0 if box-ip is in the list
#   admin_password_ok <password> <email> → 0 if the realm password policy accepts it
#   admin_email_normalize <raw>        → the usable admin sign-in e-mail (AI-2792)
#
# Honored env (flag twins owned by install.sh): DRY_RUN, VERBOSE, PANEL_DOMAIN,
# TLS_MODE (letsencrypt|letsencrypt-dns; cloudflare = old alias), INSTALL_DIR.
# Test override hooks: ARCH_OVERRIDE, VIRT_OVERRIDE, EUID_OVERRIDE — bats can't
# assign the readonly $EUID, so check_root reads EUID_OVERRIDE first (see helper).

PREFLIGHT_EXIT_MISSING_PREREQ=2
PREFLIGHT_MIN_DISK_BYTES=$((5 * 1024 * 1024 * 1024)) # 5 GiB

# Default-route guard (AI-423): where the opt-in AAP_FIX_ROUTING fix writes its
# netplan drop-in, and the metric it parks the private default route at (well
# above any normal DHCP metric, so the public default always wins). ROUTE_FIX_FILE
# is overridable for tests.
ROUTE_FIX_FILE="${ROUTE_FIX_FILE:-/etc/netplan/99-aap-route-fix.yaml}"
ROUTE_FIX_METRIC=4000

# ── minimal logging (only define if the bootstrap hasn't already) ─────────────
# install.sh provides richer info/warn/error; these fallbacks keep the lib
# usable standalone (and in bats) without pulling in the whole bootstrap.
if ! declare -F info >/dev/null 2>&1; then
  info() { printf '[INFO]  %s\n' "$*"; }
fi
if ! declare -F warn >/dev/null 2>&1; then
  warn() { printf '[WARN]  %s\n' "$*" >&2; }
fi
if ! declare -F pf_fail >/dev/null 2>&1; then
  # pf_fail prints a blocker + fix to stderr. It does NOT exit — preflight_checks
  # aggregates failures and returns 2, so the bootstrap controls process exit.
  pf_fail() { printf '[FAIL]  %s\n' "$*" >&2; }
fi

# ── pure predicates (no side effects — bats calls these directly) ─────────────

# arch_supported <uname-m> → 0 for 64-bit x86_64/aarch64, 1 otherwise (32-bit).
arch_supported() {
  local m="$1"
  case "$m" in
    x86_64 | amd64 | aarch64 | arm64) return 0 ;;
    *) return 1 ;;
  esac
}

# virt_supported <virt-type> → 1 (unsupported) for openvz and any lxc flavour
# (rootful Docker can't run in OpenVZ or an unprivileged LXC container); 0 for
# kvm / none / docker / amazon / etc. systemd-detect-virt prints `none` on bare
# metal and a non-zero exit, which the caller maps to "none".
virt_supported() {
  local v="$1"
  case "$v" in
    openvz | lxc | lxc-libvirt) return 1 ;;
    *) return 0 ;;
  esac
}

# disk_ok <free-bytes> → 0 if >= 5 GiB. Non-numeric input is treated as a
# failure (inconclusive probe shouldn't pass silently).
disk_ok() {
  local bytes="$1"
  case "$bytes" in
    '' | *[!0-9]*) return 1 ;;
  esac
  [ "$bytes" -ge "$PREFLIGHT_MIN_DISK_BYTES" ]
}

# admin_password_ok <password> <email> → 0 if Keycloak's realm password policy
# (AI-2521: length(12) and maxLength(128) and notUsername and notEmail) accepts
# <password> for the admin account <email>, whose username is the email too.
# Keycloak compares the username and email ignoring case.
admin_password_ok() {
  local pw="$1" email="$2"
  [ "${#pw}" -ge 12 ] && [ "${#pw}" -le 128 ] || return 1
  [ -n "$email" ] && [ "$(printf '%s' "$pw" | tr '[:upper:]' '[:lower:]')" = "$(printf '%s' "$email" | tr '[:upper:]' '[:lower:]')" ] && return 1
  return 0
}

# port_in_use <listen-table> <port> → 0 if the table shows a LISTEN socket on
# <port>. Accepts BOTH `ss -ltn` and `netstat -ltn` output (audit ss-not-present
# fallback). Both render the local endpoint as ADDR:PORT in a whitespace-
# separated column, where ADDR may itself contain colons (IPv6 `[::]:443`,
# `*:443`) — so we match the port as the final `:PORT` token, anchored on a
# word boundary, and never on the trailing `:*` peer column.
port_in_use() {
  local table="$1" port="$2" line addr
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      *LISTEN*) ;;
      *) continue ;;
    esac
    # Scan each whitespace token; the local endpoint is the one ending in
    # :<port> that is NOT the peer column (peer ends in ":*").
    for addr in $line; do
      case "$addr" in
        *:\*) continue ;;       # peer column (ss/netstat) — skip
        *:"$port")              # endpoint ends exactly in :<port>
          return 0 ;;
      esac
    done
  done <<EOF
$table
EOF
  return 1
}

# normalize_panel_version <PANEL_VERSION> → echoes the image tag to use (AI-2172).
# GitHub names a release "v2.22.0" and get.aiadminpanel.com serves its assets
# under /v2.22.0/, but GHCR tags the image "2.22.0" and "2.22" — never with the
# v. So a release name is accepted and its leading v/V dropped; every other value
# (2.22.0, latest, main, main-<sha>) is a registry tag already and passes
# unchanged. Empty means the default, "latest". Pure.
normalize_panel_version() {
  local v="${1:-latest}"
  if [[ "$v" =~ ^[vV][0-9]+\.[0-9]+ ]]; then
    v="${v:1}"
  fi
  printf '%s\n' "$v"
}

# release_asset_base <get-base> <PANEL_VERSION> → the URL the installer
# downloads its other files (Compose file, Keycloak realm and theme) from
# (AI-2327). A concrete release (2.25.0, 2.26.0-rc.1, after
# normalize_panel_version) gets that release's own immutable folder,
# <get-base>/v2.25.0, which the release workflow fills next to SHA256SUMS. Moving
# tags (latest, main, main-<sha>, a minor alias such as 2.25) have no folder and
# keep the top of <get-base>, which tracks main. Pure.
release_asset_base() {
  local base="$1" v="${2:-latest}"
  if [[ "$v" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.+-]+)?$ ]]; then
    printf '%s/v%s\n' "$base" "$v"
  else
    printf '%s\n' "$base"
  fi
}

# sha256sums_lookup <file-name> → the hash SHA256SUMS (read on stdin, sha256sum
# format "<hex>  <name>") lists for <file-name>, or nothing. Exact name match
# only, so "install.sh" never matches "install.sh.bundle". Pure.
sha256sums_lookup() {
  local want="$1" hash name
  while read -r hash name; do
    name="${name#\*}"
    if [ "$name" = "$want" ] && [[ "$hash" =~ ^[0-9a-f]{64}$ ]]; then
      printf '%s\n' "$hash"
      return 0
    fi
  done
  return 1
}

# validate_upgrade_url <url> → 0 when the panel would use <url> as its upgrade
# link (AI-2218). Same rule as the panel's ResolveUpgradeURL
# (internal/module/entitlements.go): an absolute https URL with a host, or plain
# http only on a loopback host (localhost, 127.0.0.0/8, [::1]). Also refuses
# whitespace, quotes, backslashes, backticks and `$`, which would break or be
# expanded in the docker compose .env. Pure.
validate_upgrade_url() {
  local url="$1" rest authority host scheme
  [ -n "$url" ] || return 1
  case "$url" in
    *[[:space:]]* | *[[:cntrl:]]* | *\"* | *\'* | *\`* | *\\* | *\$*) return 1 ;;
  esac
  scheme="${url%%://*}"
  [ "$scheme" != "$url" ] || return 1
  scheme="$(printf '%s' "$scheme" | tr '[:upper:]' '[:lower:]')"
  rest="${url#*://}"
  authority="${rest%%[/?#]*}"
  authority="${authority##*@}"
  [ -n "$authority" ] || return 1
  if [[ "$authority" == \[* ]]; then
    host="${authority%%]*}]"
  else
    host="${authority%%:*}"
  fi
  [ -n "$host" ] || return 1
  case "$scheme" in
    https) return 0 ;;
    http)
      host="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]')"
      [ "$host" = "localhost" ] && return 0
      [ "$host" = "[::1]" ] && return 0
      [[ "$host" =~ ^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$ ]] || return 1
      local o
      for o in "${BASH_REMATCH[@]:1}"; do [ "$o" -le 255 ] || return 1; done
      return 0
      ;;
  esac
  return 1
}

# check_upgrade_url → stop (exit status 2) with a plain message when
# UPGRADE_URL is set but the panel would not use it (AI-2218). Runs before the
# installer changes the box. Unset or empty: nothing to check (panel default).
check_upgrade_url() {
  [ -n "${UPGRADE_URL:-}" ] || return 0
  validate_upgrade_url "$UPGRADE_URL" && return 0
  error "UPGRADE_URL must be an absolute https:// address, for example https://example.com/pricing (plain http:// only on localhost, 127.0.0.1 or [::1]). Got: ${UPGRADE_URL}"
  return 2
}

# admin_email_normalize <raw> → prints the address with surrounding spaces
# removed and in lower case, and returns 0, when it is one plain address the
# owner can receive mail at (AI-2792); returns 1 otherwise. The admin account
# is created with it as its sign-in name. Only letters, digits and . _ % + -
# before the @ and a dotted domain name after it, so the value is safe in the
# installer's SQL and kcadm arguments. Addresses under aiadminpanel.host (the
# temporary domains) have no mailbox and are refused.
admin_email_normalize() {
  local LC_ALL=C raw="$1" addr local_part domain
  local label='[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?'
  addr="${raw#"${raw%%[![:space:]]*}"}"
  addr="${addr%"${addr##*[![:space:]]}"}"
  addr="${addr,,}"
  [ "${#addr}" -le 254 ] || return 1
  [[ "$addr" =~ ^[a-z0-9._%+-]{1,64}@${label}(\.${label})+$ ]] || return 1
  local_part="${addr%@*}"
  domain="${addr#*@}"
  case "$local_part" in .* | *. | *..*) return 1 ;; esac
  case "$domain" in aiadminpanel.host | *.aiadminpanel.host) return 1 ;; esac
  printf '%s\n' "$addr"
}

# check_admin_email → with ADMIN_EMAIL (or --admin-email) set, normalize it in
# place, or stop (exit status 2) before the installer changes the box when it
# is not a usable address (AI-2792). Unset: nothing to check.
check_admin_email() {
  [ -n "${ADMIN_EMAIL:-}" ] || return 0
  local addr
  if addr="$(admin_email_normalize "$ADMIN_EMAIL")"; then
    ADMIN_EMAIL="$addr"
    return 0
  fi
  echo "ADMIN_EMAIL / --admin-email must be one e-mail address you can receive mail at, for example you@example.com. It becomes your admin sign-in e-mail. Addresses at aiadminpanel.host have no mailbox. Got: ${ADMIN_EMAIL}" >&2
  return 2
}

# tls_mode_is_dns01 → 0 when TLS_MODE asks for the DNS-01 resolver. AI-2400:
# letsencrypt-dns is the name; cloudflare is the old name, kept as an alias so
# scripts and copied commands that pass it keep working.
tls_mode_is_dns01() {
  case "${TLS_MODE:-letsencrypt}" in
    letsencrypt-dns | cloudflare) return 0 ;;
  esac
  return 1
}

# check_tls_mode → stop (exit status 2) on a TLS_MODE the installer does not
# know, before the box changes. Before AI-2400 an unknown value (a typo, or a
# guess such as "dns") silently became HTTP-01. With cloudflare it prints a
# one-line note naming the new value.
check_tls_mode() {
  case "${TLS_MODE:-letsencrypt}" in
    letsencrypt | letsencrypt-dns) return 0 ;;
    cloudflare)
      info "TLS_MODE=cloudflare is the old name for TLS_MODE=letsencrypt-dns (DNS-01 through the DNS provider saved in Settings); it still works, use letsencrypt-dns from now on."
      return 0
      ;;
  esac
  pf_fail "TLS_MODE must be letsencrypt or letsencrypt-dns (got '${TLS_MODE}'). letsencrypt (the default) gets the panel certificate over port 80 (HTTP-01); letsencrypt-dns gets it through a DNS record (DNS-01). Fix the value and re-run. (No changes were made to this box.)"
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# dns_matches <resolved-ip-list> <box-ip> → 0 if box-ip appears as a whole
# entry in the (whitespace/newline-separated) resolved list. Empty resolution
# or empty box-ip is a failure (we can't prove the record points here).
dns_matches() {
  local resolved="$1" box_ip="$2" ip
  [ -n "$box_ip" ] || return 1
  [ -n "$resolved" ] || return 1
  for ip in $resolved; do
    [ "$ip" = "$box_ip" ] && return 0
  done
  return 1
}

# _is_rfc1918 <ipv4> → 0 if the address is in a private RFC1918 range
# (10/8, 172.16-31/12, 192.168/16). Pure. Tells a box's public default route
# apart from a private-network (vRack/cloud-private) one.
_is_rfc1918() {
  case "$1" in
    10.* | 192.168.*) return 0 ;;
    172.1[6-9].* | 172.2[0-9].* | 172.3[0-1].*) return 0 ;;
    *) return 1 ;;
  esac
}

# dangerous_default_routes <`ip -4 route show default` output> → detect the
# multi-homed footgun (AI-423): a PRIVATE-network default route at a metric <=
# the PUBLIC default's. Linux then routes forwarded Docker container replies
# (private/container source) out the private NIC, where they're dropped — the
# panel goes unreachable AND containers lose egress, with NO error message.
# Each route is classified public/private by its `src` (fallback: `via` gateway);
# a missing `metric` token means metric 0 (highest priority). Echoes
# "<private-dev> <metric>" and returns 0 when dangerous; returns 1 when safe.
# Pure (no I/O) so bats exercises it with crafted tables.
dangerous_default_routes() {
  local table="$1" line tok prev dev gw src metric addr
  local pub_metrics=() priv_devs=() priv_metrics=()
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      default*) ;;
      *) continue ;;
    esac
    dev=""; gw=""; src=""; metric=""; prev=""
    for tok in $line; do
      case "$prev" in
        via) gw="$tok" ;;
        dev) dev="$tok" ;;
        src) src="$tok" ;;
        metric) metric="$tok" ;;
      esac
      prev="$tok"
    done
    case "$metric" in '' | *[!0-9]*) metric=0 ;; esac
    # Classify by src, falling back to the gateway; skip if neither is present.
    if [ -n "$src" ]; then addr="$src"
    elif [ -n "$gw" ]; then addr="$gw"
    else continue; fi
    if _is_rfc1918 "$addr"; then
      priv_devs+=("$dev")
      priv_metrics+=("$metric")
    else
      pub_metrics+=("$metric")
    fi
  done <<EOF
$table
EOF
  # A conflict needs at least one public AND one private default.
  [ "${#pub_metrics[@]}" -ge 1 ] && [ "${#priv_devs[@]}" -ge 1 ] || return 1
  local pubmin="" m
  for m in "${pub_metrics[@]}"; do
    { [ -z "$pubmin" ] || [ "$m" -lt "$pubmin" ]; } && pubmin="$m"
  done
  local i
  for i in "${!priv_devs[@]}"; do
    if [ "${priv_metrics[$i]}" -le "$pubmin" ]; then
      printf '%s %s\n' "${priv_devs[$i]}" "${priv_metrics[$i]}"
      return 0
    fi
  done
  return 1
}

# ── detection helpers (thin I/O wrappers over the pure predicates) ────────────

# _detect_virt → echoes the virtualization type; honors VIRT_OVERRIDE for tests.
# `systemd-detect-virt` exits non-zero and prints `none` on bare metal — we
# normalize that to "none" so the predicate sees a stable value.
_detect_virt() {
  if [ -n "${VIRT_OVERRIDE:-}" ]; then
    printf '%s' "$VIRT_OVERRIDE"
    return 0
  fi
  if command -v systemd-detect-virt >/dev/null 2>&1; then
    local v
    v="$(systemd-detect-virt 2>/dev/null || true)"
    printf '%s' "${v:-none}"
  else
    printf 'none'
  fi
}

# _free_bytes <dir> → free bytes on the filesystem holding <dir>, walking up to
# the nearest existing ancestor (the install dir may not exist yet pre-install).
_free_bytes() {
  local dir="$1"
  while [ -n "$dir" ] && [ ! -d "$dir" ]; do
    dir="$(dirname "$dir")"
  done
  [ -d "$dir" ] || dir="/"
  # df -P -B1 → POSIX columns, bytes. Field 4 (1-indexed) of the data row is
  # "Available". Filesystem names can wrap to a second line, so take the last.
  df -P -B1 "$dir" 2>/dev/null | awk 'END { print $4 }'
}

# _listen_table → `ss -ltn` output, falling back to `netstat -ltn` when ss is
# absent OR present-but-yields-nothing (audit id ss-not-present: minimal images
# ship without iproute2, or ship a broken ss). Returns 1 only when NEITHER tool
# produced any output, so the caller can treat the probe as inconclusive.
_listen_table() {
  local out=""
  if command -v ss >/dev/null 2>&1; then
    out="$(ss -ltn 2>/dev/null)"
  fi
  if [ -z "$out" ] && command -v netstat >/dev/null 2>&1; then
    out="$(netstat -ltn 2>/dev/null)"
  fi
  [ -n "$out" ] || return 1
  printf '%s' "$out"
}

# _port_holder <port> → best-effort "name (pid)" of the process holding <port>,
# or empty. Uses `ss -ltnp` (needs root for the process column); silent on fail.
_port_holder() {
  local port="$1" out
  command -v ss >/dev/null 2>&1 || return 0
  out="$(ss -ltnp "sport = :$port" 2>/dev/null | grep -oE 'users:\(\("[^"]+"' | head -1)"
  out="${out##*\"}"
  out="${out%%\"*}"
  printf '%s' "$out"
}

# _box_public_ip → this box's public IPv4 via the two best-effort services in
# the research (api.ipify.org, then ifconfig.co). Empty on total failure.
_box_public_ip() {
  local ip
  ip="$(curl -4 -fsS --max-time 5 https://api.ipify.org 2>/dev/null || true)"
  if [ -z "$ip" ]; then
    ip="$(curl -4 -fsS --max-time 5 https://ifconfig.co 2>/dev/null || true)"
  fi
  # Strip stray whitespace/newlines.
  printf '%s' "$ip" | tr -d '[:space:]'
}

# _resolve_domain <domain> → newline-separated A-record IPs. Query REAL public
# DNS first (dig/host bypass /etc/hosts); getent is LAST because it consults
# /etc/hosts, where a box whose hostname == the panel FQDN (the cloud-init norm)
# has 127.0.0.1/::1 entries that shadow the real A record. Empty if unresolved.
# AI-2217: a fresh cloud image ships neither dig nor host, so before getent we
# ask public DNS over HTTPS with curl (already a hard requirement); getent is
# only reached when both DoH resolvers are unreachable.
_resolve_domain() {
  local domain="$1"
  if command -v dig >/dev/null 2>&1; then
    dig +short A "$domain" 2>/dev/null
  elif command -v host >/dev/null 2>&1; then
    host -t A "$domain" 2>/dev/null | awk '/has address/ { print $NF }'
  elif _resolve_domain_doh "$domain"; then
    return 0
  elif command -v getent >/dev/null 2>&1; then
    getent ahostsv4 "$domain" 2>/dev/null | awk '{ print $1 }' | sort -u
  fi
}

# _resolve_domain_doh <domain> → A-record IPv4s from the public DNS-over-HTTPS
# JSON APIs: Cloudflare (cloudflare-dns.com/dns-query, needs the
# `accept: application/dns-json` header), then Google (dns.google/resolve).
# Returns 0 once a resolver gave a real DNS answer: Status 0 (NOERROR) prints the
# type-1 records' IPs (CNAME targets are hostnames, so the IPv4 pattern skips
# them); Status 3 (NXDOMAIN) prints nothing, an authoritative "no A record".
# Returns 1 when neither answered usably (blocked egress, timeout, SERVFAIL, a
# captive-portal HTML page) so the caller falls back to getent. Each request is
# capped at 5 s, so an offline box loses at most ~10 s here.
_resolve_domain_doh() {
  local domain="$1" url body status
  command -v curl >/dev/null 2>&1 || return 1
  for url in "https://cloudflare-dns.com/dns-query?name=${domain}&type=A" \
    "https://dns.google/resolve?name=${domain}&type=A"; do
    body="$(curl -fsS --connect-timeout 3 --max-time 5 \
      -H 'accept: application/dns-json' "$url" 2>/dev/null)" || continue
    status="$(printf '%s' "$body" | grep -oE '"Status": *[0-9]+' | head -1 | grep -oE '[0-9]+$')"
    case "$status" in
      0)
        printf '%s' "$body" | grep -oE '"data": *"[0-9]{1,3}(\.[0-9]{1,3}){3}"' |
          grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}' | sort -u
        return 0
        ;;
      3) return 0 ;;
    esac
  done
  return 1
}

# _strip_loopback <ip-list> → echo only the non-loopback IPs (drop 127.x, ::1,
# ::, 0.0.0.0). A box whose hostname == the panel FQDN resolves the FQDN to
# loopback via /etc/hosts; that is never the public A record, so it must not
# masquerade as one. Pure — bats-tested.
_strip_loopback() {
  local ip
  for ip in $1; do
    case "$ip" in
      127.* | ::1 | ::1/* | 0.0.0.0 | ::) continue ;;
      *) printf '%s\n' "$ip" ;;
    esac
  done
}

# _default_route_table → `ip -4 route show default` output. Honors
# ROUTE_TABLE_OVERRIDE (tests inject crafted tables). Returns 1 when `ip` is
# absent so the caller treats route assessment as inconclusive (skip, never warn).
_default_route_table() {
  if [ -n "${ROUTE_TABLE_OVERRIDE:-}" ]; then
    printf '%s\n' "$ROUTE_TABLE_OVERRIDE"
    return 0
  fi
  command -v ip >/dev/null 2>&1 || return 1
  ip -4 route show default 2>/dev/null
}

# _netplan_present → 0 when this host is netplan-managed (the only network stack
# the opt-in auto-fix supports). RHEL/NetworkManager and systemd-networkd-only
# boxes return non-zero; the caller then warns instead of mutating.
_netplan_present() {
  command -v netplan >/dev/null 2>&1 && [ -d /etc/netplan ]
}

# _apply_route_metric_fix <dev> → deprioritize the private interface <dev>'s
# default route via a reversible netplan drop-in (dhcp4-overrides.route-metric),
# then `netplan apply`. Idempotent (skips if the drop-in already exists). Only
# ever touches the PRIVATE NIC — never the public default route.
_apply_route_metric_fix() {
  local dev="$1"
  if [ -e "$ROUTE_FIX_FILE" ]; then
    info "Default-route fix already present at ${ROUTE_FIX_FILE} — leaving it untouched (idempotent)."
    return 0
  fi
  cat >"$ROUTE_FIX_FILE" <<YAML
# Written by the AI Admin Panel installer (AAP_FIX_ROUTING) — AI-423.
# The private interface ${dev} advertised a DHCP default route at a metric <= the
# public default, so Docker container return traffic egressed ${dev} and was
# dropped (panel unreachable / no container egress). Deprioritize it so the public
# default always wins. Revert: delete this file and run 'netplan apply'.
network:
  version: 2
  ethernets:
    ${dev}:
      dhcp4-overrides:
        route-metric: ${ROUTE_FIX_METRIC}
YAML
  chmod 600 "$ROUTE_FIX_FILE" 2>/dev/null || true
  if netplan apply >/dev/null 2>&1; then
    info "Fixed default-route priority: deprioritized ${dev} to metric ${ROUTE_FIX_METRIC} (public NIC now preferred). Wrote ${ROUTE_FIX_FILE}; revert by deleting it and running 'netplan apply'."
  else
    warn "Wrote ${ROUTE_FIX_FILE} but 'netplan apply' failed — run 'netplan apply' manually (or reboot) to finish deprioritizing ${dev}'s default route."
  fi
}

# ── GPU detection (AI-419) ────────────────────────────────────────────────────
# The installer needs to know whether THIS host has an NVIDIA GPU so it can
# install + configure the NVIDIA Container Toolkit (without it, a GPU-aware
# deploy silently can't start a container). This mirrors internal/gpu/detect.go's
# sysfs PCI scan so the installer and the running panel agree on "GPU present?".

# gpu_pci_class_is_gpu <vendor> <class> → 0 if a PCI device with this sysfs
# vendor and class (e.g. "0x1002 0x120000") is a GPU. Mirrors isGPUClass in
# internal/gpu/detect.go (AI-2325). VGA (0x0300xx) and 3D controller (0x0302xx,
# how datacenter GPUs enumerate) count for the known GPU vendors NVIDIA, AMD and
# Intel. AMD Instinct cards enumerate as display-other (0x0380xx, MI210/MI250)
# or processing accelerator (0x1200xx, MI300X); those two classes count only for
# AMD and NVIDIA, because 0x1200 is a generic accelerator class (crypto offload,
# AI ASICs) and another vendor's device in it is not a GPU. Pure (no I/O).
gpu_pci_class_is_gpu() {
  local vendor="${1#0x}" class="${2#0x}"
  case "$vendor" in
    10de | 1002 | 8086) ;;
    *) return 1 ;;
  esac
  case "$class" in
    0300* | 0302*) return 0 ;;
  esac
  case "$vendor" in
    10de | 1002) ;;
    *) return 1 ;;
  esac
  case "$class" in
    0380* | 1200*) return 0 ;;
  esac
  return 1
}

# nvidia_pci_present <"vendor class" table> → 0 if any row is an NVIDIA (0x10de)
# GPU-class device (gpu_pci_class_is_gpu decides the class). Each row is a
# device's sysfs `vendor` then `class` value, whitespace-separated (e.g.
# "0x10de 0x030000"). Pure (no I/O) so bats can exercise it with crafted tables.
nvidia_pci_present() {
  local table="$1" vendor class
  while read -r vendor class _; do
    case "$vendor" in
      0x10de | 10de) ;;
      *) continue ;;
    esac
    gpu_pci_class_is_gpu "$vendor" "$class" && return 0
  done <<EOF
$table
EOF
  return 1
}

# host_has_nvidia_gpu → 0 if this host has an NVIDIA GPU on the PCI bus. PCI
# devices are NOT namespaced, so the sysfs scan sees host GPUs from the
# installer's shell. Honors GPU_SYSFS_ROOT (tests point it at a fixture dir).
host_has_nvidia_gpu() {
  local root="${GPU_SYSFS_ROOT:-/sys/bus/pci/devices}" dev table="" v c
  [ -d "$root" ] || return 1
  for dev in "$root"/*; do
    [ -d "$dev" ] || continue
    [ -r "$dev/vendor" ] && [ -r "$dev/class" ] || continue
    read -r v <"$dev/vendor" || continue
    read -r c <"$dev/class" || continue
    table="${table}${v} ${c}"$'\n'
  done
  nvidia_pci_present "$table"
}

# host_has_nvidia_driver → 0 if an NVIDIA kernel driver is loaded. A GPU can be
# present on the bus with NO driver (fresh OVH/bare image) — the toolkit still
# installs, but deployed containers (and the rich nvidia-smi view) need the
# driver, so the installer warns when this returns non-zero.
host_has_nvidia_driver() {
  if command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi >/dev/null 2>&1; then
    return 0
  fi
  [ -e /proc/driver/nvidia/version ] && return 0
  [ -e /dev/nvidia0 ] && return 0
  return 1
}

# ── individual checks (each its own function; HARD ones echo a fix + return 2) ─

# check_root — EUID 0. Non-root tolerated only under DRY_RUN (mirrors
# install.sh's check_root, which we preserve the intent of).
check_root() {
  # EUID_OVERRIDE lets bats exercise the non-root path without assigning the
  # readonly $EUID (mirrors platform.sh's ARCH_OVERRIDE). Falls back to the real
  # $EUID, then `id -u`.
  local euid="${EUID_OVERRIDE:-${EUID:-$(id -u)}}"
  if [ "$euid" -eq 0 ]; then
    info "Running as root."
    return 0
  fi
  if [ "${DRY_RUN:-false}" = "true" ]; then
    warn "Not running as root — dry-run mode allows non-root execution."
    return 0
  fi
  pf_fail "Must run as root. Fix: re-run with 'sudo bash $0' (or as the root user)."
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# check_systemd — systemctl present AND PID 1 is systemd. We need systemd-
# managed Docker (`systemctl enable --now docker`), so a non-systemd init
# (OpenRC/SysV/inside an unmanaged container) is a hard fail.
check_systemd() {
  if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
    info "systemd is PID 1 (required for systemd-managed Docker)."
    return 0
  fi
  pf_fail "systemd is required (we manage Docker via systemctl) but PID 1 is not systemd. Fix: install on a systemd-based OS (Ubuntu 22.04+, Debian 12+, Rocky/AlmaLinux 9+); Alpine/OpenRC and non-systemd containers are unsupported."
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# check_arch_supported — 64-bit only. Honors ARCH_OVERRIDE for tests; otherwise
# reads `uname -m`. Reuses platform.sh's detect_arch when sourced alongside, but
# the verdict comes from the pure arch_supported predicate either way.
check_arch_supported() {
  local m="${ARCH_OVERRIDE:-$(uname -m)}"
  if arch_supported "$m"; then
    info "Architecture ${m} is 64-bit (supported)."
    return 0
  fi
  pf_fail "Unsupported architecture '${m}'. Fix: install on a 64-bit host — x86_64/amd64 or aarch64/arm64. 32-bit (i686/armv7l) is not supported."
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# check_virt — reject OpenVZ and (unprivileged) LXC: rootful Docker can't run
# there. KVM/none/docker/cloud hypervisors pass.
check_virt() {
  local v
  v="$(_detect_virt)"
  if virt_supported "$v"; then
    info "Virtualization '${v}' supports rootful Docker."
    return 0
  fi
  pf_fail "Virtualization '${v}' cannot run rootful Docker (OpenVZ / unprivileged LXC lack the required kernel capabilities). Fix: use a KVM/Xen VM or a bare-metal/dedicated host. Ask your provider for a 'KVM' plan, not an 'OpenVZ/LXC container' plan."
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# check_disk — >= 5 GiB free on the install dir (default /opt/aiadminpanel).
check_disk() {
  local dir="${INSTALL_DIR:-/opt/aiadminpanel}" bytes gib
  bytes="$(_free_bytes "$dir")"
  if disk_ok "$bytes"; then
    gib=$((bytes / 1024 / 1024 / 1024))
    info "Disk space OK: ${gib} GiB free at ${dir} (need >= 5 GiB)."
    return 0
  fi
  pf_fail "Not enough free disk space at ${dir} (need >= 5 GiB; the Docker images alone are several GiB). Fix: free space ('docker system prune -af', remove old logs/backups) or attach a larger volume, then re-run."
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# check_admin_password — a supplied ADMIN_PASSWORD must pass the realm's
# password policy (AI-2521), or Keycloak refuses it halfway through the
# install, after Docker and the secrets are set up. A generated one always does.
check_admin_password() {
  [ -n "${ADMIN_PASSWORD:-}" ] || return 0
  if admin_password_ok "$ADMIN_PASSWORD" "${ADMIN_EMAIL:-admin@${PANEL_DOMAIN:-}}"; then
    info "ADMIN_PASSWORD meets the sign-in password policy."
    return 0
  fi
  pf_fail "ADMIN_PASSWORD does not meet the sign-in password policy: it needs 12 to 128 characters and must not be the admin email (${ADMIN_EMAIL:-admin@${PANEL_DOMAIN:-<domain>}}). Fix: choose a longer password, or unset ADMIN_PASSWORD to have one generated, then re-run."
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# check_ports_free — 80 and 443 must be free (Traefik binds them for TLS). Probe
# with ss, fall back to netstat. Name the holder when we can and print the exact
# stop/disable command. Preserves the intent of install.sh's check_ports.
check_ports_free() {
  local table port holder failed=0
  if ! table="$(_listen_table)"; then
    warn "Neither 'ss' nor 'netstat' is available — cannot verify ports 80/443 are free; continuing (the stack will fail loudly at bind time if they're held)."
    return 0
  fi
  for port in 80 443; do
    if port_in_use "$table" "$port"; then
      holder="$(_port_holder "$port")"
      if [ -n "$holder" ]; then
        pf_fail "Port ${port} is held by '${holder}'. Fix: 'systemctl stop ${holder} && systemctl disable ${holder}' (or remove the conflicting service), then re-run."
      else
        pf_fail "Port ${port} is already in use. Fix: identify the holder with 'ss -ltnp \"sport = :${port}\"', stop/disable that service, then re-run."
      fi
      failed=1
    else
      info "Port ${port} is free."
    fi
  done
  [ "$failed" -eq 0 ] && return 0
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# _panel_image_tag_status <tag> → echoes the HTTP status GHCR gives for the
# panel image manifest at <tag> (200 found, 404 not found, 000 unreachable).
# Anonymous pull token, same flow as aap-update.sh's list_remote_tags; no jq
# (a fresh box may not have it yet).
_panel_image_tag_status() {
  local tag="$1" repo="aiadminpanel/ai-admin-panel" token code
  token="$(curl -fsS --max-time 10 \
    "https://ghcr.io/token?scope=repository:${repo}:pull&service=ghcr.io" 2>/dev/null |
    sed -n 's/.*"token":"\([^"]*\)".*/\1/p')"
  if [ -z "$token" ]; then
    echo 000
    return 0
  fi
  code="$(curl -sS -o /dev/null -w '%{http_code}' -I --max-time 10 \
    -H "Authorization: Bearer ${token}" \
    -H 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.manifest.v1+json' \
    "https://ghcr.io/v2/${repo}/manifests/${tag}" 2>/dev/null)"
  echo "${code:-000}"
}

# check_panel_image_tag — HARD gate (AI-2172): the panel image tag named by
# PANEL_VERSION must exist on GHCR. Without this gate a mistyped or
# unpublished version failed at step 14, after Docker, secrets, Keycloak and
# the databases were already set up. A registry that cannot be reached only
# warns (check_outbound already reports egress problems), so an
# egress-filtered box is not blocked by this check alone.
check_panel_image_tag() {
  local tag="${PANEL_VERSION:-latest}" status
  status="$(_panel_image_tag_status "$tag")"
  case "$status" in
    200) return 0 ;;
    404 | 401 | 403)
      pf_fail "Panel version '${tag}' does not exist: there is no image ghcr.io/aiadminpanel/ai-admin-panel:${tag}. Fix: set PANEL_VERSION to a published release (for example PANEL_VERSION=2.22.0 or PANEL_VERSION=v2.22.0), or leave it unset for the latest release. No changes were made to this box."
      return "$PREFLIGHT_EXIT_MISSING_PREREQ"
      ;;
    *)
      warn "Could not check that panel version '${tag}' exists on ghcr.io (HTTP ${status}). If it does not, the install will fail when it pulls the panel image."
      return 0
      ;;
  esac
}

# check_outbound — best-effort reachability to the endpoints the install pulls
# from. WARN only (proxied/egress-filtered networks are legitimate); never a
# hard fail.
check_outbound() {
  local host url unreachable=()
  for host in ghcr.io get.docker.com acme-v02.api.letsencrypt.org; do
    url="https://${host}"
    if ! curl -fsS --max-time 5 -o /dev/null "$url" 2>/dev/null; then
      unreachable+=("$host")
    fi
  done
  if [ "${#unreachable[@]}" -eq 0 ]; then
    info "Outbound reachability OK (ghcr.io, get.docker.com, Let's Encrypt)."
    return 0
  fi
  warn "Could not reach: ${unreachable[*]}. The install pulls images and a TLS cert from these — if they stay blocked the install will fail later. Check egress firewall/proxy/DNS, then re-run if needed."
  return 0
}

# check_dns — only when PANEL_DOMAIN is set and TLS_MODE is not DNS-01. Resolve
# the domain and compare to this box's public IP. A MISMATCH is a HARD stop:
# letting ACME HTTP-01 hammer a wrong/missing record risks a week-long Let's
# Encrypt rate-limit lockout on the domain (research risk #5).
check_dns() {
  local domain="${PANEL_DOMAIN:-}" mode="${TLS_MODE:-letsencrypt}"
  if [ -z "$domain" ]; then
    return 0 # nothing to validate yet (interactive prompt happens later)
  fi
  if tls_mode_is_dns01; then
    info "TLS_MODE=${mode} — skipping public A-record check (DNS-01)."
    return 0
  fi
  local resolved box_ip tries=0
  # An EMPTY answer is asked again (AI-2786): a resolver pool (Vultr's
  # 108.61.10.10 and 108.61.115.10) where one backend cached NXDOMAIN for a
  # seconds-old record answers empty and then the IP, query by query, for up to
  # the zone's negative TTL. 12 tries, 5 s apart by default. A wrong address is
  # still a hard stop at once, below.
  while :; do
    tries=$((tries + 1))
    resolved="$(_resolve_domain "$domain")"
    [ -n "$resolved" ] && break
    [ "$tries" -ge "${PREFLIGHT_DNS_EMPTY_TRIES:-12}" ] && break
    [ "$tries" -eq 1 ] && info "${domain} has no A record yet from this box's resolver; asking again for up to a minute (cached 'no such name' answers can linger)."
    sleep "${PREFLIGHT_DNS_RETRY_INTERVAL:-5}"
  done
  box_ip="$(_box_public_ip)"
  if [ -z "$box_ip" ]; then
    warn "Could not determine this box's public IP (api.ipify.org/ifconfig.co unreachable) — skipping the DNS match check. Make sure ${domain} points here before the TLS step or Let's Encrypt will fail."
    return 0
  fi
  if [ -z "$resolved" ]; then
    pf_fail "${domain} does not resolve to any A record (asked ${tries} times). Fix: point the A record for ${domain} at ${box_ip} (this box) and re-run. (Skipping this lets Let's Encrypt HTTP-01 fail repeatedly and can lock the domain out for a week.)"
    return "$PREFLIGHT_EXIT_MISSING_PREREQ"
  fi
  # Ignore loopback (127.x / ::1): a box whose hostname == ${domain} resolves it
  # to loopback via /etc/hosts (the cloud-init norm), which is never the public A
  # record. So a loopback-ONLY result is "inconclusive" → warn-and-continue (don't
  # break valid cloud installs); a non-loopback mismatch is a positive hard fail.
  local public
  public="$(_strip_loopback "$resolved" | tr '\n' ' ')"
  if [ -z "${public// /}" ]; then
    warn "Could not confirm the public A record for ${domain} from this host (it may be shadowed by an /etc/hosts hostname entry — common on cloud images). Ensure ${domain} points at ${box_ip} before the TLS step or Let's Encrypt will fail. Proceeding."
    return 0
  fi
  if dns_matches "$public" "$box_ip"; then
    info "DNS OK: ${domain} resolves to ${box_ip} (this box)."
    return 0
  fi
  pf_fail "${domain} resolves to '${public}' but this box is ${box_ip}. Fix: point the A record for ${domain} at ${box_ip} and re-run. (Re-running against a wrong record risks a week-long Let's Encrypt rate-limit lockout — use TLS_MODE=letsencrypt-dns for DNS-01 if you can't change the A record.)"
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# ── DNS resolver gate (AI-2319) ──────────────────────────────────────────────
# A fresh OVH OpenStack Rocky Linux 10 server got DNS servers from DHCP
# (10.1.0.2/3) that answered every query with an empty reply. dnf failed with
# "Could not resolve host" and nothing could be installed, while 1.1.1.1 was
# reachable and answered normally. So before anything is installed, or a
# temporary domain is claimed, the installer asks the box's own resolver (the
# one dnf, apt and Docker use) for a name it must reach anyway.
PREFLIGHT_DNS_PROBE_HOST="${PREFLIGHT_DNS_PROBE_HOST:-get.aiadminpanel.com}"

# resolver_verdict <resolves: yes|no> <internet-by-ip: yes|no> → ok |
# broken-dns (no answer, but the internet is reachable by IP: the resolver is
# the fault) | offline (no internet at all, or only through a proxy). Pure.
resolver_verdict() {
  if [ "$1" = "yes" ]; then
    echo ok
  elif [ "$2" = "yes" ]; then
    echo broken-dns
  else
    echo offline
  fi
}

# _system_resolves <host> → 0 when the box's own resolver returns an address.
# getent goes through nsswitch, exactly like dnf and apt. Without getent, curl's
# exit 6 ("could not resolve host") is the same signal.
_system_resolves() {
  local host="$1" rc
  if command -v getent >/dev/null 2>&1; then
    [ -n "$(getent ahosts "$host" 2>/dev/null)" ]
    return
  fi
  rc=0
  curl -sS --connect-timeout 3 --max-time 5 -o /dev/null "https://${host}/" 2>/dev/null || rc=$?
  [ "$rc" -ne 6 ]
}

# _internet_by_ip → 0 when a public resolver answers HTTPS by its IP address
# (no DNS needed): Cloudflare 1.1.1.1, then Quad9 9.9.9.9. 5 s cap each.
_internet_by_ip() {
  local ip
  for ip in 1.1.1.1 9.9.9.9; do
    curl -s --connect-timeout 3 --max-time 5 -o /dev/null "https://${ip}/" 2>/dev/null && return 0
  done
  return 1
}

# _nm_active_connection → the name of the first active NetworkManager
# connection that is not loopback, or nothing when nmcli is absent.
_nm_active_connection() {
  command -v nmcli >/dev/null 2>&1 || return 0
  local line name
  while IFS= read -r line; do
    name="${line%:*}"
    case "${line##*:}" in loopback) continue ;; esac
    [ -n "$name" ] && { printf '%s' "$name"; return 0; }
  done < <(nmcli -t -f NAME,TYPE connection show --active 2>/dev/null)
}

check_resolver() {
  local host="$PREFLIGHT_DNS_PROBE_HOST" resolves=no by_ip=no verdict conn
  _system_resolves "$host" && resolves=yes
  if [ "$resolves" = "no" ]; then
    _internet_by_ip && by_ip=yes
  fi
  verdict="$(resolver_verdict "$resolves" "$by_ip")"
  case "$verdict" in
    ok)
      info "DNS resolution OK (${host} resolves)."
      return 0
      ;;
    offline)
      warn "This box cannot resolve ${host}, and 1.1.1.1 is not reachable either: it looks offline, or it reaches the internet only through a proxy. The install downloads Docker and images and will fail without internet access."
      return 0
      ;;
  esac
  conn="$(_nm_active_connection)"
  [ -n "$conn" ] || conn="<connection>"
  pf_fail "This box cannot resolve ${host}, but the internet is reachable by IP (1.1.1.1 answers). The DNS servers this box uses (see /etc/resolv.conf, usually set by DHCP) are not answering, so no package can be installed. Fix: use public DNS servers, then re-run the installer.
  NetworkManager (Rocky, AlmaLinux, RHEL, CentOS Stream; list connections with 'nmcli con show'):
    nmcli con mod \"${conn}\" ipv4.ignore-auto-dns yes ipv4.dns \"1.1.1.1 9.9.9.9\"
    nmcli con up \"${conn}\"
  systemd-resolved (Ubuntu, Debian): in /etc/systemd/resolved.conf, under [Resolve], set
    DNS=1.1.1.1 9.9.9.9
    Domains=~.
    then run: systemctl restart systemd-resolved
    (If the DHCP servers are still used, switch them off for the interface; with netplan: dhcp4-overrides: {use-dns: false}, then netplan apply.)
  Check with: getent hosts ${host}
(No changes were made to this box.)"
  return "$PREFLIGHT_EXIT_MISSING_PREREQ"
}

# tls_cert_resolver — map TLS_MODE to the Traefik certresolver the panel/keycloak
# router labels must use. letsencrypt-dns (or its old alias cloudflare) → the
# DNS-01 resolver (letsencrypt-dns), which works on hosts where inbound :80 is
# closed/proxied; letsencrypt or unset → the HTTP-01 resolver (letsencrypt). Any
# other value prints nothing and fails (AI-2400; check_tls_mode stops the
# installer on it first). The installer writes the result as CERT_RESOLVER
# in .env; docker-compose.yml reads ${CERT_RESOLVER:-letsencrypt} on the routers.
# Pinning AI-425: before this, cloudflare mode defined the DNS-01 resolver but the
# routers still pinned letsencrypt (HTTP-01), so DNS-01 was wired yet never used.
tls_cert_resolver() {
  case "${TLS_MODE:-letsencrypt}" in
    letsencrypt-dns | cloudflare) echo "letsencrypt-dns" ;;
    letsencrypt) echo "letsencrypt" ;;
    *) return 1 ;;
  esac
}

# check_time_sync — NTP synchronized? Clock skew breaks ACME JWS verification
# (badNonce / signature failure → silent self-signed cert). WARN with the
# chrony/timesyncd hint; the caller decides whether to auto-enable NTP (this
# function never mutates).
check_time_sync() {
  local synced=""
  if command -v timedatectl >/dev/null 2>&1; then
    synced="$(timedatectl show -p NTPSynchronized --value 2>/dev/null || true)"
  fi
  if [ "$synced" = "yes" ]; then
    info "Clock is NTP-synchronized."
    return 0
  fi
  warn "Clock is NOT NTP-synchronized — skew breaks Let's Encrypt (badNonce/signature errors → silent self-signed cert). Fix: 'timedatectl set-ntp true' (Debian/Ubuntu: systemd-timesyncd; RHEL/AL2023: 'dnf install -y chrony && systemctl enable --now chronyd'), then re-check with 'timedatectl'."
  return 0
}

# check_cgroup_v2 — WARN only when cgroup v2 is absent (v1 long tail: Amazon
# Linux 2, CentOS 7). Docker still runs on v1, so this never hard-fails.
check_cgroup_v2() {
  if [ -f /sys/fs/cgroup/cgroup.controllers ]; then
    info "cgroup v2 is active."
    return 0
  fi
  warn "cgroup v1 detected (no /sys/fs/cgroup/cgroup.controllers). Docker still runs, but v1 is deprecated (Docker Engine v29 / systemd v258 drop it). Recommended: switch to cgroup v2 ('grubby --update-kernel=ALL --args=systemd.unified_cgroup_hierarchy=1 && reboot') or use a v2-default image (Amazon Linux 2023, Ubuntu 22.04+, Rocky/Alma 9+)."
  return 0
}

# check_default_routes — WARN only (soft gate). Detect the multi-homed
# dual-default-route footgun (AI-423). Default: warn with the offending NIC + the
# fix + the AAP_FIX_ROUTING hint. With AAP_FIX_ROUTING=1 on a netplan host: apply
# the reversible drop-in automatically. Never changes the install verdict.
check_default_routes() {
  local table offender dev metric
  if ! table="$(_default_route_table)" || [ -z "$table" ]; then
    return 0 # no `ip` / no default routes to assess — nothing to do
  fi
  if ! offender="$(dangerous_default_routes "$table")"; then
    info "Default route OK (no conflicting private-network default)."
    return 0
  fi
  dev="${offender%% *}"
  metric="${offender##* }"
  if [ "${AAP_FIX_ROUTING:-}" = "1" ] || [ "${AAP_FIX_ROUTING:-}" = "true" ]; then
    if _netplan_present; then
      _apply_route_metric_fix "$dev"
      return 0
    fi
    warn "AAP_FIX_ROUTING is set but this host is not netplan-managed — auto-fix is netplan-only for now. Manually give '${dev}'s default route a higher metric than your public NIC so Docker container traffic stops egressing '${dev}'."
    return 0
  fi
  warn "Two default routes detected: a private-network default on '${dev}' (metric ${metric}) at the same-or-better priority as your public default. Docker container return traffic can exit '${dev}' and be silently dropped — the panel becomes unreachable and containers can't reach the internet. Fix: deprioritize '${dev}'s default route, or re-run the installer with AAP_FIX_ROUTING=1 to apply it automatically (netplan hosts). Details: https://docs.aiadminpanel.com/docs/deployment/multi-homed-vps-routing"
  return 0
}

# ── orchestrator ──────────────────────────────────────────────────────────────

# preflight_checks — run every gate. Hard gates run first (cheapest, most
# fundamental → DNS last since it does network I/O). Soft gates always run so
# the operator sees ALL warnings in one pass. Returns 2 if any hard gate failed.
preflight_checks() {
  info "Running pre-flight checks (fail fast before any changes)..."
  local hard_failed=0 rc

  # Hard gates — accumulate failures so the operator sees every blocker at once,
  # rather than fixing one and re-running to discover the next.
  local check
  for check in check_root check_systemd check_arch_supported check_virt \
    check_disk check_ports_free check_dns check_panel_image_tag check_admin_password; do
    "$check"
    rc=$?
    [ "$rc" -ne 0 ] && hard_failed=1
  done

  # Soft gates — WARN only, never change the verdict.
  check_outbound
  check_default_routes
  check_time_sync
  check_cgroup_v2

  if [ "$hard_failed" -ne 0 ]; then
    pf_fail "Pre-flight failed — fix the blocker(s) above and re-run. (No changes were made to this box.)"
    return "$PREFLIGHT_EXIT_MISSING_PREREQ"
  fi
  info "Pre-flight checks passed."
  return 0
}

# ===== scripts/lib/gpu.sh =====
# scripts/lib/gpu.sh — NVIDIA GPU driver detection and plan (AI-2330).
#
# WHY: the installer configures the NVIDIA Container Toolkit, but when a card is
# on the PCI bus with no kernel driver it only warns, and the panel then sees a
# GPU it cannot use (Ollama on CPU, vLLM cannot start). This module looks at the
# host's driver state and decides what the installer should do about it. The
# rules are in docs/research/installer-gpu-driver-design-2026-11.md §1:
#   * a loaded driver is never touched (warn below 580: vLLM's CUDA 13 image);
#   * Turing or newer (PCI device ID >= 0x1e00) gets branch 620, open modules;
#   * older cards (Maxwell/Pascal/Volta) get branch 580, proprietary modules;
#   * installed-but-not-loaded means a reboot is pending, not a reinstall.
#
# Units of AI-2330: 1 detection, plan and the --gpu-driver flag; 2 the install
# on Rocky/Alma/CentOS Stream/RHEL 9 and 10; 3 the install on Ubuntu 22.04/24.04
# and Debian 12/13, plus the cloud guards (a provider-managed or licensed
# driver is left to the provider). Other systems report the plan and continue.
# AI-2320 adds NVIDIA Fabric Manager on NVSwitch (HGX) boards, with a fresh
# driver and next to a driver that is already there (design §10).
#
# Pure function definitions only, nothing runs at source time (same contract as
# preflight.sh). Pure predicates (bats calls them with crafted input):
#   gpu_driver_mode_valid <mode>
#   gpu_arch_from_device_id <pci-device-id>
#   gpu_driver_major <driver-version>
#   gpu_sb_state_from_mokutil <mokutil --sb-state output>
#   gpu_nvidia_version_from_proc <contents of /proc/driver/nvidia/version>
#   gpu_driver_plan <vendor> <arch> <driver> <installed> <nouveau> <sb> <nvswitch> <machine> [cloud]
#   gpu_plan_for_os <plan> <os_id> <major>
#   gpu_kernel_flavour <uname -r>, gpu_debian_codename <major>
#   gpu_nvswitch_gen4_device <pci-device-id>, gpu_fabric_state_from_smi <text>,
#   gpu_fabric_state_is_nvswitch <state>, gpu_fm_version_from_output <text>,
#   gpu_fm_version_matches <driver> <fm>, gpu_upstream_version <pkg version>,
#   gpu_fm_packages <family> <branch> <version> <nvlsm>
# Probes (read-only; every source is overridable for tests):
#   GPU_SYSFS_ROOT (PCI devices), GPU_SYS_MODULE_ROOT (/sys/module),
#   GPU_PROC_NVIDIA_VERSION, GPU_EFIVARS_DIR, GPU_DMI_ROOT, GPU_GRIDD_CONF,
#   GPU_GRIDD_UNITS, ARCH_OVERRIDE; nvidia-smi, nv-fabricmanager, mokutil, rpm,
#   dpkg-query, systemctl and cloud-init are looked up on PATH.

# Exit codes of the driver step (design §3), for automation to rely on.
export GPU_EXIT_REBOOT_REQUIRED=20
export GPU_EXIT_SECURE_BOOT=21

# vLLM v0.31's default image is CUDA 13.0, which needs driver 580 or newer.
GPU_DRIVER_FLOOR=580
# Branch for Turing and newer: R620 is the current long-term branch (EOL 2029-09).
GPU_DRIVER_BRANCH_OPEN=620
# Last branch that supports Maxwell/Pascal/Volta (proprietary modules only).
GPU_DRIVER_BRANCH_LEGACY=580
# Ubuntu: the newest long-term "-server" branch in Ubuntu's own archive for
# 22.04 and 24.04 (packages.ubuntu.com, 2026-11-14: 580/590/595/615-server, no
# 620). 580 is NVIDIA's other long-term branch (EOL 2028-06) and meets the
# floor. Ubuntu's packages carry Canonical-signed prebuilt modules.
GPU_DRIVER_BRANCH_UBUNTU=580
GPU_DRIVER_DOC_URL="https://docs.nvidia.com/datacenter/tesla/driver-installation-guide/"

if ! declare -F info >/dev/null 2>&1; then
  info() { printf '[INFO]  %s\n' "$*"; }
fi
if ! declare -F warn >/dev/null 2>&1; then
  warn() { printf '[WARN]  %s\n' "$*" >&2; }
fi

# ── pure predicates ───────────────────────────────────────────────────────────

# gpu_driver_mode_valid <mode> → 0 for auto|skip|install.
gpu_driver_mode_valid() {
  case "$1" in
    auto | skip | install) return 0 ;;
    *) return 1 ;;
  esac
}

# gpu_arch_from_device_id <id> → "pre-turing" for NVIDIA device IDs below
# 0x1e00 (Maxwell/Pascal/Volta, e.g. V100 1db4), "turing+" from 0x1e00 (the
# first TU102) up, which includes Ampere, Ada, Hopper and Blackwell. Accepts
# "0x1eb0" or "1eb0". Returns 1 (no output) for anything that is not hex.
gpu_arch_from_device_id() {
  local id="${1#0x}"
  id="${id#0X}"
  case "$id" in
    '' | *[!0-9a-fA-F]*) return 1 ;;
  esac
  if [ $((16#$id)) -lt $((16#1e00)) ]; then
    echo "pre-turing"
  else
    echo "turing+"
  fi
}

# gpu_driver_major <version> → the branch number ("575.57.08" → 575). Returns 1
# when the version does not start with digits.
gpu_driver_major() {
  local major="${1%%.*}"
  case "$major" in
    '' | *[!0-9]*) return 1 ;;
  esac
  echo "$major"
}

# gpu_sb_state_from_mokutil <output> → on|off|unknown. mokutil --sb-state
# prints "SecureBoot enabled" or "SecureBoot disabled" (and "This system
# doesn't support Secure Boot" on legacy BIOS, which is off).
gpu_sb_state_from_mokutil() {
  case "$1" in
    *"SecureBoot enabled"*) echo "on" ;;
    *"SecureBoot disabled"* | *"doesn't support Secure Boot"* | *"not supported"*) echo "off" ;;
    *) echo "unknown" ;;
  esac
}

# gpu_nvidia_version_from_proc <text> → the driver version in
# /proc/driver/nvidia/version ("NVRM version: NVIDIA UNIX Open Kernel Module for
# x86_64  620.70.06  Release Build ..."). Returns 1 when none is found.
gpu_nvidia_version_from_proc() {
  local word
  # shellcheck disable=SC2013 # splitting on words is the point
  for word in $(printf '%s\n' "$1" | sed -n '1p'); do
    case "$word" in
      [0-9]*.[0-9]*)
        echo "$word"
        return 0
        ;;
    esac
  done
  return 1
}

# gpu_driver_plan <vendor> <arch> <driver> <installed> <nouveau> <sb> <nvswitch> <machine>
# The design's decision table (§1) as code. Inputs:
#   vendor    nvidia | amd | none   (first GPU found on the PCI bus)
#   arch      turing+ | pre-turing | "" (unknown device ID)
#   driver    loaded driver version, "unknown" if loaded but unreadable, "" if none
#   installed yes | no   (driver packages present but not loaded)
#   nouveau   yes | no   (the built-in display driver is loaded)
#   sb        on | off | unknown   (Secure Boot)
#   nvswitch  no | yes | gen4   (HGX board: Fabric Manager needed; gen4 is
#             the fourth-generation NVSwitch of HGX B100/B200/B300, which
#             also needs the NVLink Subnet Manager, nvlsm)
#   machine   uname -m
#   cloud     none | vgpu | vultr | aws-grid   (optional, default none): a
#             provider that installs or licenses the driver itself
# Prints key=value lines; "action" is always first:
#   action=none|amd-later|leave|reboot-pending|manual|install
#   flavour=open|proprietary, branch=<NNN>      (install only)
#   reboot=yes|no                               (install: nouveau must go)
#   secureboot_stop=yes|no                      (install: needs MOK enrolment)
#   fabric_manager=yes|no, nvlsm=yes|no         (install: always; leave: only
#                                               when an NVSwitch is present)
#   reason=<token>                              (manual/amd-later: why)
#   warn=driver-below-floor|pre-turing-vllm     (zero or more)
gpu_driver_plan() {
  local vendor="$1" arch="$2" driver="$3" installed="$4" nouveau="$5" sb="$6" nvswitch="$7" machine="$8" cloud="${9:-none}" major
  case "$vendor" in
    nvidia) ;;
    amd)
      echo "action=amd-later"
      echo "reason=amd-driver-not-automated"
      return 0
      ;;
    *)
      echo "action=none"
      return 0
      ;;
  esac
  if [ -n "$driver" ]; then
    echo "action=leave"
    if major="$(gpu_driver_major "$driver")" && [ "$major" -lt "$GPU_DRIVER_FLOOR" ]; then
      echo "warn=driver-below-floor"
    fi
    # The driver stays as it is; an HGX board still needs Fabric Manager.
    if [ "$nvswitch" = "yes" ] || [ "$nvswitch" = "gen4" ]; then
      echo "fabric_manager=yes"
      _gpu_yes_no nvlsm "$([ "$nvswitch" = "gen4" ] && echo yes)"
    fi
    return 0
  fi
  # The provider installs or licenses this driver (vGPU guest, Vultr's
  # cloud-init driver, AWS GRID-only instances): never install over it.
  case "$cloud" in
    '' | none) ;;
    *)
      echo "action=manual"
      echo "reason=cloud-${cloud}"
      return 0
      ;;
  esac
  if [ "$installed" = "yes" ]; then
    echo "action=reboot-pending"
    return 0
  fi
  case "$machine" in
    aarch64 | arm64)
      echo "action=manual"
      echo "reason=arm-not-automated"
      return 0
      ;;
  esac
  case "$arch" in
    turing+)
      echo "action=install"
      echo "flavour=open"
      echo "branch=${GPU_DRIVER_BRANCH_OPEN}"
      ;;
    pre-turing)
      echo "action=install"
      echo "flavour=proprietary"
      echo "branch=${GPU_DRIVER_BRANCH_LEGACY}"
      echo "warn=pre-turing-vllm"
      ;;
    *)
      echo "action=manual"
      echo "reason=unknown-model"
      return 0
      ;;
  esac
  _gpu_yes_no reboot "$nouveau"
  _gpu_yes_no secureboot_stop "$([ "$sb" = "on" ] && echo yes)"
  _gpu_yes_no fabric_manager "$({ [ "$nvswitch" = "yes" ] || [ "$nvswitch" = "gen4" ]; } && echo yes)"
  _gpu_yes_no nvlsm "$([ "$nvswitch" = "gen4" ] && echo yes)"
}

# _gpu_yes_no <key> <value> → "<key>=yes" when value is yes, else "<key>=no".
_gpu_yes_no() {
  if [ "$2" = "yes" ]; then echo "$1=yes"; else echo "$1=no"; fi
}

# gpu_plan_get <plan> <key> → the value of the first <key>= line.
gpu_plan_get() {
  printf '%s\n' "$1" | sed -n "s/^$2=//p" | head -n 1
}

# gpu_plan_for_os <plan> <os_id> <major> → the plan adjusted to what that OS
# can install (the decision table is OS-agnostic; the archives are not):
#   * Ubuntu installs from its own archive, whose newest long-term -server
#     branch is GPU_DRIVER_BRANCH_UBUNTU. Its prebuilt modules are signed by
#     Canonical, so Secure Boot needs no enrolment (secureboot_stop=no; the
#     DKMS fallback for custom kernels checks Secure Boot itself).
#   * NVIDIA's Debian 13 repository starts at branch 590, which dropped
#     Maxwell/Pascal/Volta, and Debian's own driver is 550: no driver that
#     meets the floor for those cards there.
gpu_plan_for_os() {
  local plan="$1" os_id="$2" major="$3"
  if [ "$(gpu_plan_get "$plan" action)" != "install" ]; then
    printf '%s\n' "$plan"
    return 0
  fi
  case "$os_id" in
    ubuntu)
      printf '%s\n' "$plan" | sed -e "s/^branch=.*/branch=${GPU_DRIVER_BRANCH_UBUNTU}/" -e "s/^secureboot_stop=.*/secureboot_stop=no/"
      ;;
    debian)
      if [ "$major" = "13" ] && [ "$(gpu_plan_get "$plan" flavour)" = "proprietary" ]; then
        echo "action=manual"
        echo "reason=no-legacy-branch"
      else
        printf '%s\n' "$plan"
      fi
      ;;
    *) printf '%s\n' "$plan" ;;
  esac
}

# gpu_plan_has <plan> <key>=<value> → 0 when that exact line is in the plan.
gpu_plan_has() {
  printf '%s\n' "$1" | grep -qx -- "$2"
}

# ── probes (read-only) ────────────────────────────────────────────────────────

# gpu_probe — fills the GPU_* globals the plan reads. Never changes the host.
gpu_probe() {
  local root="${GPU_SYSFS_ROOT:-/sys/bus/pci/devices}" dev v c d
  GPU_VENDOR=none
  GPU_DEVICE_ID=""
  GPU_ARCH=""
  GPU_NVSWITCH=no
  local amd_seen=no
  if [ -d "$root" ]; then
    for dev in "$root"/*; do
      [ -r "$dev/vendor" ] || continue
      [ -r "$dev/class" ] || continue
      read -r v <"$dev/vendor" || continue
      read -r c <"$dev/class" || continue
      d=""
      [ -r "$dev/device" ] && read -r d <"$dev/device"
      case "$v" in
        0x10de | 10de)
          case "$c" in 0x0680* | 0680*) GPU_NVSWITCH=yes ;; esac
          if [ "$GPU_VENDOR" != "nvidia" ] && gpu_pci_class_is_gpu "$v" "$c"; then
            GPU_VENDOR=nvidia
            GPU_DEVICE_ID="${d#0x}"
          fi
          ;;
        0x1002 | 1002)
          gpu_pci_class_is_gpu "$v" "$c" && amd_seen=yes
          ;;
      esac
    done
  fi
  # NVIDIA wins when a box has both (this module plans NVIDIA drivers).
  if [ "$GPU_VENDOR" = "none" ] && [ "$amd_seen" = "yes" ]; then
    GPU_VENDOR=amd
  fi
  if [ "$GPU_VENDOR" = "nvidia" ]; then
    GPU_ARCH="$(gpu_arch_from_device_id "$GPU_DEVICE_ID" || true)"
    # Fourth-generation NVSwitches (HGX B100/B200/B300) are not PCI devices on
    # the host, so the GPU model is the signal there.
    if gpu_nvswitch_gen4_device "$GPU_DEVICE_ID"; then GPU_NVSWITCH=gen4; fi
  fi
  GPU_DRIVER_VERSION="$(gpu_probe_driver_version)"
  # With a driver loaded, the GPU itself says whether it sits on an NVSwitch
  # fabric (a VM with passed-through GPUs may not see the switches).
  GPU_FABRIC_STATE=""
  if [ -n "$GPU_DRIVER_VERSION" ] && command -v nvidia-smi >/dev/null 2>&1; then
    GPU_FABRIC_STATE="$(gpu_fabric_state_from_smi "$(nvidia-smi -q 2>/dev/null)")"
    if [ "$GPU_NVSWITCH" = "no" ] && gpu_fabric_state_is_nvswitch "$GPU_FABRIC_STATE"; then
      GPU_NVSWITCH=yes
    fi
  fi
  GPU_FM_VERSION="$(gpu_probe_fm_version)"
  GPU_DRIVER_INSTALLED="$(gpu_probe_driver_installed)"
  GPU_NOUVEAU=no
  [ -d "${GPU_SYS_MODULE_ROOT:-/sys/module}/nouveau" ] && GPU_NOUVEAU=yes
  GPU_SECURE_BOOT="$(gpu_probe_secure_boot)"
  GPU_MACHINE="${ARCH_OVERRIDE:-$(uname -m)}"
  GPU_CLOUD="$(gpu_probe_cloud)"
}

# gpu_probe_cloud → vgpu | vultr | aws-grid | none: providers whose GPU driver
# is theirs to install or license (design §4).
#   vgpu      a GRID/vGPU guest (licence config or the nvidia-gridd service).
#   vultr     Vultr installs licensed vGPU drivers via cloud-init on a custom
#             kernel; "the GPU will not run if the license file is missing".
#   aws-grid  AWS g6f/gr6f (fractional GPU): only AWS's GRID driver works. On
#             Nitro instances the DMI product name is the instance type.
gpu_probe_cloud() {
  local dmi="${GPU_DMI_ROOT:-/sys/class/dmi/id}" vendor="" product="" unit
  local units="${GPU_GRIDD_UNITS-/etc/systemd/system/nvidia-gridd.service /usr/lib/systemd/system/nvidia-gridd.service /lib/systemd/system/nvidia-gridd.service}"
  if [ -e "${GPU_GRIDD_CONF:-/etc/nvidia/gridd.conf}" ]; then
    echo "vgpu"
    return 0
  fi
  for unit in $units; do
    if [ -e "$unit" ]; then
      echo "vgpu"
      return 0
    fi
  done
  [ -r "$dmi/sys_vendor" ] && read -r vendor <"$dmi/sys_vendor"
  [ -r "$dmi/product_name" ] && read -r product <"$dmi/product_name"
  case "$vendor" in
    *Vultr*)
      echo "vultr"
      return 0
      ;;
  esac
  case "$product" in
    g6f.* | gr6f.*)
      echo "aws-grid"
      return 0
      ;;
  esac
  echo "none"
}

# gpu_inside_cloud_init → 0 when this process runs inside one of cloud-init's
# own stages (its systemd cgroup is cloud-init-local, cloud-init, cloud-config
# or cloud-final.service): Vultr Vendor Data, user data and the image's
# first-boot hook all run there. GPU_SELF_CGROUP is the tests' stand-in for
# /proc/self/cgroup.
gpu_inside_cloud_init() {
  grep -qE '/cloud-(init-local|init|config|final)\.service$' "${GPU_SELF_CGROUP:-/proc/self/cgroup}" 2>/dev/null
}

# gpu_wait_cloud_init — when cloud-init is still running (first boot), waits
# for it (GPU_CLOUD_INIT_TIMEOUT seconds, default 600): providers that install
# a driver on first boot would otherwise race with the installer.
# AI-2777: not when the installer runs inside cloud-init itself. cloud-init
# cannot finish before the installer does, so the wait always ran its full 10
# minutes (Vultr build 5250). AAP_SKIP_CLOUD_INIT_WAIT=1 skips it anywhere.
gpu_wait_cloud_init() {
  local limit="${GPU_CLOUD_INIT_TIMEOUT:-600}"
  command -v cloud-init >/dev/null 2>&1 || return 0
  case "$(cloud-init status 2>/dev/null)" in
    *running*) ;;
    *) return 0 ;;
  esac
  if [ "${AAP_SKIP_CLOUD_INIT_WAIT:-}" = "1" ]; then
    info "cloud-init (the provider's first-boot setup) is still running; AAP_SKIP_CLOUD_INIT_WAIT=1, so the installer does not wait for it."
    return 0
  fi
  if gpu_inside_cloud_init; then
    info "The installer runs inside cloud-init (the provider's first-boot setup), which cannot finish before the installer does, so it does not wait for it."
    return 0
  fi
  info "cloud-init (the provider's first-boot setup) is still running. It may install a GPU driver, so the installer waits for it (up to $((limit / 60)) minutes)..."
  if command -v timeout >/dev/null 2>&1; then
    timeout "$limit" cloud-init status --wait >/dev/null 2>&1 ||
      warn "cloud-init has not finished. Checking the GPU driver anyway."
  else
    cloud-init status --wait >/dev/null 2>&1 || true
  fi
  return 0
}

# gpu_probe_driver_version → the loaded NVIDIA driver version, "unknown" when a
# driver is loaded but its version cannot be read, or nothing.
gpu_probe_driver_version() {
  local out proc="${GPU_PROC_NVIDIA_VERSION:-/proc/driver/nvidia/version}"
  if command -v nvidia-smi >/dev/null 2>&1; then
    out="$(nvidia-smi --query-gpu=driver_version --format=csv,noheader 2>/dev/null | head -n 1 | tr -d '[:space:]')"
    if [ -n "$out" ] && gpu_driver_major "$out" >/dev/null; then
      echo "$out"
      return 0
    fi
  fi
  if [ -r "$proc" ]; then
    gpu_nvidia_version_from_proc "$(cat "$proc")" || echo "unknown"
    return 0
  fi
  return 0
}

# gpu_probe_driver_installed → yes when NVIDIA driver packages (or a .run
# installer) are on disk. Only meaningful when no driver is loaded.
gpu_probe_driver_installed() {
  if [ -e "${GPU_NVIDIA_UNINSTALL:-/usr/bin/nvidia-uninstall}" ]; then
    echo yes
    return 0
  fi
  if command -v rpm >/dev/null 2>&1 &&
    rpm -qa 2>/dev/null | grep -qE '^(kmod-nvidia|nvidia-driver|nvidia-open|nvidia-kmod|cuda-drivers)'; then
    echo yes
    return 0
  fi
  if command -v dpkg-query >/dev/null 2>&1 &&
    dpkg-query -W -f '${db:Status-Abbrev} ${Package}\n' 2>/dev/null |
    grep -qE '^ii +(nvidia-driver|nvidia-dkms|nvidia-kernel|nvidia-headless|nvidia-open|libnvidia-compute|linux-modules-nvidia|cuda-drivers)'; then
    echo yes
    return 0
  fi
  echo no
}

# gpu_probe_secure_boot → on|off|unknown. mokutil first; then the SecureBoot
# EFI variable (its last byte is 1 when on); no EFI at all means legacy BIOS.
gpu_probe_secure_boot() {
  local efi="${GPU_EFIVARS_DIR:-/sys/firmware/efi/efivars}" f byte out state
  if command -v mokutil >/dev/null 2>&1; then
    out="$(mokutil --sb-state 2>&1)" || true
    state="$(gpu_sb_state_from_mokutil "$out")"
    if [ "$state" != "unknown" ]; then
      echo "$state"
      return 0
    fi
  fi
  if [ ! -d "${efi%/efivars}" ] && [ ! -d "$efi" ]; then
    echo "off"
    return 0
  fi
  for f in "$efi"/SecureBoot-*; do
    [ -r "$f" ] || continue
    byte="$(od -An -t u1 "$f" 2>/dev/null | awk '{print $NF}' | tail -n 1)"
    if [ "$byte" = "1" ]; then echo "on"; else echo "off"; fi
    return 0
  done
  echo "unknown"
}

# ── operator output ───────────────────────────────────────────────────────────
# Plain-English lines, kept in one place so the docs page can quote them.

# gpu_driver_report <plan> — prints what was found and what the plan is. Reads
# the GPU_* globals gpu_probe filled.
gpu_driver_report() {
  local plan="$1" action arch_txt sb_txt nv_txt
  action="$(gpu_plan_get "$plan" action)"
  case "$action" in
    none)
      info "No NVIDIA GPU on this server. Nothing to do for the GPU driver."
      return 0
      ;;
    amd-later)
      info "Found: AMD GPU. The installer does not install AMD drivers yet; it leaves this card alone."
      return 0
      ;;
  esac
  case "$GPU_ARCH" in
    turing+) arch_txt="Turing or newer" ;;
    pre-turing) arch_txt="older than Turing: Maxwell, Pascal or Volta" ;;
    *) arch_txt="model not recognised" ;;
  esac
  if [ -n "$GPU_DRIVER_VERSION" ]; then
    info "Found: NVIDIA GPU (${arch_txt}, PCI 10de:${GPU_DEVICE_ID:-?}) with driver ${GPU_DRIVER_VERSION} loaded."
  else
    info "Found: NVIDIA GPU (${arch_txt}, PCI 10de:${GPU_DEVICE_ID:-?}). No driver is loaded."
  fi
  case "$GPU_SECURE_BOOT" in
    on | off) sb_txt="$GPU_SECURE_BOOT" ;;
    *) sb_txt="could not be read" ;;
  esac
  nv_txt="not loaded"
  [ "$GPU_NOUVEAU" = "yes" ] && nv_txt="loaded"
  info "Secure Boot: ${sb_txt}. nouveau (the built-in display driver): ${nv_txt}."
  case "$action" in
    leave)
      if [ "${GPU_CLOUD:-none}" = "vgpu" ]; then
        info "This is a virtual GPU (vGPU/GRID) with the provider's licensed driver. The provider manages that driver; the installer leaves it alone."
      fi
      if gpu_plan_has "$plan" "warn=driver-below-floor"; then
        warn "Driver ${GPU_DRIVER_VERSION} is already loaded, so the installer leaves it alone. Note: the vLLM app needs driver ${GPU_DRIVER_FLOOR} or newer (CUDA 13); Ollama works from 550. Update the driver when convenient."
      else
        info "Plan: leave the loaded driver alone."
      fi
      ;;
    reboot-pending)
      warn "NVIDIA driver packages are installed but the driver is not loaded. This usually means the server has not been restarted since they were installed. Plan: restart the server (sudo reboot), then run the installer again."
      ;;
    manual)
      case "$(gpu_plan_get "$plan" reason)" in
        arm-not-automated)
          warn "This is an ARM (aarch64) server. The installer does not install NVIDIA drivers on ARM yet. Install the driver from NVIDIA's 'sbsa' repository: ${GPU_DRIVER_DOC_URL}"
          ;;
        cloud-vgpu)
          warn "This is a virtual GPU (vGPU/GRID). It needs the provider's licensed guest driver, so the installer does not install one. Use the provider's GPU image or its driver instructions, then run the installer again."
          ;;
        cloud-vultr)
          warn "This is a Vultr Cloud GPU. Vultr installs its licensed GPU driver itself (cloud-init, at first boot), so the installer does not install one. Wait for that setup to finish or use a Vultr GPU image, then run the installer again."
          ;;
        cloud-aws-grid)
          warn "This AWS instance type (g6f/gr6f, a fractional GPU) runs only AWS's GRID driver, which AWS licenses to its customers. The installer does not install it. Use an AWS image with the GRID driver or follow AWS's GRID driver page, then run the installer again."
          ;;
        no-legacy-branch)
          warn "This card is older than Turing and needs driver branch 580, but NVIDIA's Debian 13 repository has no 580 branch (it starts at 590, which dropped these cards) and Debian's own driver is 550. The installer does not install a driver here. Options: Debian 12 or Ubuntu, or install Debian's nvidia-driver yourself (Ollama only; the vLLM app needs 580)."
          ;;
        *)
          warn "The GPU model could not be read from the PCI bus, so the installer cannot pick a driver for it. Install the NVIDIA driver yourself: ${GPU_DRIVER_DOC_URL}"
          ;;
      esac
      ;;
    install)
      if [ "$(gpu_plan_get "$plan" flavour)" = "open" ]; then
        info "Plan: install NVIDIA driver $(gpu_plan_get "$plan" branch) (long-term branch, open kernel modules, compute-only: no desktop packages)."
      else
        info "Plan: install NVIDIA driver $(gpu_plan_get "$plan" branch) (the last branch for this card, proprietary kernel modules, compute-only: no desktop packages)."
        warn "This card is older than Turing. Ollama runs on it, but the vLLM app's default image (CUDA 13) does not support it."
      fi
      if gpu_plan_has "$plan" "reboot=yes"; then
        info "nouveau is loaded, so a restart will be needed after the driver is installed."
      fi
      if gpu_plan_has "$plan" "secureboot_stop=yes"; then
        warn "Secure Boot is on. A driver built on this server must be trusted by the firmware once (MOK enrolment at the server console) before it can load."
      elif [ "${OS_ID:-}" = "ubuntu" ] && [ "$GPU_SECURE_BOOT" = "on" ]; then
        info "Secure Boot is on. Ubuntu's prebuilt driver modules are signed by Canonical, so no key enrolment is needed."
      fi
      if gpu_plan_has "$plan" "fabric_manager=yes"; then
        info "NVSwitch found (HGX board): CUDA only starts there with NVIDIA Fabric Manager. The installer also installs it, at the driver's version, and turns its service on."
        if gpu_plan_has "$plan" "nvlsm=yes"; then
          info "This board has fourth-generation NVSwitches (HGX B100/B200/B300): it also needs the NVLink Subnet Manager (nvlsm), which Fabric Manager starts."
        fi
      fi
      ;;
  esac
  return 0
}

# gpu_driver_step — the installer step. Returns 0 to continue, 1 to fail the
# install, 20 (reboot required) or 21 (Secure Boot enrolment).
#   auto     install where this version can (EL 9/10, Ubuntu 22.04/24.04,
#            Debian 12/13; x86_64); elsewhere report and continue CPU-only.
#   install  the same, but a host where the driver cannot be installed fails
#            the install (for automation that needs the GPU). It still never
#            replaces a loaded driver.
#   skip     no check at all.
gpu_driver_step() {
  local mode="${AAP_GPU_DRIVER:-auto}" plan action rc
  if [ "$mode" = "skip" ]; then
    info "GPU driver check skipped (--gpu-driver=skip). The installer leaves the GPU driver to you."
    return 0
  fi
  if [ "${DRY_RUN:-false}" != "true" ]; then gpu_wait_cloud_init; fi
  gpu_probe
  plan="$(gpu_driver_plan "$GPU_VENDOR" "$GPU_ARCH" "$GPU_DRIVER_VERSION" "$GPU_DRIVER_INSTALLED" \
    "$GPU_NOUVEAU" "$GPU_SECURE_BOOT" "$GPU_NVSWITCH" "$GPU_MACHINE" "$GPU_CLOUD")"
  plan="$(gpu_plan_for_os "$plan" "${OS_ID:-}" "${OS_VERSION_MAJOR:-}")"
  gpu_driver_report "$plan"
  action="$(gpu_plan_get "$plan" action)"
  case "$action" in
    none | amd-later) return 0 ;;
    leave)
      # A working driver is never touched, but an HGX board without Fabric
      # Manager has no CUDA (common on rented HGX servers).
      gpu_plan_has "$plan" "fabric_manager=yes" || return 0
      gpu_fm_existing "$plan" "$mode"
      return
      ;;
  esac
  # A driver that is installed but not loaded needs only a restart, whatever the
  # OS: install mode stops for it everywhere, auto only where we install.
  if [ "$action" = "reboot-pending" ] && [ "$mode" = "install" ]; then
    gpu_stop_reboot_required
    _gpu_stop "$GPU_EXIT_REBOOT_REQUIRED"
    return
  fi
  if [ "$action" = "manual" ] || ! gpu_install_supported "${OS_ID:-}" "${OS_VERSION_MAJOR:-}" "$GPU_MACHINE"; then
    _gpu_cannot_install "$mode" "$action"
    return
  fi
  if [ "$action" = "reboot-pending" ]; then
    gpu_stop_reboot_required
    _gpu_stop "$GPU_EXIT_REBOOT_REQUIRED"
    return
  fi
  rc=0
  case "${OS_ID:-}" in
    ubuntu) gpu_ubuntu_install "$plan" || rc=$? ;;
    debian) gpu_debian_install "$plan" || rc=$? ;;
    *) gpu_el_install "$plan" || rc=$? ;;
  esac
  if [ "$rc" -eq 1 ]; then
    if [ "$mode" = "install" ]; then
      error_gpu "The NVIDIA driver install failed (--gpu-driver=install). See the step above and ${INSTALL_LOG:-the install log}."
      return 1
    fi
    warn "The NVIDIA driver install failed. Continuing without a GPU driver; the panel runs, AI apps use the CPU. See the step above and ${INSTALL_LOG:-the install log}."
    return 0
  fi
  return "$rc"
}

# _gpu_cannot_install <mode> <action> — this host needs a driver the installer
# cannot install. auto: say so and continue as before; install: fail.
_gpu_cannot_install() {
  if [ "$1" = "install" ]; then
    error_gpu "--gpu-driver=install: this installer cannot install the NVIDIA driver on ${OS_PRETTY:-this OS} (${GPU_MACHINE}) yet. Install it yourself (${GPU_DRIVER_DOC_URL}), or run with --gpu-driver=auto to continue without it."
    return 1
  fi
  if [ "$2" = "reboot-pending" ]; then
    info "Continuing without the GPU for now. Restart the server and run the installer again to use it."
  elif [ "$2" = "manual" ]; then
    info "Continuing without a GPU driver: the panel runs, AI apps use the CPU. Once a driver is loaded, run the installer again to use the GPU."
  else
    info "This installer installs the NVIDIA driver on Ubuntu 22.04 and 24.04, Debian 12 and 13, and Rocky Linux, AlmaLinux, CentOS Stream and RHEL 9 and 10 (x86_64). Continuing without a GPU driver: the panel runs, AI apps use the CPU. Install the driver yourself (${GPU_DRIVER_DOC_URL}), then run the installer again."
  fi
  return 0
}

# gpu_install_supported <os_id> <major> <machine> → 0 when this version
# installs the driver on that host: EL 9/10, Ubuntu 22.04/24.04 (LTS), Debian
# 12/13; x86_64 only (aarch64 uses NVIDIA's separate sbsa repository).
gpu_install_supported() {
  case "$1:$2" in
    ubuntu:22 | ubuntu:24 | debian:12 | debian:13) ;;
    *)
      gpu_el_supported "$@"
      return
      ;;
  esac
  case "$3" in
    x86_64 | amd64) return 0 ;;
    *) return 1 ;;
  esac
}

# error_gpu <msg> — prints a failure without exiting (the caller returns 1 and
# install.sh exits). log.sh's error() exits, which would skip that contract.
error_gpu() {
  printf '[ERROR] %s\n' "$*" >&2
}

# ── NVIDIA driver install: Rocky / AlmaLinux / CentOS Stream / RHEL 9 and 10 ─
# (AI-2330 unit 2; design §2.1, §2.2, §3.) Only these hosts install a driver in
# this version. Every other OS keeps the unit-1 behaviour: report and continue.

GPU_NVIDIA_REPO_BASE="https://developer.download.nvidia.com/compute/cuda/repos"
GPU_VERSIONLOCK_LIST="${GPU_VERSIONLOCK_LIST:-/etc/dnf/plugins/versionlock.list}"
GPU_NOUVEAU_BLACKLIST="${GPU_NOUVEAU_BLACKLIST:-/etc/modprobe.d/aap-blacklist-nouveau.conf}"
GPU_DKMS_MOK_PUB="${GPU_DKMS_MOK_PUB:-/var/lib/dkms/mok.pub}"

# gpu_el_supported <os_id> <major> <machine> → 0 when this version installs the
# driver on that host: the EL family the installer certifies, x86_64 only
# (aarch64 uses NVIDIA's separate sbsa repository, not done yet).
gpu_el_supported() {
  case "$1" in
    rocky | almalinux | centos | rhel) ;;
    *) return 1 ;;
  esac
  case "$2" in
    9 | 10) ;;
    *) return 1 ;;
  esac
  case "$3" in
    x86_64 | amd64) return 0 ;;
    *) return 1 ;;
  esac
}

# gpu_el_install_commands <os_id> <major> <flavour> <branch> <kernel> → the
# install commands, one per line, in order. Pure, so bats and --dry-run show
# exactly what a real run executes. Lines are run with eval; the gpu_el_*
# entries are functions in this module.
#   * CRB + EPEL: dkms lives in EPEL, and EPEL needs CRB. RHEL proper has no
#     epel-release package and calls CRB "codeready-builder".
#   * kernel-devel/headers for the RUNNING kernel, so DKMS can build now.
#   * NVIDIA's CUDA repository for rhel<major>.
#   * Branch pin before the install, so dnf cannot pick a newer branch: EL9 by
#     module stream, EL10 (no module streams) by versionlock entries.
#   * Compute-only packages: nvidia-driver-cuda without the desktop stack that
#     the nvidia-open meta package pulls in (the 2026-11-13 Rocky 10 finding).
gpu_el_install_commands() {
  local os_id="$1" major="$2" flavour="$3" branch="$4" kernel="$5" kmod
  if [ "$flavour" = "open" ]; then kmod="kmod-nvidia-open-dkms"; else kmod="kmod-nvidia-latest-dkms"; fi
  echo "dnf install -y dnf-plugins-core"
  if [ "$os_id" = "rhel" ]; then
    echo "subscription-manager repos --enable codeready-builder-for-rhel-${major}-x86_64-rpms"
    echo "dnf install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-${major}.noarch.rpm"
  else
    echo "dnf config-manager --set-enabled crb"
    echo "dnf install -y epel-release"
  fi
  echo "dnf install -y kernel-devel-${kernel} kernel-headers-${kernel} dkms"
  echo "dnf config-manager --add-repo ${GPU_NVIDIA_REPO_BASE}/rhel${major}/x86_64/cuda-rhel${major}.repo"
  echo "dnf clean expire-cache"
  if [ "$major" = "9" ]; then
    if [ "$flavour" = "open" ]; then
      echo "dnf module enable -y nvidia-driver:${branch}-open"
    else
      echo "dnf module enable -y nvidia-driver:${branch}-dkms"
    fi
  else
    echo "dnf install -y python3-dnf-plugin-versionlock"
    echo "gpu_el_write_versionlock ${branch}"
  fi
  echo "dnf install -y nvidia-driver-cuda ${kmod}"
}

# gpu_el_versionlock_entries <branch> → the branch-wide lock lines NVIDIA's
# guide gives for DNF 4 (EL10). Branch globs, not one version, so security
# updates inside the branch keep flowing.
gpu_el_versionlock_entries() {
  local b="$1" p
  for p in 'kmod-nvidia*' 'libnvidia*' 'nvidia-driver*' 'nvidia-kmod-common-' 'nvidia-libXNVCtrl*' \
    'nvidia-modprobe-' 'nvidia-open-' 'nvidia-persistenced-' 'nvidia-settings-' 'nvidia-xconfig-' 'xorg-x11-nvidia-'; do
    printf '%s3:%s*\n' "$p" "$b"
  done
}

# gpu_el_write_versionlock <branch> — appends the entries that are not there yet.
gpu_el_write_versionlock() {
  local line
  mkdir -p "$(dirname "$GPU_VERSIONLOCK_LIST")" || return 1
  touch "$GPU_VERSIONLOCK_LIST" || return 1
  while read -r line; do
    grep -qxF -- "$line" "$GPU_VERSIONLOCK_LIST" || printf '%s\n' "$line" >>"$GPU_VERSIONLOCK_LIST" || return 1
  done <<EOF
$(gpu_el_versionlock_entries "$1")
EOF
}

# gpu_rerun_command — the command to run after the reboot: the same flags this
# run got (AAP_INSTALL_ARGS, set by install.sh). Flags carry no secrets; the
# operator's environment variables are named in the text, never printed.
gpu_rerun_command() {
  local args="" a
  for a in "${AAP_INSTALL_ARGS[@]+"${AAP_INSTALL_ARGS[@]}"}"; do
    args="${args} $(printf '%q' "$a")"
  done
  echo "curl -fsSL https://get.aiadminpanel.com | sudo bash -s --${args}"
}

# gpu_stop_reboot_required — the exit-20 text (design §6.2).
gpu_stop_reboot_required() {
  warn "REBOOT REQUIRED. The NVIDIA driver is installed and loads after a restart. Nothing else has been changed yet."
  warn "  Run:   sudo reboot"
  warn "  Then:  $(gpu_rerun_command)"
  warn "  (or 'sudo bash install.sh' with the same options, and the same environment variables such as PANEL_DOMAIN if you set any). The installer picks up where it left off."
}

# gpu_stop_secure_boot [key] — the exit-21 text (design §3.3). <key> is the
# DKMS signing certificate (default GPU_DKMS_MOK_PUB; Ubuntu has its own).
gpu_stop_secure_boot() {
  local key="${1:-$GPU_DKMS_MOK_PUB}"
  warn "Secure Boot is on. The NVIDIA kernel module was built on this server and must be trusted by the firmware before it can load. This needs someone at the server console once:"
  warn "  1. sudo mokutil --import ${key}      (choose a one-time password)"
  warn "  2. sudo reboot"
  warn "  3. At the blue \"MOK management\" screen: Enroll MOK, Continue, Yes, then type the password"
  warn "     (cloud servers: use the provider's web or serial console; this screen shows before Linux boots)"
  warn "  4. After boot, run the installer again: $(gpu_rerun_command)"
  warn "  Alternative: turn Secure Boot off in the firmware or provider settings, then run the installer again."
}

# gpu_mok_enrolled → 0 when the DKMS signing key is already enrolled, so a
# Secure Boot host can load the new module without a console visit.
gpu_mok_enrolled() {
  local key="${1:-$GPU_DKMS_MOK_PUB}"
  [ -r "$key" ] || return 1
  command -v mokutil >/dev/null 2>&1 || return 1
  mokutil --test-key "$key" 2>&1 | grep -qi "already enrolled"
}

# gpu_blacklist_nouveau [initramfs command...] — keeps nouveau from loading at
# the next boot. NVIDIA's packages ship a blacklist too; ours makes it
# independent of package layout. The initramfs is rebuilt (dracut on EL,
# update-initramfs -u on Ubuntu/Debian), which otherwise still loads nouveau.
gpu_blacklist_nouveau() {
  printf '%s\n' "# Written by the AI Admin Panel installer (AI-2330): the NVIDIA driver replaces nouveau." \
    "blacklist nouveau" "options nouveau modeset=0" >"$GPU_NOUVEAU_BLACKLIST" || return 1
  if [ "$#" -eq 0 ]; then
    dracut --force
  else
    "$@"
  fi
}

# _gpu_exec <line> — runs one install line, or narrates it under --dry-run.
_gpu_exec() {
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] $1"
    return 0
  fi
  info "Running: $1"
  eval "$1"
}

# _gpu_stop <code> — the stop at the end of the step. A dry run only says so.
_gpu_stop() {
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] the installer would stop here with exit code $1."
    return 0
  fi
  return "$1"
}

# gpu_el_install <plan> — installs the planned driver on an EL host, then
# decides whether the run can continue. Returns 0 (continue), 1 (a command
# failed), 20 (reboot required) or 21 (Secure Boot enrolment needed).
gpu_el_install() {
  local plan="$1" kernel
  kernel="${GPU_KERNEL_OVERRIDE:-$(uname -r)}"
  info "Installing the NVIDIA driver from NVIDIA's repository for ${OS_PRETTY:-${OS_ID} ${OS_VERSION_MAJOR}} (log: ${INSTALL_LOG:-the install log})..."
  _gpu_run_lines "$(gpu_el_install_commands "$OS_ID" "$OS_VERSION_MAJOR" "$(gpu_plan_get "$plan" flavour)" "$(gpu_plan_get "$plan" branch)" "$kernel")" || return 1
  _gpu_fm_after_install "$plan" el || return 1
  _gpu_finish "$plan" "$(gpu_plan_get "$plan" secureboot_stop)" "$GPU_DKMS_MOK_PUB"
}

# _gpu_run_lines <lines> — runs install lines in order (one per line); stops at
# the first failure and names it. Returns 0 or 1.
_gpu_run_lines() {
  local line
  while read -r line; do
    [ -n "$line" ] || continue
    _gpu_exec "$line" || {
      warn "This step failed: ${line}"
      return 1
    }
  done <<EOF
$1
EOF
}

# _gpu_finish <plan> <secure-boot-applies yes|no> <mok key> [initramfs cmd...]
# — after the packages are in: block nouveau when it is loaded, stop for a
# Secure Boot enrolment (21) or a restart (20), or load the module now and
# continue. Shared by every OS; the initramfs command is dracut by default.
_gpu_finish() {
  local plan="$1" sb="$2" key="$3"
  shift 3
  if gpu_plan_has "$plan" "reboot=yes"; then
    _gpu_exec "gpu_blacklist_nouveau${*:+ $*}" || {
      warn "Could not block nouveau for the next boot (${GPU_NOUVEAU_BLACKLIST}, ${*:-dracut})."
      return 1
    }
  fi
  if [ "$sb" = "yes" ] && ! gpu_mok_enrolled "$key"; then
    gpu_stop_secure_boot "$key"
    _gpu_stop "$GPU_EXIT_SECURE_BOOT"
    return
  fi
  if gpu_plan_has "$plan" "reboot=yes"; then
    gpu_stop_reboot_required
    _gpu_stop "$GPU_EXIT_REBOOT_REQUIRED"
    return
  fi
  # No nouveau in the way (typical for datacenter cards on a fresh image): try
  # to load the module now and carry on in the same run.
  if [ "${DRY_RUN:-false}" = "true" ]; then
    info "[dry] modprobe nvidia && nvidia-smi   (on success the install continues; otherwise it stops with exit code ${GPU_EXIT_REBOOT_REQUIRED})"
    if gpu_plan_has "$plan" "fabric_manager=yes"; then
      info "[dry] systemctl start ${GPU_FM_SERVICE}   (once the driver is loaded)"
    fi
    return 0
  fi
  if modprobe nvidia && nvidia-smi >/dev/null 2>&1; then
    info "NVIDIA driver loaded without a restart. Continuing."
    # Fabric Manager needs the loaded driver; it was only enabled so far.
    if gpu_plan_has "$plan" "fabric_manager=yes" && ! systemctl start "$GPU_FM_SERVICE"; then
      warn "Fabric Manager did not start (${GPU_FM_SERVICE}). CUDA on this HGX board will not work until it runs: sudo journalctl -u ${GPU_FM_SERVICE}"
    fi
    return 0
  fi
  gpu_stop_reboot_required
  return "$GPU_EXIT_REBOOT_REQUIRED"
}

# ── NVIDIA driver install: Ubuntu 22.04/24.04 and Debian 12/13 ────────────────
# (AI-2330 unit 3; design §2.3, §2.4.) Package names checked 2026-11-14 against
# packages.ubuntu.com and NVIDIA's repository indexes; see the design note.

GPU_UBUNTU_MOK_DER="${GPU_UBUNTU_MOK_DER:-/var/lib/shim-signed/mok/MOK.der}"
GPU_APT_SOURCES_DIR="${GPU_APT_SOURCES_DIR:-/etc/apt}"
GPU_DEB_CONTRIB_LIST="${GPU_DEB_CONTRIB_LIST:-/etc/apt/sources.list.d/aap-debian-contrib.list}"

# gpu_kernel_flavour <uname -r> → the kernel flavour that names the meta
# packages: "6.8.0-149-generic" → generic, "6.8.0-1030-aws" → aws,
# "6.1.0-27-cloud-amd64" → cloud-amd64, "6.12.38+deb13-amd64" → amd64.
# Returns 1 when there is none.
gpu_kernel_flavour() {
  local f
  f="$(printf '%s\n' "$1" | sed -E 's/^[0-9]+\.[0-9]+(\.[0-9]+)?(-[0-9]+)?(\+[^-]*)?-//')"
  case "$f" in
    "$1" | '' | *[!a-z0-9.-]* | [!a-z]*) return 1 ;;
  esac
  echo "$f"
}

# gpu_debian_codename <major> → bookworm | trixie (the releases installed here).
gpu_debian_codename() {
  case "$1" in
    12) echo "bookworm" ;;
    13) echo "trixie" ;;
    *) return 1 ;;
  esac
}

# gpu_ubuntu_kernel_meta <uname -r> <VERSION_ID> → the flavour whose
# linux-modules-nvidia-* meta package follows this kernel through updates. A
# generic kernel from the HWE stack (22.04 running 6.8, say) follows
# generic-hwe-<VERSION_ID>; the archive has both names.
gpu_ubuntu_kernel_meta() {
  local f
  f="$(gpu_kernel_flavour "$1")" || return 1
  if [ "$f" = "generic" ] && [ -n "$2" ] && command -v dpkg-query >/dev/null 2>&1 &&
    dpkg-query -W -f '${db:Status-Abbrev} ${Package}\n' "linux-image-generic-hwe-$2" "linux-generic-hwe-$2" 2>/dev/null |
    grep -qE "^ii +linux-(image-)?generic-hwe-$2\$"; then
    f="generic-hwe-$2"
  fi
  echo "$f"
}

# gpu_ubuntu_install_commands <flavour> <branch> <kernel> <meta> <signed> →
# the apt command for Ubuntu's own -server driver, headless (no X/desktop).
#   signed=yes  Canonical's prebuilt, signed modules (Ubuntu's recommended
#               path; they load under Secure Boot): the package for the running
#               kernel plus the flavour meta, so every kernel update brings the
#               matching module, then the headless no-DKMS userspace.
#   signed=no   no prebuilt module for this kernel (custom kernel): Ubuntu's
#               DKMS package builds it here, so Secure Boot needs a MOK.
# No apt-mark hold: the branch is in every package name, so apt never moves
# to another branch, and each linux-modules-nvidia package depends on the exact
# userspace version (nvidia-kernel-common-<branch>-server (= x)). Holding the
# userspace would hold back the module for the next kernel and leave the GPU
# without a driver after that kernel's reboot.
gpu_ubuntu_install_commands() {
  local flavour="$1" b="$2" kernel="$3" meta="$4" signed="$5" o=""
  [ "$flavour" = "open" ] && o="-open"
  if [ "$signed" = "yes" ]; then
    echo "DEBIAN_FRONTEND=noninteractive apt-get install -y linux-modules-nvidia-${b}-server${o}-${kernel} linux-modules-nvidia-${b}-server${o}-${meta} nvidia-headless-no-dkms-${b}-server${o} nvidia-utils-${b}-server"
  else
    echo "DEBIAN_FRONTEND=noninteractive apt-get install -y linux-headers-${kernel} nvidia-dkms-${b}-server${o} nvidia-headless-${b}-server${o} nvidia-utils-${b}-server"
  fi
}

# gpu_ubuntu_install <plan> — installs the planned driver on Ubuntu 22.04/24.04.
# Returns 0 (continue), 1 (a command failed), 20 or 21 (see _gpu_finish).
gpu_ubuntu_install() {
  local plan="$1" kernel flavour branch meta="" o="" signed=no sb=no
  kernel="${GPU_KERNEL_OVERRIDE:-$(uname -r)}"
  flavour="$(gpu_plan_get "$plan" flavour)"
  branch="$(gpu_plan_get "$plan" branch)"
  [ "$flavour" = "open" ] && o="-open"
  info "Installing the NVIDIA ${branch}-server driver from Ubuntu's archive (log: ${INSTALL_LOG:-the install log})..."
  _gpu_run_lines "apt-get update" || return 1
  if meta="$(gpu_ubuntu_kernel_meta "$kernel" "${OS_VERSION_ID:-}")" &&
    apt-cache show "linux-modules-nvidia-${branch}-server${o}-${kernel}" >/dev/null 2>&1 &&
    apt-cache show "linux-modules-nvidia-${branch}-server${o}-${meta}" >/dev/null 2>&1; then
    signed=yes
    info "Using Canonical's prebuilt, signed driver modules for kernel ${kernel}."
  else
    warn "Ubuntu has no prebuilt NVIDIA module for kernel ${kernel} (a custom kernel?). The module will be built on this server (DKMS) instead."
    if [ "$GPU_SECURE_BOOT" = "on" ]; then sb=yes; fi
  fi
  _gpu_run_lines "$(gpu_ubuntu_install_commands "$flavour" "$branch" "$kernel" "$meta" "$signed")" || return 1
  _gpu_fm_after_install "$plan" ubuntu-archive || return 1
  _gpu_finish "$plan" "$sb" "$GPU_UBUNTU_MOK_DER" update-initramfs -u
}

# gpu_debian_install_commands <major> <flavour> <branch> <kernel> <kflavour>
# → the install commands for Debian 12/13, one per line. Debian's own
# non-free driver is below the floor (bookworm 535, trixie 550), so this is
# NVIDIA's CUDA repository, as in NVIDIA's guide:
#   * headers for the running kernel plus the flavour meta
#     (linux-headers-amd64), so DKMS rebuilds the module on kernel updates;
#   * contrib enabled (NVIDIA's prerequisite);
#   * NVIDIA's cuda-keyring for debian<major>;
#   * the branch pinning package BEFORE the driver ("for the best experience
#     when locking a branch"). It is NVIDIA's apt pin, and Debian's
#     unattended-upgrades only takes Debian-Security by default, so the driver
#     never moves to another branch on its own;
#   * compute-only: nvidia-driver-cuda (NVIDIA's headless set) plus
#     nvidia-smi, which it does not pull in, and the open or proprietary
#     DKMS module.
gpu_debian_install_commands() {
  local major="$1" flavour="$2" branch="$3" kernel="$4" kfl="$5" codename kmod="nvidia-kernel-dkms"
  codename="$(gpu_debian_codename "$major")" || return 1
  [ "$flavour" = "open" ] && kmod="nvidia-kernel-open-dkms"
  echo "apt-get update"
  echo "DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates curl linux-headers-${kernel}${kfl:+ linux-headers-${kfl}}"
  echo "gpu_deb_enable_contrib ${codename}"
  echo "gpu_deb_install_keyring debian${major}"
  echo "apt-get update"
  echo "DEBIAN_FRONTEND=noninteractive apt-get install -y nvidia-driver-pinning-${branch}"
  echo "DEBIAN_FRONTEND=noninteractive apt-get install -y -V nvidia-driver-cuda nvidia-smi ${kmod}"
}

# gpu_deb_enable_contrib <codename> — adds Debian's contrib component in a file
# of our own, unless an existing source already has it. The operator's own
# source files are never edited.
gpu_deb_enable_contrib() {
  local d="$GPU_APT_SOURCES_DIR" f
  for f in "$d/sources.list" "$d"/sources.list.d/*.list "$d"/sources.list.d/*.sources; do
    [ -r "$f" ] || continue
    if grep -Eqs '^[[:space:]]*deb[[:space:]].*[[:space:]]contrib([[:space:]]|$)|^Components:.*[[:space:]]contrib([[:space:]]|$)' "$f"; then
      return 0
    fi
  done
  mkdir -p "$(dirname "$GPU_DEB_CONTRIB_LIST")" || return 1
  printf '%s\n' "# Written by the AI Admin Panel installer (AI-2330): NVIDIA's driver guide needs contrib." \
    "deb http://deb.debian.org/debian $1 contrib" >"$GPU_DEB_CONTRIB_LIST"
}

# gpu_deb_install_keyring <debian12|debian13> — installs NVIDIA's cuda-keyring
# package, which adds the repository and its signing key.
gpu_deb_install_keyring() {
  local tmp rc=0 deb="cuda-keyring_1.1-1_all.deb"
  tmp="$(mktemp -d)" || return 1
  if ! curl --proto '=https' --tlsv1.2 -fsSL -o "$tmp/$deb" "${GPU_NVIDIA_REPO_BASE}/$1/x86_64/$deb" ||
    ! dpkg -i "$tmp/$deb"; then
    rc=1
  fi
  rm -rf "$tmp"
  return "$rc"
}

# gpu_debian_install <plan> — installs the planned driver on Debian 12/13.
# Returns 0 (continue), 1 (a command failed), 20 or 21 (see _gpu_finish).
gpu_debian_install() {
  local plan="$1" kernel kfl
  kernel="${GPU_KERNEL_OVERRIDE:-$(uname -r)}"
  kfl="$(gpu_kernel_flavour "$kernel" || true)"
  info "Installing the NVIDIA driver from NVIDIA's repository for ${OS_PRETTY:-Debian ${OS_VERSION_MAJOR}} (log: ${INSTALL_LOG:-the install log})..."
  _gpu_run_lines "$(gpu_debian_install_commands "$OS_VERSION_MAJOR" "$(gpu_plan_get "$plan" flavour)" "$(gpu_plan_get "$plan" branch)" "$kernel" "$kfl")" || return 1
  _gpu_fm_after_install "$plan" nvidia-apt || return 1
  _gpu_finish "$plan" "$(gpu_plan_get "$plan" secureboot_stop)" "$GPU_DKMS_MOK_PUB" update-initramfs -u
}

# ── NVIDIA Fabric Manager on NVSwitch (HGX) boards ────────────────────────────
# (AI-2320; design §10.) On an HGX board (8x A100/H100/H200/B200 SXM) the GPUs
# talk through NVSwitch chips, and CUDA does not start until Fabric Manager has
# set up that fabric ("system not yet initialized"). Package names and version
# rules were checked on 2026-11-14 against NVIDIA's guides and repository
# indexes and Ubuntu's archive; see the design note.
#   * Branches below 620: Fabric Manager must be the driver's exact version.
#   * From 620, Fabric Manager is a standalone 2.x package ("-direct") that
#     the driver's libnvidia-fmdrv library pairs with; NSCQ/NVSDM keep the
#     driver's version. On EL10 the bare name nvidia-fabricmanager is the old
#     615 package, so the -direct name is used.
#   * Fourth-generation NVSwitch boards (HGX B100/B200/B300) also need the
#     NVLink Subnet Manager (nvlsm); Fabric Manager's service starts it.
#   * From 620 the service is not enabled by the package, so the installer
#     enables it. IMEX is left out: it is for multi-node NVLink, not one HGX.

GPU_FM_SERVICE=nvidia-fabricmanager.service
GPU_FM_DOC_URL="https://docs.nvidia.com/datacenter/tesla/fabric-manager-user-guide/"

# gpu_nvswitch_gen4_device <pci-device-id> → 0 for the GPUs of HGX B100/B200/
# B300 boards, whose NVSwitches are not PCI devices on the host (FM user guide,
# "HGX B200/B300 GPU Baseboard"; IDs from the PCI ID database, 2026-11-14:
# 2901/2909/290a B200, 2920 and 29bc B100/B200, 3182 B300 SXM6). Grace systems
# (GB200/GB300) are aarch64, which the installer leaves to the operator.
gpu_nvswitch_gen4_device() {
  case "${1#0x}" in
    2901 | 2909 | 290a | 2920 | 29bc | 3182) return 0 ;;
    *) return 1 ;;
  esac
}

# gpu_fabric_state_from_smi <nvidia-smi -q output> → the first GPU's fabric
# "State" ("Completed", "In Progress", "Not Started", "N/A", ...), or nothing.
gpu_fabric_state_from_smi() {
  printf '%s\n' "$1" | awk '
    /^[[:space:]]*Fabric[[:space:]]*$/ { f = 1; next }
    f && /^[[:space:]]*State[[:space:]]*:/ {
      sub(/^[^:]*:[[:space:]]*/, ""); sub(/[[:space:]]+$/, ""); print; exit
    }'
}

# gpu_fabric_state_is_nvswitch <state> → 0 when the GPU is part of an NVSwitch
# fabric: any state but "N/A", "Not Supported" or none.
gpu_fabric_state_is_nvswitch() {
  case "$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" in
    '' | n/a | "not supported") return 1 ;;
    *) return 0 ;;
  esac
}

# gpu_fm_version_from_output <text> → the version in "nv-fabricmanager
# --version" output ("Fabric Manager version is : 580.95.05"). Returns 1 when
# there is none.
gpu_fm_version_from_output() {
  local w out=""
  for w in $1; do
    case "$w" in
      [0-9]*.[0-9]*) out="$w" ;;
    esac
  done
  [ -n "$out" ] || return 1
  echo "$out"
}

# gpu_probe_fm_version → the installed Fabric Manager version, or nothing.
gpu_probe_fm_version() {
  command -v nv-fabricmanager >/dev/null 2>&1 || return 0
  gpu_fm_version_from_output "$(nv-fabricmanager --version 2>&1)" || true
}

# gpu_fm_version_matches <driver> <fm> → 0 when this Fabric Manager works with
# this driver: the same version below branch 620, a standalone 2.x from 620.
gpu_fm_version_matches() {
  local dmaj fmaj
  dmaj="$(gpu_driver_major "$1")" || return 1
  fmaj="$(gpu_driver_major "$2")" || return 1
  if [ "$dmaj" -ge 620 ]; then
    [ "$fmaj" -lt 100 ]
  else
    [ "$1" = "$2" ]
  fi
}

# gpu_upstream_version <package version> → the version without epoch and
# packaging revision ("580.95.05-0ubuntu0.24.04.2" → 580.95.05).
gpu_upstream_version() {
  local v="${1#*:}"
  echo "${v%%-*}"
}

# gpu_fm_packages <family> <branch> <driver version> <nvlsm yes|no> → the
# package list, pinned to the driver version. Families:
#   el              NVIDIA's CUDA repository on EL 9/10 (dnf name-version).
#   nvidia-apt      NVIDIA's CUDA repository on Debian/Ubuntu ('name=version-*',
#                   apt's version prefix match; it fails when that exact
#                   version is missing instead of taking another).
#   ubuntu-archive  Ubuntu's own -server driver: nvidia-fabricmanager-<branch>,
#                   which depends on that exact driver version. Branch 580 and
#                   newer only (below, it is transitional to 580: returns 1).
#                   nvlsm is not in Ubuntu's archive (the caller says so).
gpu_fm_packages() {
  local fam="$1" b="$2" v="$3" l="$4" out
  case "$b" in '' | *[!0-9]*) return 1 ;; esac
  case "$fam" in
    el)
      if [ "$b" -ge 620 ]; then
        out="nvidia-fabricmanager-direct libnvidia-nscq-$v libnvsdm-$v"
      elif [ "$b" -ge 580 ]; then
        out="nvidia-fabricmanager-$v libnvidia-nscq-$v"
        [ "$l" = "yes" ] && out="$out libnvsdm-$v"
      else
        out="nvidia-fabric-manager-$v libnvidia-nscq-$b-$v"
        [ "$l" = "yes" ] && out="$out libnvsdm-$b-$v"
      fi
      ;;
    nvidia-apt)
      if [ "$b" -ge 620 ]; then
        out="'nvidia-fabricmanager=$b-*' 'libnvidia-nscq=$v-*' 'libnvsdm=$v-*'"
      elif [ "$b" -ge 580 ]; then
        out="'nvidia-fabricmanager=$v-*' 'libnvidia-nscq=$v-*'"
        [ "$l" = "yes" ] && out="$out 'libnvsdm=$v-*'"
      else
        out="'nvidia-fabricmanager-$b=$v-*' 'libnvidia-nscq-$b=$v-*'"
        [ "$l" = "yes" ] && out="$out 'libnvsdm-$b=$v-*'"
      fi
      ;;
    ubuntu-archive)
      # Below 580 the archive's nvidia-fabricmanager-<branch> is only a
      # transitional package to the 580 one, which would not match the driver.
      [ "$b" -ge 580 ] || return 1
      echo "'nvidia-fabricmanager-$b=$v-*' 'libnvidia-nscq-$b=$v-*'"
      return 0
      ;;
    *) return 1 ;;
  esac
  [ "$l" = "yes" ] && out="$out nvlsm"
  echo "$out"
}

# gpu_fm_install_commands <family> <branch> <version> <nvlsm> <start-now yes|no>
# → the install line and the service enable, one per line.
gpu_fm_install_commands() {
  local pkgs
  pkgs="$(gpu_fm_packages "$1" "$2" "$3" "$4")" || return 1
  if [ "$1" = "el" ]; then
    echo "dnf install -y $pkgs"
  else
    echo "DEBIAN_FRONTEND=noninteractive apt-get install -y $pkgs"
  fi
  if [ "$5" = "yes" ]; then
    echo "systemctl enable --now ${GPU_FM_SERVICE}"
  else
    echo "systemctl enable ${GPU_FM_SERVICE}"
  fi
}

# gpu_installed_driver_version <family> <branch> → the version of the driver
# packages just installed (the module may not be loaded until a restart).
gpu_installed_driver_version() {
  local v=""
  case "$1" in
    el) v="$(rpm -q --qf '%{VERSION}\n' nvidia-driver-cuda 2>/dev/null | head -n 1)" ;;
    nvidia-apt) v="$(dpkg-query -W -f '${Version}\n' nvidia-driver-cuda 2>/dev/null | head -n 1)" ;;
    ubuntu-archive) v="$(dpkg-query -W -f '${Version}\n' "nvidia-utils-$2-server" 2>/dev/null | head -n 1)" ;;
  esac
  v="$(gpu_upstream_version "$v")"
  gpu_driver_major "$v" >/dev/null || return 1
  echo "$v"
}

# gpu_ubuntu_archive_driver <branch> → 0 when the loaded driver is Ubuntu's
# own -server driver of that branch (so Fabric Manager comes from the archive).
gpu_ubuntu_archive_driver() {
  command -v dpkg-query >/dev/null 2>&1 || return 1
  dpkg-query -W -f '${db:Status-Abbrev} ${Package}\n' 2>/dev/null |
    grep -qE "^ii +(nvidia-utils|libnvidia-compute|nvidia-headless-no-dkms|nvidia-headless)-$1-server(-open)?\$"
}

# _gpu_fm_nvlsm_archive_note — Ubuntu's archive has no nvlsm.
_gpu_fm_nvlsm_archive_note() {
  warn "This board (HGX B100/B200/B300) also needs the NVLink Subnet Manager (nvlsm), which Ubuntu's archive does not have. Install the nvlsm package from NVIDIA's CUDA repository, then: sudo systemctl restart ${GPU_FM_SERVICE} (${GPU_FM_DOC_URL})"
}

# _gpu_fm_failed <mode> <why> — Fabric Manager could not be set up. auto: warn
# and continue (the panel runs; CUDA on this board does not); install: fail.
_gpu_fm_failed() {
  warn "Fabric Manager could not be installed: $2. CUDA on this HGX board will not start until NVIDIA Fabric Manager runs at the driver's version: install it, then sudo systemctl enable --now ${GPU_FM_SERVICE} (${GPU_FM_DOC_URL})."
  if [ "$1" = "install" ]; then
    error_gpu "--gpu-driver=install: NVIDIA Fabric Manager is required on this NVSwitch board and could not be set up."
    return 1
  fi
  return 0
}

# _gpu_fm_after_install <plan> <family> — after a fresh driver install: adds
# Fabric Manager at the version just installed and enables its service (it
# starts with the driver: at the next boot, or in _gpu_finish). Returns 1 only
# under --gpu-driver=install.
_gpu_fm_after_install() {
  local plan="$1" fam="$2" mode="${AAP_GPU_DRIVER:-auto}" branch nvlsm v lines
  gpu_plan_has "$plan" "fabric_manager=yes" || return 0
  branch="$(gpu_plan_get "$plan" branch)"
  nvlsm="$(gpu_plan_get "$plan" nvlsm)"
  if [ "${DRY_RUN:-false}" = "true" ]; then
    v="<driver-version>"
  elif ! v="$(gpu_installed_driver_version "$fam" "$branch")"; then
    _gpu_fm_failed "$mode" "the version of the driver just installed could not be read"
    return
  fi
  if ! lines="$(gpu_fm_install_commands "$fam" "$branch" "$v" "$nvlsm" no)"; then
    _gpu_fm_failed "$mode" "no Fabric Manager package matches driver branch ${branch} here"
    return
  fi
  info "Installing NVIDIA Fabric Manager for driver ${v} (NVSwitch board)..."
  [ "$fam" = "ubuntu-archive" ] && [ "$nvlsm" = "yes" ] && _gpu_fm_nvlsm_archive_note
  _gpu_run_lines "$lines" || {
    _gpu_fm_failed "$mode" "the package step above failed"
    return
  }
}

# gpu_fm_existing <plan> <mode> — a driver is loaded on an NVSwitch board. The
# driver is never touched. Fabric Manager is installed when missing, its
# service turned on when it matches, and a version that does not match the
# driver is reported, never replaced. Returns 1 only under --gpu-driver=install.
gpu_fm_existing() {
  local plan="$1" mode="$2" drv="${GPU_DRIVER_VERSION:-}" fm="${GPU_FM_VERSION:-}" branch fam nvlsm lines
  nvlsm="$(gpu_plan_get "$plan" nvlsm)"
  info "NVSwitch found (HGX board): CUDA only starts there with NVIDIA Fabric Manager at the driver's version."
  if [ -n "$fm" ]; then
    if gpu_fm_version_matches "$drv" "$fm"; then
      if systemctl is-active --quiet "$GPU_FM_SERVICE" && systemctl is-enabled --quiet "$GPU_FM_SERVICE"; then
        info "Fabric Manager ${fm} is installed and running. Nothing to do."
        return 0
      fi
      info "Fabric Manager ${fm} matches driver ${drv}, but its service is not on. Turning it on."
      _gpu_exec "systemctl enable --now ${GPU_FM_SERVICE}" || {
        _gpu_fm_failed "$mode" "its service did not start (sudo journalctl -u ${GPU_FM_SERVICE})"
        return
      }
      return 0
    fi
    warn "Fabric Manager ${fm} does not match driver ${drv}. CUDA on this HGX board will not start until they match: below branch 620 Fabric Manager must be the driver's exact version, from 620 it is the 2.x package of the driver's branch. The installer replaces neither; update Fabric Manager to match the driver (${GPU_FM_DOC_URL})."
    if [ "$mode" = "install" ]; then
      error_gpu "--gpu-driver=install: Fabric Manager ${fm} does not match driver ${drv}."
      return 1
    fi
    return 0
  fi
  if ! branch="$(gpu_driver_major "$drv")"; then
    _gpu_fm_failed "$mode" "the loaded driver's version could not be read"
    return
  fi
  if [ -e "${GPU_NVIDIA_UNINSTALL:-/usr/bin/nvidia-uninstall}" ]; then
    _gpu_fm_failed "$mode" "the driver was installed with NVIDIA's .run installer, so packages would not match it; install the Fabric Manager build for driver ${drv} from NVIDIA"
    return
  fi
  if ! gpu_install_supported "${OS_ID:-}" "${OS_VERSION_MAJOR:-}" "${GPU_MACHINE:-}"; then
    _gpu_fm_failed "$mode" "this installer does not install packages for it on ${OS_PRETTY:-this OS}"
    return
  fi
  case "${OS_ID:-}" in
    ubuntu)
      if gpu_ubuntu_archive_driver "$branch"; then fam=ubuntu-archive; else fam=nvidia-apt; fi
      ;;
    debian) fam=nvidia-apt ;;
    *) fam=el ;;
  esac
  if ! lines="$(gpu_fm_install_commands "$fam" "$branch" "$drv" "$nvlsm" yes)"; then
    _gpu_fm_failed "$mode" "Ubuntu's archive has no Fabric Manager for driver branch ${branch} any more (it moved to 580); update the driver to 580-server first"
    return
  fi
  info "Fabric Manager is not installed. Installing it for driver ${drv}; the driver itself stays as it is."
  [ "$fam" = "ubuntu-archive" ] && [ "$nvlsm" = "yes" ] && _gpu_fm_nvlsm_archive_note
  _gpu_run_lines "$lines" || {
    _gpu_fm_failed "$mode" "the package step above failed. The package must be exactly version ${drv}; if the repository only has a newer one, update the driver first (and check that the driver's package repository is configured)"
    return
  }
  return 0
}

# ===== scripts/lib/ai.sh =====
# shellcheck disable=SC2034  # this library SETS globals (METERED_*) that are read
# by install.sh.in's setup_litellm_config / pull_metered_model — shellcheck can't
# see those cross-file reads when it lints this module in isolation.
# scripts/lib/ai.sh — metered-AI model selection for the bundled Ollama singleton.
#
# The metered operator AI is served by a panel-managed Ollama singleton
# (aiadminpanel_ollama) behind the LiteLLM gateway. The gateway mounts its config
# read-only and has NO runtime reload path, so the model must be chosen at install
# time — and it must match what Ollama actually has pulled, or the first metered
# call 404s. deepseek-r1:7b (~8GB working set) also OOMs the small marketplace
# boxes (DigitalOcean/Vultr) that our auto-deploy targets.
#
# So we RAM-gate (AI-622): deepseek-r1:7b on capable boxes, a small Llama-3B
# fallback on small ones, and the installer auto-pulls whichever it picked.
#
# Design decision (AI-622, "stable alias"): the gateway model_name stays
# `deepseek-r1` on EVERY box — it is the invoke key three Go call sites hardcode
# as the VPS default (chat_handler.go, analyze_handler.go, aideploy/openai_client.go).
# Renaming it would 404 those calls on exactly the small boxes we protect. On a
# small box it simply routes `deepseek-r1` → the real llama3.2:3b at the honest
# 3B price; the AI Models page shows the operator the model actually running, so
# nobody is misled. See docs-v2 concepts/ai.md.
#
# Pure, sourceable functions — unit-tested directly in tests/installer/ai_metered_model.bats.

# ── Model tiers ──────────────────────────────────────────────────────────────
# The gateway's stable invoke name (never varies — see header). Backend defaults
# to this string when no model is configured.
AAP_METERED_MODEL_NAME="deepseek-r1"

# Capable-box model: the showcase reasoning model.
AAP_METERED_DEEPSEEK_TAG="deepseek-r1:7b"     # 4.7GB download, ~8GB working set
AAP_METERED_DEEPSEEK_IN="0.0000001"           # operator selling price: $0.10 / 1M input tokens
AAP_METERED_DEEPSEEK_OUT="0.0000004"          #                        $0.40 / 1M output tokens

# Small-box fallback: current-best small general model (verified against the live
# Ollama library at wiring, 2026-07-18). Priced at half the 7B rate — honestly
# cheaper for a smaller model. Local models cost $0 in LiteLLM's map, so without a
# price here metered budgets never accrue spend (spec M2).
AAP_METERED_FALLBACK_TAG="llama3.2:3b"        # 2.0GB download, ~3-4GB working set
AAP_METERED_FALLBACK_IN="0.00000005"          # $0.05 / 1M input tokens
AAP_METERED_FALLBACK_OUT="0.0000002"          # $0.20 / 1M output tokens

# Threshold (total RAM, MB). deepseek-r1:7b wants ~8GB and the box also runs
# Postgres/Keycloak/Traefik/panel/litellm. 12000MB cleanly separates the real
# marketplace tiers: an 8GB box reports ~7900MB MemTotal (→ fallback), a 16GB box
# ~15800MB (→ deepseek). Overridable for tests.
AAP_METERED_MIN_MB_DEEPSEEK="${AAP_METERED_MIN_MB_DEEPSEEK:-12000}"

# _detect_total_mem_mb — echo total RAM in MB, read from MemTotal (KB) in
# /proc/meminfo. Honors MEMINFO_FILE so tests can feed a fixture. Echoes 0 if
# unreadable — which classifies as "small" and picks the safe fallback.
_detect_total_mem_mb() {
  local meminfo="${MEMINFO_FILE:-/proc/meminfo}" kb
  kb="$(awk '/^MemTotal:/ { print $2; exit }' "$meminfo" 2>/dev/null || true)"
  if [ -n "$kb" ] && [ "$kb" -gt 0 ] 2>/dev/null; then
    echo "$(( kb / 1024 ))"
  else
    echo 0
  fi
}

# ── Engine memory limit (AI-2492) ────────────────────────────────────────────
# The bundled Ollama runs under a hard memory limit with no swap on top, so a
# model that does not fit kills the engine's own runner and nothing else. The
# limit is sized from host RAM once, here, and written to .env as
# OLLAMA_MEM_LIMIT; docker-compose.yml applies it as mem_limit = memswap_limit.
#
#   limit_mb = min(total_mb / 2, total_mb - 3072), and never below 1024
#
# The 3 GB floor of headroom is the platform's own working set (panel, Postgres,
# Keycloak, LiteLLM, Traefik, OpenBao, Valkey, ~2-2.5 GB measured on demo2) plus
# the kernel; taking at most half the RAM leaves the other half for customer
# apps on bigger servers. 8 GB class (7488 MB) → 3744 MB; 16 GB → 8000 MB.
# scripts/aap-update.sh carries a copy of this function for existing installs;
# tests/installer/ai_2492_ollama_memory_cap.bats keeps the two identical.
# AAP_OLLAMA_MEM_LIMIT_MB pins the value instead.
AAP_OLLAMA_MODEL_MARGIN_MB="${AAP_OLLAMA_MODEL_MARGIN_MB:-1024}"  # context + runtime buffers on top of the weights

ollama_mem_limit_mb() {
  if [ -n "${AAP_OLLAMA_MEM_LIMIT_MB:-}" ] && [ "$AAP_OLLAMA_MEM_LIMIT_MB" -gt 0 ] 2>/dev/null; then
    echo "$AAP_OLLAMA_MEM_LIMIT_MB"
    return 0
  fi
  local total half rest limit
  total="$(_detect_total_mem_mb)"
  half=$(( total / 2 ))
  rest=$(( total - 3072 ))
  limit=$half
  [ "$rest" -lt "$limit" ] && limit=$rest
  [ "$limit" -lt 1024 ] && limit=1024
  echo "$limit"
}

# ollama_mem_limit_env_block — the .env line docker-compose.yml reads.
ollama_mem_limit_env_block() {
  echo "OLLAMA_MEM_LIMIT=$(ollama_mem_limit_mb)m"
}

# metered_model_size_mb TAG — download size of a model the installer may pull
# (the weights Ollama loads into memory). Echoes 0 for a tag it does not know.
metered_model_size_mb() {
  case "$1" in
    deepseek-r1:7b) echo 4700 ;;
    llama3.2:3b)    echo 2048 ;;
    *)              echo 0 ;;
  esac
}

# metered_model_fits TAG — true when the model's weights plus the margin fit
# the engine's memory limit. An unknown size is not refused here (the panel's
# pull check sees the real size while it downloads).
metered_model_fits() {
  local size
  size="$(metered_model_size_mb "$1")"
  [ "$size" -eq 0 ] && return 0
  [ $(( size + AAP_OLLAMA_MODEL_MARGIN_MB )) -le "$(ollama_mem_limit_mb)" ]
}

# select_metered_model — decide the bundled Ollama model from detected RAM and set:
#   METERED_OLLAMA_TAG    the tag to pull + route to (deepseek-r1:7b | llama3.2:3b)
#   METERED_INPUT_COST    per-token selling price (input)
#   METERED_OUTPUT_COST   per-token selling price (output)
#   METERED_IS_FALLBACK   "true" on a small box, "false" on a capable one
#   METERED_TOTAL_MB      detected total RAM in MB (for the UI/log message)
# The gateway model_name is always AAP_METERED_MODEL_NAME (stable alias).
select_metered_model() {
  local mb
  mb="$(_detect_total_mem_mb)"
  METERED_TOTAL_MB="$mb"
  if [ "$mb" -ge "$AAP_METERED_MIN_MB_DEEPSEEK" ]; then
    METERED_OLLAMA_TAG="$AAP_METERED_DEEPSEEK_TAG"
    METERED_INPUT_COST="$AAP_METERED_DEEPSEEK_IN"
    METERED_OUTPUT_COST="$AAP_METERED_DEEPSEEK_OUT"
    METERED_IS_FALLBACK="false"
  else
    METERED_OLLAMA_TAG="$AAP_METERED_FALLBACK_TAG"
    METERED_INPUT_COST="$AAP_METERED_FALLBACK_IN"
    METERED_OUTPUT_COST="$AAP_METERED_FALLBACK_OUT"
    METERED_IS_FALLBACK="true"
  fi
}

# render_litellm_config — emit the LiteLLM proxy config for the selected model to
# stdout. Auto-selects if select_metered_model has not run yet. Deterministic:
# given the same RAM it always produces the same config.
render_litellm_config() {
  [ -n "${METERED_OLLAMA_TAG:-}" ] || select_metered_model
  cat <<EOF
# LiteLLM Proxy Configuration
# Routes AI inference requests to the local Ollama singleton.
# Mounted into the litellm container at /app/config.yaml (read-only).
#
# GENERATED BY THE INSTALLER (AI-622) — the model is RAM-gated at install time:
#   >= ${AAP_METERED_MIN_MB_DEEPSEEK}MB total RAM -> ${AAP_METERED_DEEPSEEK_TAG}, else ${AAP_METERED_FALLBACK_TAG}.
# The model_name stays '${AAP_METERED_MODEL_NAME}' on every box (stable invoke key);
# on a small box it routes to the real fallback model at its own price. Edit freely;
# a re-run keeps an existing file.

model_list:
  - model_name: ${AAP_METERED_MODEL_NAME}
    litellm_params:
      model: ollama_chat/${METERED_OLLAMA_TAG}
      # The container name, not the Compose service name "ollama": the gateway
      # has a leg in tenant networks, where a tenant service of that name would
      # answer the lookup (AI-832).
      api_base: http://aiadminpanel_ollama:11434
    model_info:
      # Operator's SELLING price for the bundled local model (USD per token).
      # Local models are \$0 in LiteLLM's cost map — without a price here,
      # metered budgets never accrue spend for local usage (spec M2).
      # Edit to your own price list; a pricing UI is a filed follow-up.
      input_cost_per_token: ${METERED_INPUT_COST}
      output_cost_per_token: ${METERED_OUTPUT_COST}

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
EOF
}

# local_ai_model_env_block — emit the .env line that tells the panel which model
# the installer pulled (AI-1144). The panel's "Local AI" deploy source hands this
# name to deployed apps; it used to carry its own literal, which named a tag no
# box had. One value, one place: the same METERED_OLLAMA_TAG the gateway config
# routes to and pull_metered_model pulls. Auto-selects if select_metered_model
# has not run yet.
local_ai_model_env_block() {
  [ -n "${METERED_OLLAMA_TAG:-}" ] || select_metered_model
  echo "AAP_LOCAL_AI_MODEL=${METERED_OLLAMA_TAG}"
}

# ── On-demand engine (AI-2746) ───────────────────────────────────────────────
# docker-compose.yml puts the bundled Ollama behind the Compose profile
# "ollama": the image is 8.5 GB and no model is pulled at first boot, so a fresh
# install neither pulls nor starts it. The panel starts it when an admin pulls
# the first local model (through the host updater, which then adds the profile
# here). Compose reads COMPOSE_PROFILES from the .env next to the Compose file,
# so every later `docker compose` call - an installer re-run, an update - keeps
# the engine. An install where the engine already exists gets the line too.
#
# The updater (scripts/aap-update.sh) carries the same two functions; the bats
# test tests/installer/ai_2746_ollama_on_demand.bats keeps them identical.

# ollama_profile_enabled <env_file> — true when COMPOSE_PROFILES there names
# the "ollama" profile.
ollama_profile_enabled() {
  local line
  line="$(grep -E '^COMPOSE_PROFILES=' "$1" 2>/dev/null | tail -1)" || return 1
  line="${line#COMPOSE_PROFILES=}"
  line="$(printf '%s' "$line" | tr -d "\"' ")"
  case ",${line}," in
    *,ollama,*) return 0 ;;
  esac
  return 1
}

# add_ollama_profile <env_file> — add "ollama" to COMPOSE_PROFILES, keeping any
# profile already named there. Idempotent; ends an open last line first.
add_ollama_profile() {
  local env_file="$1" current
  ollama_profile_enabled "$env_file" && return 0
  current="$(grep -E '^COMPOSE_PROFILES=' "$env_file" 2>/dev/null | tail -1)"
  current="$(printf '%s' "${current#COMPOSE_PROFILES=}" | tr -d "\"' ")"
  sed -i -E '/^COMPOSE_PROFILES=/d' "$env_file" || return 1
  if [ -s "$env_file" ] && [ -n "$(tail -c1 "$env_file")" ]; then
    echo >> "$env_file" || return 1
  fi
  echo "COMPOSE_PROFILES=${current:+${current},}ollama" >> "$env_file"
}

# ===== scripts/lib/hardening.sh =====
# scripts/lib/hardening.sh — AI-2776: every install hardens SSH and the server
# automatically, and SSH stays reachable.
#
# Owner decision (2026-11-28): "Don't switch SSH off. Leave it open, and apply
# fail2ban and the other hardening automatically." So this module never stops,
# restarts or closes SSH. It adds four things, each of which an operator can
# turn off in /opt/aiadminpanel/.env (or the environment of install.sh):
#
#   AAP_HARDEN_FAIL2BAN=off     fail2ban with an sshd jail (systemd journal
#                               backend: Ubuntu 26.04 has no auth.log)
#   AAP_HARDEN_PANEL_JAIL=off   the fail2ban jail for failed panel / Keycloak
#                               sign-ins (on by default)
#   AAP_HARDEN_SSHD=off         the sshd drop-in sshd_config.d/10-aiadminpanel-hardening.conf
#   AAP_HARDEN_SSH_PASSWORDS=keep   never turn off password login, even when a
#                               working authorized key exists
#   AAP_HARDEN_UPGRADES=off     automatic security updates (unattended-upgrades)
#   AAP_HARDEN_IGNOREIP="…"     extra addresses / CIDRs fail2ban never bans
#
# "off" also removes what an earlier install wrote for that part (our own files
# only), so turning a part off and re-running the installer undoes it.
# A failure in any part warns and the install goes on; nothing here is fatal.
#
# Research and sources: docs/research/2026-11-29-install-hardening.md.
#
# The sshd rules (DockPanel re-check a3, docs/research/2026-11-29-dockpanel-recheck.md):
#   - sshd keeps the FIRST value it reads. Ubuntu, Debian and RHEL read
#     sshd_config.d/*.conf in name order from an Include at the top of
#     sshd_config, so our "10-" file wins over the provider's 50-cloud-init.conf.
#     We never edit sshd_config itself. After the write, `sshd -T` must show
#     our values; a setting another file wins is reported, not fought.
#   - `sshd -t` runs before any reload; when it fails, the previous drop-in
#     comes back (or ours is removed) and sshd is not reloaded.
#   - Root login stays possible (Vultr customers sign in as root with the Vultr
#     password). `PermitRootLogin prohibit-password` only when root has a
#     working authorized key; `PasswordAuthentication no` only when root and
#     every other user with a password have one.
#   - It never sets ListenAddress or Port. Vultr's first boot holds sshd on
#     127.0.0.1 with `ListenAddress 127.0.0.1` in sshd_config and removes the
#     line when its own vendor scripts finish (AI-2735); a ListenAddress here
#     would be read first and keep SSH closed.
#
# Public functions:
#   hardening_apply                 → runs every part, then the reachability
#                                     check, and prints what it applied
#   hardening_setting KEY DEFAULT   → the value from the environment, else from
#                                     ${PANEL_DIR}/.env, else DEFAULT
#   hardening_sshd_dropin R P       → the drop-in text (R: root key-only yes|no,
#                                     P: password login off yes|no) (pure)
#   hardening_ssh_key_decision      → HARDEN_ROOT_KEYONLY, HARDEN_PASSWORDS_OFF,
#                                     HARDEN_KEY_REASON
#   hardening_jail_conf PORTS IGNORE PANEL → the fail2ban jail file (pure)
#   hardening_keycloak_filter       → the fail2ban filter for Keycloak (pure)
#   hardening_keycloak_log_unit     → the systemd unit that copies Keycloak's
#                                     sign-in events to the journal (pure)
#   hardening_check_ssh_reachable   → warns loudly when the SSH port is not
#                                     allowed by the firewall or nothing listens
#
# Test surface: every path is under ${AAP_HARDEN_ROOT:-} (empty on a real
# server), and every tool (sshd, systemctl, fail2ban-client, apt-get, ss, ufw,
# firewall-cmd, nft) resolves through PATH, so bats shims them.
# Pure function definitions only — nothing runs at source time.

HARDEN_DROPIN_NAME="10-aiadminpanel-hardening.conf"
HARDEN_JAIL_NAME="aiadminpanel.local"
HARDEN_FILTER_NAME="aiadminpanel-keycloak.conf"
HARDEN_UNIT_NAME="aap-keycloak-auth-log.service"
HARDEN_APT_NAME="21aiadminpanel-auto-upgrades"
HARDEN_KC_CONTAINER="aiadminpanel_keycloak"
# Docker's networks on a panel host: docker0 (172.17/16) and the panel's
# address pools (172.18–172.31, lib/docker.sh). The panel talks to Keycloak from
# there, and when Docker's userland proxy forwards a client (IPv6 to an
# IPv4-only container), Keycloak sees the bridge gateway instead of the client.
# Banning one of those would cut the panel off, so they are never banned.
HARDEN_DOCKER_NETS="172.16.0.0/12"

# The installer's info/warn (lib/log.sh) when they are defined as functions;
# `command -v info` would also find texinfo's /usr/bin/info.
_hd_info() { if declare -F info >/dev/null; then info "$@"; else printf 'INFO  %s\n' "$*" >&2; fi; }
_hd_warn() { if declare -F warn >/dev/null; then warn "$@"; else printf 'WARN  %s\n' "$*" >&2; fi; }
_hd_dry() { printf '[would] %s\n' "$*"; }
_hd_report() { HARDENING_REPORT+=("$*"); }
_hd_is_dry() { [ "${DRY_RUN:-false}" = "true" ]; }

# ── settings ──────────────────────────────────────────────────────────────────
# The .env file is read line by line, never sourced: it holds secrets and is
# not ours to execute.
hardening_setting() {
  local key="$1" def="${2:-}" val="" found=false file line
  if [ -n "${!key+x}" ]; then
    val="${!key}"
    found=true
  else
    file="${PANEL_DIR:-/opt/aiadminpanel}/.env"
    if [ -r "$file" ]; then
      while IFS= read -r line || [ -n "$line" ]; do
        case "$line" in "$key="*) val="${line#*=}"; found=true ;; esac
      done <"$file"
      val="${val%\"}"; val="${val#\"}"; val="${val%\'}"; val="${val#\'}"
    fi
  fi
  if [ "$found" = false ] || [ -z "$val" ]; then val="$def"; fi
  printf '%s' "$val"
}

# hardening_on KEY → 0 when the part is on (the default), 1 when it is off.
hardening_on() {
  local val
  val="$(hardening_setting "$1" on)"
  case "$(printf '%s' "$val" | tr '[:upper:]' '[:lower:]')" in
    on | true | yes | 1 | auto) return 0 ;;
    off | false | no | 0 | keep) return 1 ;;
    *)
      _hd_warn "$1=${val} is not on or off; treating it as on."
      return 0
      ;;
  esac
}

# ── sshd: who has a working authorized key ────────────────────────────────────
# A key line counts when it is a known public-key type followed by a base64
# blob. A key with a forced command (command="…", as AWS puts on root's
# "please log in as ubuntu" key) is not a way to log in, so it does not count.
_hd_key_line_ok() {
  local line="$1" before
  case "$line" in '' | '#'*) return 1 ;; esac
  if [[ "$line" =~ (^|[[:space:],])((ssh-ed25519|ssh-rsa|ssh-dss|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)[[:space:]]+[A-Za-z0-9+/]{60,}={0,3})([[:space:]]|$) ]]; then
    before="${line%%"${BASH_REMATCH[2]}"*}"
    case "$before" in *command=*) return 1 ;; esac
    return 0
  fi
  return 1
}

# _hd_mode_safe PATH → 0 when PATH is not writable by group or others (sshd's
# StrictModes refuses keys under such a path).
_hd_mode_safe() {
  local mode
  mode="$(stat -c '%a' "$1" 2>/dev/null)" || return 1
  [ $((8#$mode & 8#022)) -eq 0 ]
}

# _hd_owner_ok PATH UID → owned by that user or by root.
_hd_owner_ok() {
  local owner
  owner="$(stat -c '%u' "$1" 2>/dev/null)" || return 1
  [ "$owner" = "$2" ] || [ "$owner" = 0 ]
}

# _hd_authorized_key_files HOME USER → the authorized-keys files sshd reads for
# USER, from `sshd -T` (AuthorizedKeysFile), else OpenSSH's default.
_hd_authorized_key_files() {
  local home="$1" user="$2" files="" key val f
  if [ -n "${HARDEN_SSHD_T:-}" ]; then
    while read -r key val; do
      [ "$key" = "authorizedkeysfile" ] && files="$val"
    done <<<"$HARDEN_SSHD_T"
  fi
  [ -n "$files" ] || files=".ssh/authorized_keys .ssh/authorized_keys2"
  for f in $files; do
    [ "$f" = none ] && continue
    f="${f//%h/$home}"
    f="${f//%u/$user}"
    f="${f//%%/%}"
    case "$f" in /*) ;; *) f="${home}/${f}" ;; esac
    printf '%s%s\n' "${AAP_HARDEN_ROOT:-}" "$f"
  done
}

# hardening_user_has_working_key USER UID HOME → 0 when sshd would accept at
# least one key for USER: a valid key line in a file sshd reads, and that file,
# its folder and the home folder pass StrictModes.
hardening_user_has_working_key() {
  local user="$1" uid="$2" home="$3" file dir line
  while IFS= read -r file; do
    if [ ! -f "$file" ] || [ ! -r "$file" ]; then continue; fi
    dir="$(dirname "$file")"
    if ! _hd_owner_ok "$file" "$uid" || ! _hd_mode_safe "$file"; then continue; fi
    if ! _hd_owner_ok "$dir" "$uid" || ! _hd_mode_safe "$dir"; then continue; fi
    _hd_mode_safe "${AAP_HARDEN_ROOT:-}${home}" || continue
    while IFS= read -r line || [ -n "$line" ]; do
      if _hd_key_line_ok "$line"; then return 0; fi
    done <"$file"
  done < <(_hd_authorized_key_files "$home" "$user")
  return 1
}

# hardening_ssh_key_decision → sets HARDEN_ROOT_KEYONLY (yes|no),
# HARDEN_PASSWORDS_OFF (yes|no) and HARDEN_KEY_REASON (plain English).
# Password users: uid 0 or 1000+, a login shell, and a usable password hash.
hardening_ssh_key_decision() {
  local passwd="${AAP_HARDEN_ROOT:-}/etc/passwd" shadow="${AAP_HARDEN_ROOT:-}/etc/shadow"
  local name uid home shell hash root_home="/root" root_uid=0
  local -a pw_users_without_key=()
  HARDEN_ROOT_KEYONLY=no
  HARDEN_PASSWORDS_OFF=no

  if [ -r "$passwd" ]; then
    while IFS=: read -r name _ uid _ _ home shell; do
      [ "$name" = root ] && { root_home="$home"; root_uid="$uid"; }
    done <"$passwd"
  fi

  if hardening_user_has_working_key root "$root_uid" "$root_home"; then
    HARDEN_ROOT_KEYONLY=yes
  else
    HARDEN_KEY_REASON="root has no working authorized key, so root keeps password login"
    return 0
  fi

  if ! hardening_on AAP_HARDEN_SSH_PASSWORDS; then
    HARDEN_KEY_REASON="root has a working key; password login is kept (AAP_HARDEN_SSH_PASSWORDS=keep)"
    return 0
  fi

  if [ -r "$passwd" ]; then
    while IFS=: read -r name _ uid _ _ home shell; do
      [ "$name" = root ] && continue
      case "$uid" in '' | *[!0-9]*) continue ;; esac
      if [ "$uid" -lt 1000 ] || [ "$uid" -eq 65534 ]; then continue; fi
      case "$shell" in */nologin | */false | '') continue ;; esac
      hash=""
      if [ -r "$shadow" ]; then
        hash="$(awk -F: -v u="$name" '$1 == u { print $2; exit }' "$shadow")"
      fi
      case "$hash" in '' | '!'* | '*'*) continue ;; esac
      hardening_user_has_working_key "$name" "$uid" "$home" || pw_users_without_key+=("$name")
    done <"$passwd"
  else
    HARDEN_KEY_REASON="root has a working key; password login is kept (${passwd} is not readable, so other users cannot be checked)"
    return 0
  fi

  if [ "${#pw_users_without_key[@]}" -gt 0 ]; then
    HARDEN_KEY_REASON="root has a working key; password login is kept because ${pw_users_without_key[*]} has a password and no working key"
    return 0
  fi
  HARDEN_PASSWORDS_OFF=yes
  HARDEN_KEY_REASON="root has a working key, and no other user signs in with a password only"
}

# ── sshd: the drop-in ─────────────────────────────────────────────────────────
hardening_sshd_dropin() {
  local root_keyonly="$1" passwords_off="$2"
  cat <<'EOF'
# Written by the AI Admin Panel installer (AI-2776). Every install writes it
# again; to stop that, set AAP_HARDEN_SSHD=off in /opt/aiadminpanel/.env and
# re-run the installer, which then removes this file.
#
# sshd keeps the first value it reads, and it reads this folder in name order
# before the rest of /etc/ssh/sshd_config, so "10-" wins over 50-cloud-init.conf.
# This file never sets ListenAddress or Port (see the installation docs).
MaxAuthTries 4
LoginGraceTime 30
PermitEmptyPasswords no
X11Forwarding no
EOF
  if [ "$root_keyonly" = yes ]; then
    printf '%s\n' "# root has a working authorized key: root signs in with a key only." \
      "PermitRootLogin prohibit-password"
  fi
  if [ "$passwords_off" = yes ]; then
    printf '%s\n' "# Every user who had a password also has a working key." \
      "PasswordAuthentication no" "KbdInteractiveAuthentication no"
  fi
}

# Reload (never restart, never stop) whichever sshd unit is running. On Ubuntu
# with socket activation ssh.service may be idle; it reads the file at start.
_hd_reload_sshd() {
  local unit
  command -v systemctl >/dev/null 2>&1 || return 0
  for unit in ssh.service sshd.service; do
    if systemctl is-active --quiet "$unit" 2>/dev/null; then
      systemctl reload "$unit" >/dev/null 2>&1 \
        || _hd_warn "sshd did not reload (${unit}); the new settings apply at its next start."
      return 0
    fi
  done
  return 0
}

# _hd_sshd_check_effective FILE → warns for each setting of FILE that `sshd -T`
# shows with another value (another file read first sets it).
_hd_sshd_check_effective() {
  local file="$1" key val got eff lost=()
  eff="$(sshd -T 2>/dev/null)" || return 0
  while read -r key val; do
    case "$key" in '' | '#'*) continue ;; esac
    key="$(printf '%s' "$key" | tr '[:upper:]' '[:lower:]')"
    val="$(printf '%s' "$val" | tr '[:upper:]' '[:lower:]')"
    got="$(awk -v k="$key" '$1 == k { $1 = ""; sub(/^ /, ""); print; exit }' <<<"$eff")"
    [ "$got" = "$val" ] || lost+=("${key} (sshd uses ${got:-nothing})")
  done <"$file"
  if [ "${#lost[@]}" -gt 0 ]; then
    _hd_warn "sshd does not use these settings of ${file}, because a file it reads first sets them: ${lost[*]}"
  fi
}

_hd_remove_sshd_dropin() {
  local file="$1"
  [ -f "$file" ] || return 0
  if _hd_is_dry; then _hd_dry "rm ${file}; sshd -t; reload sshd"; return 0; fi
  rm -f "$file"
  if sshd -t >/dev/null 2>&1; then _hd_reload_sshd; fi
}

hardening_apply_sshd() {
  local root="${AAP_HARDEN_ROOT:-}"
  local main="${root}/etc/ssh/sshd_config" dir="${root}/etc/ssh/sshd_config.d"
  local file="${dir}/${HARDEN_DROPIN_NAME}" content prev="" had=false err

  if ! hardening_on AAP_HARDEN_SSHD; then
    _hd_remove_sshd_dropin "$file"
    _hd_report "sshd settings: off (AAP_HARDEN_SSHD=off)"
    return 0
  fi
  if ! command -v sshd >/dev/null 2>&1 || [ ! -f "$main" ]; then
    _hd_report "sshd settings: skipped (no OpenSSH server on this host)"
    return 0
  fi
  if ! grep -Eqi '^[[:space:]]*Include[[:space:]]+[^#]*sshd_config\.d' "$main"; then
    _hd_warn "${main} does not read ${dir}, and the installer never edits sshd_config itself; sshd settings not changed."
    _hd_report "sshd settings: skipped (${main} has no Include of sshd_config.d)"
    return 0
  fi

  HARDEN_SSHD_T="$(sshd -T 2>/dev/null)" || HARDEN_SSHD_T=""
  hardening_ssh_key_decision
  content="$(hardening_sshd_dropin "$HARDEN_ROOT_KEYONLY" "$HARDEN_PASSWORDS_OFF")"

  if _hd_is_dry; then
    _hd_dry "write ${file} (MaxAuthTries 4, LoginGraceTime 30, X11Forwarding no, PermitEmptyPasswords no; ${HARDEN_KEY_REASON}); sshd -t; reload sshd"
    _hd_report "sshd settings: would be written (${HARDEN_KEY_REASON})"
    return 0
  fi

  if [ -f "$file" ]; then prev="$(cat "$file")"; had=true; fi
  if [ "$had" = true ] && [ "$prev" = "$content" ]; then
    _hd_report "sshd settings: already in place (${HARDEN_KEY_REASON})"
    return 0
  fi

  mkdir -p "$dir"
  printf '%s\n' "$content" >"${file}.aap-new" && chmod 644 "${file}.aap-new" && mv -f "${file}.aap-new" "$file"

  if ! err="$(sshd -t 2>&1)"; then
    if [ "$had" = true ]; then printf '%s\n' "$prev" >"$file"; else rm -f "$file"; fi
    _hd_warn "sshd -t rejected the new settings, so they were rolled back and sshd was not reloaded: ${err%%$'\n'*}"
    _hd_report "sshd settings: rolled back (sshd -t failed)"
    return 0
  fi

  _hd_reload_sshd
  _hd_sshd_check_effective "$file"
  _hd_report "sshd settings: ${file} (${HARDEN_KEY_REASON})"
}

# ── fail2ban ──────────────────────────────────────────────────────────────────
# One jail file. [sshd] reads the journal (Ubuntu 26.04 logs SSH failures from
# sshd-session in ssh.service; RHEL uses sshd.service). The panel jail reads
# Keycloak's sign-in failures, which _hd_keycloak_log_unit copies to the
# journal under the identifier aap-keycloak-auth.
#
# Ban times: 5 failures in 10 minutes ban for 1 hour; each new ban of the same
# address doubles it, up to 1 day, so a customer who mistypes is never locked
# out for good. The panel jail allows 10, because Keycloak also locks the
# account itself after 5 (realm brute-force protection).
#
# The panel jail bans in nftables' forward hook. The panel's ports 80/443 are
# Docker-published, and Docker's DNAT sends that traffic through the forward
# path, never through input, so an input-chain ban would not stop it.
hardening_jail_conf() {
  local ports="$1" ignore="$2" panel="$3" port_list
  port_list="$(printf '%s' "$ports" | tr ' ' ',')"
  cat <<EOF
# Written by the AI Admin Panel installer (AI-2776). Every install writes it
# again; put your own changes in another /etc/fail2ban/jail.d/*.local file.
# Turn it off: AAP_HARDEN_FAIL2BAN=off (or AAP_HARDEN_PANEL_JAIL=off for the
# panel sign-in jail only) in /opt/aiadminpanel/.env, then re-run the installer.

[sshd]
enabled = true
backend = systemd
journalmatch = _SYSTEMD_UNIT=ssh.service + _SYSTEMD_UNIT=sshd.service + _COMM=sshd + _COMM=sshd-session
port = ${port_list}
maxretry = 5
findtime = 10m
bantime = 1h
bantime.increment = true
bantime.maxtime = 1d
ignoreip = 127.0.0.1/8 ::1 ${ignore}
EOF
  if [ "$panel" = on ]; then
    cat <<EOF

[aiadminpanel-keycloak]
enabled = true
filter = aiadminpanel-keycloak
backend = systemd
journalmatch = SYSLOG_IDENTIFIER=aap-keycloak-auth
maxretry = 10
findtime = 10m
bantime = 1h
bantime.increment = true
bantime.maxtime = 1d
action = nftables[type=allports, name=aiadminpanel-keycloak, chain=f2b-aap-forward, chain_hook=forward]
ignoreip = 127.0.0.1/8 ::1 ${HARDEN_DOCKER_NETS} ${ignore}
EOF
  fi
}

# Keycloak's jboss-logging listener writes one WARN line per failed sign-in
# (Keycloak 26.8.2, measured 2026-11-29, see the research note):
#   … WARN  [org.keycloak.events] (executor-thread-1) type="LOGIN_ERROR",
#   realmId="…", realmName="aiadminpanel", clientId="panel", userId="null",
#   ipAddress="203.0.113.8", error="user_not_found", …, username="…"
# Keycloak escapes quotes in values (clientId="x\", ipAddress=\"…") and joins
# lines, and ipAddress comes before the user-typed username. The regex pins the
# field order and steps over escaped quotes, so a forged ipAddress inside a
# client id or user name never matches. ipAddress is the real client: Traefik
# drops a client's own X-Forwarded-For before passing the request on.
hardening_keycloak_filter() {
  cat <<'EOF'
# Written by the AI Admin Panel installer (AI-2776): failed panel and Keycloak
# sign-ins, from Keycloak's org.keycloak.events log lines.
[Definition]
failregex = \[org\.keycloak\.events\] \(\S+\) type="(?:LOGIN_ERROR|CLIENT_LOGIN_ERROR)", realmId="[^"\\]*", (?:realmName="(?:[^"\\]|\\.)*", )?clientId="(?:[^"\\]|\\.)*", userId="[^"\\]*", ipAddress="<HOST>", error="(?:invalid_user_credentials|user_not_found|user_temporarily_disabled|invalid_client_credentials)"
ignoreregex =
EOF
}

# The unit that copies Keycloak's sign-in events into the journal. It follows
# the container by name, so it survives every recreate (updates); while the
# container is missing it retries every 10 seconds. Only [org.keycloak.events]
# lines pass, and only from this one container: a tenant app printing a fake
# line cannot get an address banned.
hardening_keycloak_log_unit() {
  cat <<EOF
# Written by the AI Admin Panel installer (AI-2776). AAP_HARDEN_PANEL_JAIL=off removes it.
[Unit]
Description=AI Admin Panel: Keycloak sign-in events for fail2ban
After=docker.service
Wants=docker.service
StartLimitIntervalSec=0

[Service]
Type=simple
ExecStart=/bin/sh -c 'docker logs --follow --tail 0 ${HARDEN_KC_CONTAINER} 2>&1 | grep --line-buffered -F "[org.keycloak.events]"'
SyslogIdentifier=aap-keycloak-auth
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
}

# _hd_pkg_install PKG… → installs the packages with the host's package manager.
_hd_pkg_install() {
  case "${PKG_MANAGER:-}" in
    apt)
      DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 install -y -q "$@" >/dev/null 2>&1 && return 0
      apt-get -o DPkg::Lock::Timeout=600 update -qq >/dev/null 2>&1 || true
      DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 install -y -q "$@" >/dev/null 2>&1
      ;;
    dnf | yum) "$PKG_MANAGER" install -y -q "$@" >/dev/null 2>&1 ;;
    zypper) zypper --non-interactive install -y "$@" >/dev/null 2>&1 ;;
    *) return 1 ;;
  esac
}

_hd_remove_fail2ban_files() {
  local root="${AAP_HARDEN_ROOT:-}" changed=false f
  local unit="${root}/etc/systemd/system/${HARDEN_UNIT_NAME}"
  if [ -f "$unit" ]; then
    if _hd_is_dry; then _hd_dry "systemctl disable --now ${HARDEN_UNIT_NAME}; rm ${unit}"; else
      systemctl disable --now "$HARDEN_UNIT_NAME" >/dev/null 2>&1 || true
      rm -f "$unit"
      systemctl daemon-reload >/dev/null 2>&1 || true
    fi
    changed=true
  fi
  if [ "${1:-all}" = all ]; then
    for f in "${root}/etc/fail2ban/jail.d/${HARDEN_JAIL_NAME}" "${root}/etc/fail2ban/filter.d/${HARDEN_FILTER_NAME}"; do
      [ -f "$f" ] || continue
      if _hd_is_dry; then _hd_dry "rm ${f}"; else rm -f "$f"; fi
      changed=true
    done
    if [ "$changed" = true ] && ! _hd_is_dry && command -v fail2ban-client >/dev/null 2>&1; then
      fail2ban-client reload >/dev/null 2>&1 || true
    fi
  fi
  return 0
}

_hd_write_file() {
  local path="$1" content="$2" mode="$3"
  mkdir -p "$(dirname "$path")"
  printf '%s\n' "$content" >"${path}.aap-new" && chmod "$mode" "${path}.aap-new" && mv -f "${path}.aap-new" "$path"
}

hardening_apply_fail2ban() {
  local root="${AAP_HARDEN_ROOT:-}"
  local jail="${root}/etc/fail2ban/jail.d/${HARDEN_JAIL_NAME}"
  local filter="${root}/etc/fail2ban/filter.d/${HARDEN_FILTER_NAME}"
  local unit="${root}/etc/systemd/system/${HARDEN_UNIT_NAME}"
  local panel=on ports ignore ok=false

  if ! hardening_on AAP_HARDEN_FAIL2BAN; then
    _hd_remove_fail2ban_files all
    _hd_report "fail2ban: off (AAP_HARDEN_FAIL2BAN=off)"
    return 0
  fi
  hardening_on AAP_HARDEN_PANEL_JAIL || panel=off
  ports="$(ssh_ports)"
  ignore="$(hardening_setting AAP_HARDEN_IGNOREIP "")"
  case "$ignore" in *[!0-9A-Fa-f.:/\ ,]*)
    _hd_warn "AAP_HARDEN_IGNOREIP may hold only addresses and CIDRs; ignoring it."
    ignore="" ;;
  esac
  ignore="${ignore//,/ }"

  if _hd_is_dry; then
    _hd_dry "install fail2ban and nftables; write ${jail} (sshd jail on ports ${ports}; panel sign-in jail ${panel})"
    [ "$panel" = on ] && _hd_dry "write ${filter} and ${unit}; systemctl enable --now ${HARDEN_UNIT_NAME}"
    _hd_dry "fail2ban-client --test; systemctl enable fail2ban; systemctl restart fail2ban"
    _hd_report "fail2ban: would be set up (panel sign-in jail ${panel})"
    return 0
  fi

  if ! command -v fail2ban-client >/dev/null 2>&1 || { [ "$panel" = on ] && ! command -v nft >/dev/null 2>&1; }; then
    if ! _hd_pkg_install fail2ban nftables; then
      _hd_warn "Could not install fail2ban with ${PKG_MANAGER:-no package manager} (on the RHEL family it comes from EPEL). SSH stays open without it."
      _hd_report "fail2ban: skipped (the package did not install)"
      return 0
    fi
  fi
  if [ "$panel" = on ] && ! command -v nft >/dev/null 2>&1; then
    _hd_warn "nft is not available, so the panel sign-in jail is left out (it bans with nftables)."
    panel=off
  fi
  if [ "$panel" = on ] && ! command -v docker >/dev/null 2>&1; then
    _hd_warn "Docker is not installed yet, so the panel sign-in jail is left out."
    panel=off
  fi

  _hd_write_file "$jail" "$(hardening_jail_conf "$ports" "$ignore" "$panel")" 644
  if [ "$panel" = on ]; then
    _hd_write_file "$filter" "$(hardening_keycloak_filter)" 644
    _hd_write_file "$unit" "$(hardening_keycloak_log_unit)" 644
  else
    _hd_remove_fail2ban_files unit
    rm -f "$filter"
  fi

  local f2b_help
  f2b_help="$(fail2ban-client --help 2>&1)" || true
  if [[ "$f2b_help" == *--test* ]] && ! fail2ban-client --test >/dev/null 2>&1; then
    rm -f "$jail" "$filter"
    _hd_remove_fail2ban_files unit
    _hd_warn "fail2ban rejected the installer's jail file, so it was removed; fail2ban keeps the distribution's settings."
    _hd_report "fail2ban: rolled back (fail2ban-client --test failed)"
    return 0
  fi

  if [ "$panel" = on ]; then
    systemctl daemon-reload >/dev/null 2>&1 || true
    systemctl enable --now "$HARDEN_UNIT_NAME" >/dev/null 2>&1 \
      || _hd_warn "${HARDEN_UNIT_NAME} did not start; the panel sign-in jail sees no events until it does."
  fi
  systemctl enable fail2ban >/dev/null 2>&1 || true
  if ! systemctl restart fail2ban >/dev/null 2>&1; then
    _hd_warn "fail2ban did not start; check 'systemctl status fail2ban' and 'journalctl -u fail2ban'."
    _hd_report "fail2ban: installed but not running"
    return 0
  fi
  for _ in 1 2 3 4 5 6 7 8 9 10; do
    if fail2ban-client status sshd >/dev/null 2>&1; then ok=true; break; fi
    sleep "${HARDEN_POLL_SECONDS:-1}"
  done
  if [ "$ok" != true ]; then
    _hd_warn "fail2ban started but its sshd jail does not answer; check 'fail2ban-client status sshd'."
    _hd_report "fail2ban: running, sshd jail not confirmed"
    return 0
  fi
  if [ "$panel" = on ]; then
    _hd_report "fail2ban: sshd jail on SSH port ${ports// /, } and the panel sign-in jail (5 SSH or 10 sign-in failures in 10 min ban for 1 h, doubling up to 1 day)"
  else
    _hd_report "fail2ban: sshd jail on SSH port ${ports// /, } (5 failures in 10 min ban for 1 h, doubling up to 1 day); panel sign-in jail off"
  fi
}

# ── automatic security updates ────────────────────────────────────────────────
# Debian and Ubuntu: unattended-upgrades with the distribution's own origins,
# which are the security pocket only. Our apt.conf.d file sorts after the
# package's 20auto-upgrades, so it wins. It never turns on automatic reboots.
hardening_apt_conf() {
  cat <<'EOF'
// Written by the AI Admin Panel installer (AI-2776): automatic security updates.
// AAP_HARDEN_UPGRADES=off in /opt/aiadminpanel/.env removes this file.
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
EOF
}

hardening_apply_upgrades() {
  local conf="${AAP_HARDEN_ROOT:-}/etc/apt/apt.conf.d/${HARDEN_APT_NAME}"
  if ! hardening_on AAP_HARDEN_UPGRADES; then
    if [ -f "$conf" ]; then
      if _hd_is_dry; then _hd_dry "rm ${conf}"; else rm -f "$conf"; fi
    fi
    _hd_report "automatic security updates: off (AAP_HARDEN_UPGRADES=off)"
    return 0
  fi
  if [ "${PKG_MANAGER:-}" != apt ]; then
    _hd_report "automatic security updates: not set up on this distribution (${OS_PRETTY:-${PKG_MANAGER:-unknown}}); turn on your distribution's own tool, for example dnf-automatic"
    return 0
  fi
  if _hd_is_dry; then
    _hd_dry "install unattended-upgrades; write ${conf}; systemctl enable --now apt-daily.timer apt-daily-upgrade.timer"
    _hd_report "automatic security updates: would be turned on"
    return 0
  fi
  if ! command -v unattended-upgrade >/dev/null 2>&1 && ! _hd_pkg_install unattended-upgrades; then
    _hd_warn "Could not install unattended-upgrades; security updates stay manual."
    _hd_report "automatic security updates: skipped (the package did not install)"
    return 0
  fi
  _hd_write_file "$conf" "$(hardening_apt_conf)" 644
  systemctl enable --now apt-daily.timer apt-daily-upgrade.timer >/dev/null 2>&1 || true
  _hd_report "automatic security updates: on (unattended-upgrades, security updates only, no automatic reboot)"
}

# ── after the install: is SSH reachable? ──────────────────────────────────────
# For every SSH port (lib/firewall.sh ssh_ports): something must listen on a
# non-loopback address, and a running ufw or firewalld must allow it. Any
# problem prints a loud warning with the fix; nothing is changed here.
_hd_loud() {
  local line
  _hd_warn "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  for line in "$@"; do _hd_warn "!!  ${line}"; done
  _hd_warn "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
}

hardening_check_ssh_reachable() {
  local ports p listen addr public lo problems=() ok_ports=()
  ports="$(ssh_ports)"
  detect_firewall
  for p in $ports; do
    listen="$(ss -Hltn "sport = :${p}" 2>/dev/null | awk '{ print $4 }')" || listen=""
    public=false lo=false
    for addr in $listen; do
      case "$addr" in 127.* | "[::1]:"* | "::1:"*) lo=true ;; *) public=true ;; esac
    done
    if [ "$public" = false ]; then
      if [ "$lo" = true ]; then
        problems+=("sshd listens on port ${p} on localhost only (127.0.0.1)." \
          "On a Vultr Marketplace server this is Vultr's own first-boot setting: Vultr removes" \
          "'ListenAddress 127.0.0.1' from /etc/ssh/sshd_config when its setup finishes (AI-2735)." \
          "Anywhere else, check ListenAddress in /etc/ssh/sshd_config and run: sshd -T | grep listenaddress")
      else
        problems+=("Nothing listens on SSH port ${p}." "Start SSH: systemctl start ssh.socket (Ubuntu) or systemctl start sshd")
      fi
    fi
    case "$FIREWALL_BACKEND" in
      ufw)
        if ! ufw status 2>/dev/null | grep -Eq "^(${p}(/tcp)?|OpenSSH)([[:space:]]+\(v6\))?[[:space:]]+(ALLOW|LIMIT)"; then
          problems+=("ufw is on and does not allow SSH port ${p}. Fix: ufw allow ${p}/tcp")
        fi
        ;;
      firewalld)
        if ! firewall-cmd --query-port="${p}/tcp" >/dev/null 2>&1 \
          && ! { [ "$p" = 22 ] && firewall-cmd --query-service=ssh >/dev/null 2>&1; }; then
          problems+=("firewalld does not allow SSH port ${p}. Fix: firewall-cmd --add-port=${p}/tcp --permanent && firewall-cmd --add-port=${p}/tcp")
        fi
        ;;
    esac
    ok_ports+=("$p")
  done
  if [ "${#problems[@]}" -gt 0 ]; then
    _hd_loud "SSH MAY NOT BE REACHABLE after this install. Fix it before you log out:" "${problems[@]}"
    _hd_report "SSH reachability: PROBLEM (see the warning above)"
    return 0
  fi
  case "$FIREWALL_BACKEND" in
    ufw | firewalld) _hd_report "SSH reachability: port ${ok_ports[*]} listens and ${FIREWALL_BACKEND} allows it" ;;
    *) _hd_report "SSH reachability: port ${ok_ports[*]} listens (no ufw or firewalld here; check your provider's firewall)" ;;
  esac
}

# ── everything ────────────────────────────────────────────────────────────────
hardening_apply() {
  HARDENING_REPORT=()
  # sshd, ufw and nft live in /usr/sbin, which a non-login root shell (or
  # cloud-init) may not have on PATH. Appended, so a PATH shim still wins.
  case ":${PATH}:" in *:/usr/sbin:*) ;; *) PATH="${PATH}:/usr/sbin" ;; esac
  case ":${PATH}:" in *:/sbin:*) ;; *) PATH="${PATH}:/sbin" ;; esac
  _hd_info "SSH and server hardening (AI-2776). SSH stays open; each part can be turned off in ${PANEL_DIR:-/opt/aiadminpanel}/.env."
  hardening_apply_fail2ban
  hardening_apply_sshd
  hardening_apply_upgrades
  hardening_check_ssh_reachable
  local line
  _hd_info "Hardening applied:"
  for line in "${HARDENING_REPORT[@]}"; do _hd_info "  - ${line}"; done
  return 0
}

setup_colors

# AI-2172: accept the GitHub release name (v2.22.0) as well as the image tag
# (2.22.0). GHCR has no v-prefixed tags, so .env must carry the tag form.
PANEL_VERSION="$(normalize_panel_version "$PANEL_VERSION")"

# AI-2327: where this run downloads its Compose file, Keycloak realm and theme.
# A concrete release reads its own folder (<GET_BASE>/v<version>); latest, main
# and other moving tags read the top level, which tracks main.
RELEASE_ASSET_BASE="$(release_asset_base "$GET_BASE" "$PANEL_VERSION")"

# AI-2218: a bad UPGRADE_URL stops here, before the box changes. The panel
# would otherwise ignore it and silently link to the default page.
check_upgrade_url || exit 2

# AI-2792: a bad ADMIN_EMAIL / --admin-email stops here, before the box
# changes; a good one is trimmed and lower-cased.
check_admin_email || exit 2

# AI-2400: a mistyped TLS_MODE stops here, before the box changes. It used to
# fall back to HTTP-01 without a word.
check_tls_mode || exit 2

# AI-2330: a mistyped --gpu-driver / AAP_GPU_DRIVER stops here too.
if ! gpu_driver_mode_valid "$AAP_GPU_DRIVER"; then
  echo "--gpu-driver / AAP_GPU_DRIVER must be auto, skip or install (got '${AAP_GPU_DRIVER}')." >&2
  exit 1
fi

# (Root / port / disk / DNS / systemd / virtualization checks are now provided by
#  lib/preflight.sh via preflight_checks().)

# ── Domain Prompt ────────────────────────────────────────────────────────────

prompt_domain() {
  if [ -n "$PANEL_DOMAIN" ]; then
    info "Using domain from environment: ${PANEL_DOMAIN}"
  elif [ "${MANAGED_DOMAIN:-}" = "off" ]; then
    # Opt-out: exactly the pre-AI-544 behavior. Order matches pre-AI-544
    # (unattended aborts even under --dry-run) so a dry-run of an unattended
    # opt-out install still surfaces the missing-PANEL_DOMAIN error instead of
    # masking it. off is not a claimable config, so the claim-path dry-run
    # short-circuit below deliberately does not apply here.
    if [ "$UNATTENDED" = "true" ]; then
      error "PANEL_DOMAIN must be set when using --unattended mode (MANAGED_DOMAIN=off)"
    elif [ "$DRY_RUN" = "true" ]; then
      PANEL_DOMAIN="dry-run.example.com"
      dryrun "Would prompt for domain, using placeholder: ${PANEL_DOMAIN}"
    elif [ ! -t 0 ]; then
      error "PANEL_DOMAIN is required. Download first, then run interactively: curl -fsSL https://get.aiadminpanel.com -o install.sh && bash install.sh"
    else
      echo ""
      read -rp "${COLOR_BOLD}Enter panel domain (e.g., panel.example.com): ${COLOR_RESET}" PANEL_DOMAIN
      if [ -z "$PANEL_DOMAIN" ]; then
        error "Domain is required. Set PANEL_DOMAIN env var or provide interactively."
      fi
      info "Domain set to: ${PANEL_DOMAIN}"
    fi
  elif [ "$DRY_RUN" = "true" ]; then
    # Claimable dry-run (no PANEL_DOMAIN, managed path enabled): never abort —
    # narrate the claim. Wins over the --unattended abort below by design.
    PANEL_DOMAIN="dry-run.example.com"
    dryrun "Would claim temporary domain from ${MANAGED_DNS_URL} (no PANEL_DOMAIN set); using placeholder: ${PANEL_DOMAIN}"
  elif [ "$UNATTENDED" = "true" ] || [ ! -t 0 ]; then
    # No domain and no human (marketplace / curl|bash): auto-claim (AI-544).
    md_acquire_domain || error "$MD_FAIL_REASON"
  else
    # Interactive: blank Enter = claim a temporary domain; failure re-prompts.
    while [ -z "$PANEL_DOMAIN" ]; do
      echo ""
      read -rp "${COLOR_BOLD}Enter panel domain (or press Enter to get a free temporary domain like aap-x7k2f9.aiadminpanel.host): ${COLOR_RESET}" PANEL_DOMAIN
      if [ -n "$PANEL_DOMAIN" ]; then
        info "Domain set to: ${PANEL_DOMAIN}"
      elif md_acquire_domain; then
        break
      else
        warn "$MD_FAIL_REASON"
        warn "Enter your own domain, or press Enter again to retry the claim."
      fi
    done
  fi

  # Derive ACME email from domain if not already set. Runs after every
  # success path (env, dry-run, interactive) so the .env file always
  # carries a real email. Without this, the docker-compose.yml fallback
  # `${ACME_EMAIL:-admin@example.com}` leaks through and Let's Encrypt
  # rejects example.com on registration (AI-239, demo2 2026-05-06).
  local acme_given=false
  [ -z "$ACME_EMAIL" ] || acme_given=true
  resolve_admin_email
  if [ -z "$ACME_EMAIL" ]; then
    # AI-2792: the owner's own address receives the certificate notices.
    if [ "$ADMIN_EMAIL_FALLBACK" = true ]; then
      ACME_EMAIL="admin@${PANEL_DOMAIN}"
    else
      ACME_EMAIL="$ADMIN_EMAIL"
    fi
    info "ACME email set to: ${ACME_EMAIL}"
  elif [ "$acme_given" = false ]; then
    info "ACME email set to: ${ACME_EMAIL}"
  fi
}

# resolve_admin_email: settles ADMIN_EMAIL, the admin account's e-mail and
# sign-in name (AI-2792), once PANEL_DOMAIN is known.
#   - A re-run (.env exists) keeps the address the panel was installed with:
#     the ADMIN_EMAIL line in .env, or admin@<domain> for an install made
#     before AI-2792. A different value is ignored with a warning; a second
#     admin account would lock the owner out of the setup wizard.
#   - Given (ADMIN_EMAIL or --admin-email, already checked): used.
#   - Interactive: asked for, again after an unusable answer.
#   - Otherwise (unattended, piped, dry run): admin@<domain>, and the setup
#     wizard asks for the owner's own e-mail once (ADMIN_EMAIL_FALLBACK).
resolve_admin_email() {
  local env_file="${PANEL_DIR}/.env" recorded="" answer addr
  if [ -f "$env_file" ]; then
    recorded="$(sed -n 's/^ADMIN_EMAIL=//p' "$env_file" | tail -n 1)"
    [ -n "$recorded" ] || recorded="admin@${PANEL_DOMAIN}"
    if [ -n "$ADMIN_EMAIL" ] && [ "$ADMIN_EMAIL" != "$recorded" ]; then
      warn "This panel keeps the admin e-mail it was installed with (${recorded}); ADMIN_EMAIL=${ADMIN_EMAIL} is ignored. Change the address in the panel (your profile) instead."
    fi
    ADMIN_EMAIL="$recorded"
    [ "$recorded" != "admin@${PANEL_DOMAIN}" ] || ADMIN_EMAIL_FALLBACK=true
    return 0
  fi
  if [ -n "$ADMIN_EMAIL" ]; then
    info "Admin sign-in e-mail: ${ADMIN_EMAIL}"
    return 0
  fi
  if [ "$UNATTENDED" != "true" ] && [ "$DRY_RUN" != "true" ] && [ -t 0 ]; then
    echo ""
    echo "${COLOR_BOLD}Your e-mail address.${COLOR_RESET} This becomes your admin sign-in e-mail;"
    echo "password resets and certificate notices go there too."
    while :; do
      read -rp "${COLOR_BOLD}Your e-mail: ${COLOR_RESET}" answer || break
      if addr="$(admin_email_normalize "$answer")"; then
        ADMIN_EMAIL="$addr"
        info "Admin sign-in e-mail: ${ADMIN_EMAIL}"
        return 0
      fi
      warn "That is not an e-mail address you can receive mail at (for example you@example.com; addresses at aiadminpanel.host have no mailbox). Try again."
    done
  fi
  ADMIN_EMAIL="admin@${PANEL_DOMAIN}"
  ADMIN_EMAIL_FALLBACK=true
  info "No ADMIN_EMAIL given: the admin signs in as ${ADMIN_EMAIL} until the setup wizard asks for your own e-mail."
}

# ── License Key Prompt ────────────────────────────────────────────────────────

prompt_license() {
  if [ -n "${LICENSE_KEY:-}" ]; then
    info "Using license key from environment"
    return 0
  fi

  if [ "$UNATTENDED" = "true" ]; then
    info "No LICENSE_KEY set — panel will start a 14-day trial on first setup"
    return 0
  fi

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "Would prompt for license key (optional)"
    return 0
  fi

  # When piped (curl | bash), stdin is not a terminal — skip optional prompt
  if [ ! -t 0 ]; then
    info "Non-interactive mode — skipping license key prompt (14-day trial will activate)"
    return 0
  fi

  echo ""
  read -rp "${COLOR_BOLD}License Key (optional — press Enter for 14-day trial): ${COLOR_RESET}" LICENSE_KEY

  if [ -n "$LICENSE_KEY" ]; then
    info "License key provided — will be written to .env"
  else
    info "No license key — panel will start a 14-day full-featured trial on first setup"
  fi
}

# ── Platform Detection + Support Gate ─────────────────────────────────────────
# Replaces the old Ubuntu/Debian-only detect_os(). Uses lib/platform.sh to detect
# the distro family, package manager and architecture, then gates on the support
# tier: certified → proceed; best-effort/document → warn and continue; reject →
# abort with a specific message naming what IS supported (AI-349).
detect_and_gate_platform() {
  detect_platform || true
  info "Detected: ${OS_PRETTY:-$OS_ID} (family=${OS_FAMILY}, version=${OS_VERSION_ID:-?})"
  case "$PLATFORM_TIER" in
    certified)
      info "Supported distribution: ${PLATFORM_REASON}"
      ;;
    best-effort)
      warn "Best-effort distribution (not in our CI-certified matrix): ${PLATFORM_REASON}"
      warn "Proceeding anyway — please report any problems."
      ;;
    document)
      warn "Partially-supported distribution: ${PLATFORM_REASON}"
      warn "Proceeding best-effort — see docs.aiadminpanel.com for manual steps if it fails."
      ;;
    reject | *)
      error "${PLATFORM_REASON}"
      ;;
  esac

  detect_pm
  [ "$PKG_MANAGER" != "unknown" ] ||
    error "No supported package manager found (need one of apt/dnf/yum/zypper/pacman)."

  detect_arch ||
    error "Unsupported architecture: $(uname -m) (need x86_64 or aarch64/arm64)."

  info "Platform: ${OS_PRETTY:-$OS_ID} | package manager: ${PKG_MANAGER} | arch: ${ARCH} (${BINARY_SUFFIX})"
}

# (detect_arch is now provided by lib/platform.sh.)

# (Port 80/443 conflict check is now in lib/preflight.sh check_ports_free, run as
#  part of preflight_checks().)

# ── Docker daemon: address pools (and, no longer, the storage driver) ────────
# The universal Docker engine + compose/buildx install is provided by
# lib/docker.sh install_docker() (every distro, with tooling verification).
# Called right after install_docker on a fresh box.
#
# AI-1330: this helper no longer pins "storage-driver": "overlay2". Docker 29
# installs with the containerd image store by default, and Git Deploy's
# Railpack builds need it: the classic store's BuildKit refuses Railpack's
# frontend ("mergeop ... only enabled with containerd image store backend").
# The pin was said to work around a "containerd v2.2.x overlayfs snapshotter
# COPY bug", but no ticket, commit message or upstream issue for that bug is on
# record (it came in with the April 2026 v2.1.x squash merge, 804478e2e). On
# 2026-10-15 a COPY check on the containerd store of stock Ubuntu 24.04 with
# Docker 29.5.3 and containerd 2.2.4 (directories, a symlink, --chmod, --link,
# multi-stage --from, deleting a lower-layer file) passed, and the CI runner has
# built every image on that store since August 2026. Evidence: PR #942 and
# docs/research/2026-10-15-railpack-builder.md. A host installed before this
# change keeps overlay2 (switching hides every image and container); Railpack
# refuses to build there with a message that says so.
#
# AI-1446: it also sets Docker's default-address-pools, so the host holds
# thousands of networks instead of about 31 (lib/docker.sh explains the range).
# Only on a fresh Docker (installed by this run, or no container yet): a re-run
# of the installer on a host in use must not restart every container, so there
# it changes nothing and points to --docker-address-pools. An existing
# daemon.json is merged, never replaced: its other keys stay, the original is
# backed up, and a file that is not JSON is refused. Docker restarts only when
# the file changed. A failure here does not stop the install: the panel then
# runs with Docker's default pools, as before.
configure_docker_daemon() {
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "On a fresh Docker only: ensure /etc/docker/daemon.json sets default-address-pools; restart Docker if it changed"
    return 0
  fi
  if [ -e /etc/docker/daemon.json ]; then ensure_jq; fi
  if docker_install_time_pools /etc/docker/daemon.json; then
    case "$DOCKER_POOLS_RESULT" in
      created) info "Docker configured with address pools for many networks" ;;
      merged) info "Docker address pools added to the existing /etc/docker/daemon.json" ;;
    esac
  else
    warn "Docker address pools were not set; this host holds about 31 Docker networks (one per customer). Fix /etc/docker/daemon.json, then run: sudo bash install.sh --docker-address-pools"
  fi
}

# --docker-address-pools (AI-1446): bring the address pools to an existing
# install. Restarts Docker, and so every container, when the file changes.
configure_docker_address_pools_only() {
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "merge default-address-pools into /etc/docker/daemon.json (backup first); restart Docker if it changed"
    return 0
  fi
  ensure_jq
  docker_configure_address_pools /etc/docker/daemon.json || return 1
  case "$DOCKER_POOLS_RESULT" in
    unchanged) info "Docker already uses the panel's address pools. Nothing changed; Docker was not restarted." ;;
    kept) info "Docker keeps the address pools already set in /etc/docker/daemon.json. Nothing changed; Docker was not restarted." ;;
    *) info "Docker now uses address pools for many networks. All containers were restarted; check that the panel and your apps are up." ;;
  esac
}

# Read-only hint for --refresh-updater: say when the pools are still Docker's
# defaults, without changing anything (a change would restart every container).
docker_address_pools_hint() {
  local pools
  pools="$(docker info --format '{{json .DefaultAddressPools}}' 2>/dev/null)" || return 0
  case "$pools" in
    "" | null | "[]")
      warn "Docker still uses its default address pools: about 31 networks, one per customer. In a maintenance window run: sudo bash install.sh --docker-address-pools (restarts every container)."
      ;;
  esac
}

# ── Directory Setup ───────────────────────────────────────────────────────────

create_directories() {
  info "Creating panel directories..."
  # update/ is the host-shared channel between the panel and the systemd updater;
  # backups/ holds the pre-update pg_dumps the updater takes (AI-431 2B).
  # AI-2745: a bake leaves secrets/ out. Its mere existence in a cloud image
  # is a leftover (spec 2.1), and --bake refuses a server that has it; the
  # first boot creates it with the secrets (generate_secrets, mode 700).
  local -a dirs=("$PANEL_DIR" "$CONFIG_DIR" "$LOG_DIR" "$SECRETS_DIR" "$PANEL_DIR/update" "$PANEL_DIR/backups")
  [ "$INSTALL_PHASE" != bake ] || dirs=("$PANEL_DIR" "$CONFIG_DIR" "$LOG_DIR" "$PANEL_DIR/update" "$PANEL_DIR/backups")
  for dir in "${dirs[@]}"; do
    if [ -d "$dir" ]; then
      debug "Directory exists: $dir"
    else
      run mkdir -p "$dir"
      info "Created: $dir"
    fi
  done
}

# ── Secret Generation ─────────────────────────────────────────────────────────
# Thin dry-run-aware wrapper over lib/secrets.sh generate_secrets(), which is
# portable (openssl/od, no GNU-only base64 -w0 / xxd), writes EVERY secret 600
# (fixes the db_password/keycloak_admin_password world-readable 644 leak), is
# idempotent (never overwrites an existing secret), and additionally generates a
# per-install litellm_master_key (no more shared sk-litellm-master-key default).
setup_secrets() {
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "Migrate any legacy /run/secrets/* into ${SECRETS_DIR}, then generate master_key, db_password, keycloak_admin_password, litellm_master_key, dns01_bridge_secret, managed_domain_token, openbao_unseal_key, an empty legacy_closed marker in ${SECRETS_DIR} (dir 700, files 600 except openbao_unseal_key 644 — read by the openbao container's non-root server), render the OpenBao config at ${PANEL_DIR}/openbao/config/openbao.hcl (dir 755, file 644), and render the audit-log rotation script at ${PANEL_DIR}/openbao/openbao-log-rotate.sh (755, bounds audit.log for the openbao_log_rotator sidecar — AI-611)"
    return 0
  fi
  # AI-397: on a box upgraded from a pre-AI-397 install that has NOT yet
  # rebooted, the live secrets still sit in the legacy tmpfs /run/secrets.
  # Carry them into the persistent dir BEFORE generating, so the existing
  # postgres password is preserved rather than regenerated into a mismatch.
  migrate_legacy_secrets "${SECRETS_DIR}"
  # AI-2146: only a key this run creates is protected automatically. An
  # existing install keeps its key until the owner runs aap-openbao-key protect
  # (it needs the owner to take the recovery key first).
  if [ ! -e "${SECRETS_DIR}/openbao_unseal_key" ] && [ ! -e "${SECRETS_DIR}/openbao_unseal_key.cred" ]; then
    OPENBAO_KEY_NEW=true
  fi
  info "Generating secrets in ${SECRETS_DIR}..."
  generate_secrets "${SECRETS_DIR}"
  write_openbao_config "${PANEL_DIR}/openbao/config"
  # Bound the OpenBao audit log so it can never fill the disk again (AI-611).
  # Rendered next to config/ (a single-file :ro bind mount into the sidecar).
  write_openbao_log_rotate_script "${PANEL_DIR}/openbao"
  info "Secrets ready (master_key, db_password, keycloak_admin_password, litellm_master_key, dns01_bridge_secret, managed_domain_token, openbao_unseal_key, legacy_closed)"
}

# ── Release-pinned downloads (AI-2327) ───────────────────────────────────────
# PANEL_VERSION=2.25.0 used to install the 2.25.0 image with the Compose file,
# realm and theme from the top of get.aiadminpanel.com, which track main: an
# older image could be started with a newer Compose file. A concrete release now
# reads its own immutable folder (<GET_BASE>/v<version>/, written once by the
# release workflow's stage-r2 job) and checks every file against that folder's
# SHA256SUMS. A wrong hash always stops the install, and a pinned install never
# falls back to main's copy (the realm may still fall back to a bundled local copy).
#
# What the hash proves: the file is the one that release published, not a
# half-download and not main's copy. SHA256SUMS comes from the same server over
# HTTPS; its cosign signature is not checked here (cosign is installed later).
# Releases up to 2.21.x have no SHA256SUMS: their own files are used unchecked.
# See docs-v2 "Verify the installer before running it" for the signed check.
RELEASE_SHA256SUMS=""

# fetch_release_asset <name> <dest> → 0 when <name> from RELEASE_ASSET_BASE is
# at <dest>. Returns 1 (and leaves <dest> absent) when the download fails, so a
# caller can fall back. A pinned release's file that does not match SHA256SUMS
# is fatal (error exits): that is never a fallback case.
fetch_release_asset() {
  local name="$1" dest="$2" part="${2}.part"
  rm -f "$part"
  if ! curl -fsSL "${RELEASE_ASSET_BASE}/${name}" -o "$part" 2>/dev/null; then
    rm -f "$part"
    return 1
  fi
  if [ "$RELEASE_ASSET_BASE" != "$GET_BASE" ]; then
    verify_release_asset "$name" "$part"
  fi
  mv -f "$part" "$dest"
}

# verify_release_asset <name> <file> → 0 when <file> has the hash the pinned
# release's SHA256SUMS lists for <name>. SHA256SUMS is downloaded once per run.
verify_release_asset() {
  local name="$1" file="$2" want got
  if [ -z "$RELEASE_SHA256SUMS" ]; then
    # The file itself just came from this server, so a failed fetch here means
    # the release has no SHA256SUMS: releases up to 2.21.x predate it. Their
    # folder still holds that release's own files, so install them unchecked.
    RELEASE_SHA256SUMS="$(curl -fsSL "${RELEASE_ASSET_BASE}/SHA256SUMS" 2>/dev/null)" || RELEASE_SHA256SUMS=""
    if [ -z "$RELEASE_SHA256SUMS" ]; then
      RELEASE_SHA256SUMS="none"
      warn "Release v${PANEL_VERSION} has no SHA256SUMS (releases up to 2.21.x predate it): its files come from its own folder but are not checked."
    fi
  fi
  [ "$RELEASE_SHA256SUMS" = "none" ] && return 0
  # Every refusal removes the downloaded file first, so nothing unchecked stays.
  if ! want="$(printf '%s\n' "$RELEASE_SHA256SUMS" | sha256sums_lookup "$name")"; then
    rm -f "$file"
    error "${RELEASE_ASSET_BASE}/SHA256SUMS does not list ${name}. Refusing to install an unchecked file."
  fi
  if ! got="$(sha256_hex <"$file")"; then
    rm -f "$file"
    error "Could not compute the SHA-256 of ${name} (needs sha256sum or openssl)."
  fi
  if [ "$got" != "$want" ]; then
    rm -f "$file"
    error "${name} from ${RELEASE_ASSET_BASE} does not match the release's SHA256SUMS (expected ${want}, got ${got}). Refusing to install it. Retry; if it fails again, report it."
  fi
  info "${name} matches the SHA256SUMS of release v${PANEL_VERSION}"
}

# ── Keycloak Setup ────────────────────────────────────────────────────────────

setup_keycloak() {
  info "Setting up Keycloak identity server..."

  # Create Keycloak database in PostgreSQL
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "CREATE DATABASE keycloak"
    return 0
  fi

  # Run DB setup via docker exec (postgres container is already running)
  docker exec aiadminpanel_postgresql psql -U aiadminpanel -c \
    "SELECT 1 FROM pg_database WHERE datname='keycloak'" 2>/dev/null | grep -q "1 row" || \
    docker exec aiadminpanel_postgresql psql -U aiadminpanel -c \
      "CREATE DATABASE keycloak;" 2>/dev/null || true

  info "Keycloak database configured"

  # Download realm export for auto-import on first boot
  local realm_export="${PANEL_DIR}/keycloak-realm-export.json"
  if [ ! -f "$realm_export" ]; then
    # Download from the get server, then fall back to a bundled local copy.
    if fetch_release_asset keycloak-realm-export.json "$realm_export"; then
      chmod 644 "$realm_export"
      info "Realm export downloaded from ${RELEASE_ASSET_BASE}"
    else
      # Try local fallbacks
      local bundled_paths=(
        "$(dirname "$(readlink -f "$0")")/../keycloak-realm-export.json"
        "/tmp/aiadminpanel-keycloak-realm-export.json"
      )
      for path in "${bundled_paths[@]}"; do
        if [ -f "$path" ]; then
          cp "$path" "$realm_export"
          chmod 644 "$realm_export"
          info "Realm export copied from ${path}"
          break
        fi
      done
    fi
    [ -f "$realm_export" ] || warn "Keycloak realm export not found — Keycloak will start with default realm. Import manually."
  else
    info "Keycloak realm export already exists at ${realm_export}"
  fi

  # Download Keycloak login theme (branded dark theme with logo)
  local theme_dir="${PANEL_DIR}/keycloak-theme/login/resources/css"
  if [ ! -d "$theme_dir" ]; then
    info "Downloading Keycloak login theme..."
    mkdir -p "$theme_dir"
    if fetch_release_asset keycloak-theme.tar.gz /tmp/keycloak-theme.tar.gz; then
      tar -xzf /tmp/keycloak-theme.tar.gz -C "${PANEL_DIR}/"
      rm -f /tmp/keycloak-theme.tar.gz
      info "Keycloak theme installed"
    elif [ "$RELEASE_ASSET_BASE" != "$GET_BASE" ]; then
      # AI-2327: the loose files below exist only at the main-tracking top
      # level; a pinned install does not mix them in.
      warn "Could not download keycloak-theme.tar.gz from ${RELEASE_ASSET_BASE}. Keycloak will use its default login theme."
    else
      # Fallback: try individual files from get server
      curl -fsSL "${GET_BASE}/keycloak-theme/login/theme.properties" -o "${PANEL_DIR}/keycloak-theme/login/theme.properties" 2>/dev/null || true
      curl -fsSL "${GET_BASE}/keycloak-theme/login/resources/css/aiadminpanel.css" -o "${theme_dir}/aiadminpanel.css" 2>/dev/null || true
      curl -fsSL "${GET_BASE}/keycloak-theme/login/resources/css/logo.png" -o "${theme_dir}/logo.png" 2>/dev/null || true
      info "Keycloak theme installed (fallback)"
    fi
  else
    info "Keycloak theme already exists"
  fi
}

# 3a-2: LiteLLM's virtual-key/budget machinery needs its own database
# (Prisma-managed). Same pattern as the keycloak DB: shared postgres
# instance, shared aiadminpanel role, separate database. Idempotent.
setup_litellm_db() {
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "Create the litellm database in the bundled Postgres (idempotent)"
    return 0
  fi

  docker exec aiadminpanel_postgresql psql -U aiadminpanel -c \
    "SELECT 1 FROM pg_database WHERE datname='litellm'" 2>/dev/null | grep -q "1 row" || \
    docker exec aiadminpanel_postgresql psql -U aiadminpanel -c \
      "CREATE DATABASE litellm;" 2>/dev/null || true

  info "LiteLLM database ready"
}

create_river_tables() {
  info "Creating River queue tables (if not exist)..."

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "CREATE river_migration, river_job, river_leader, river_queue, river_client tables"
    return 0
  fi

  # Check if river tables already exist (idempotent)
  if docker exec aiadminpanel_postgresql psql -U aiadminpanel -d aiadminpanel -tAc \
    "SELECT 1 FROM information_schema.tables WHERE table_name='river_job'" 2>/dev/null | grep -q "1"; then
    info "River tables already exist, skipping"
    return 0
  fi

  # River v0.31.0 migration SQL (from riverdriver/riverpgxv5 migration/main/001-006)
  # Write to temp file to avoid stdin conflict with curl pipe
  local sql_file="/tmp/river-migrations.sql"
  cat > "$sql_file" <<'RIVERSQL'
-- Migration 001: Create river_migration table
CREATE TABLE IF NOT EXISTS river_migration(
  id bigserial PRIMARY KEY,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  version bigint NOT NULL,
  CONSTRAINT version CHECK (version >= 1)
);
CREATE UNIQUE INDEX IF NOT EXISTS river_migration_version_idx ON river_migration USING btree(version);

-- Migration 002: Initial schema (river_job, river_leader)
DO $$ BEGIN
  CREATE TYPE river_job_state AS ENUM(
    'available', 'cancelled', 'completed', 'discarded', 'retryable', 'running', 'scheduled'
  );
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;

CREATE TABLE IF NOT EXISTS river_job(
  id bigserial PRIMARY KEY,
  state river_job_state NOT NULL DEFAULT 'available',
  attempt smallint NOT NULL DEFAULT 0,
  max_attempts smallint NOT NULL,
  attempted_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT NOW(),
  finalized_at timestamptz,
  scheduled_at timestamptz NOT NULL DEFAULT NOW(),
  priority smallint NOT NULL DEFAULT 1,
  args jsonb,
  attempted_by text[],
  errors jsonb[],
  kind text NOT NULL,
  metadata jsonb NOT NULL DEFAULT '{}',
  queue text NOT NULL DEFAULT 'default',
  tags varchar(255)[] NOT NULL DEFAULT '{}',
  CONSTRAINT finalized_or_finalized_at_null CHECK (
    (finalized_at IS NULL AND state NOT IN ('cancelled', 'completed', 'discarded')) OR
    (finalized_at IS NOT NULL AND state IN ('cancelled', 'completed', 'discarded'))
  ),
  CONSTRAINT max_attempts_is_positive CHECK (max_attempts > 0),
  CONSTRAINT priority_in_range CHECK (priority >= 1 AND priority <= 4),
  CONSTRAINT queue_length CHECK (char_length(queue) > 0 AND char_length(queue) < 128),
  CONSTRAINT kind_length CHECK (char_length(kind) > 0 AND char_length(kind) < 128)
);

CREATE INDEX IF NOT EXISTS river_job_kind ON river_job USING btree(kind);
CREATE INDEX IF NOT EXISTS river_job_state_and_finalized_at_index ON river_job USING btree(state, finalized_at) WHERE finalized_at IS NOT NULL;
CREATE INDEX IF NOT EXISTS river_job_prioritized_fetching_index ON river_job USING btree(state, queue, priority, scheduled_at, id);
CREATE INDEX IF NOT EXISTS river_job_args_index ON river_job USING GIN(args);
CREATE INDEX IF NOT EXISTS river_job_metadata_index ON river_job USING GIN(metadata);

CREATE UNLOGGED TABLE IF NOT EXISTS river_leader(
  elected_at timestamptz NOT NULL,
  expires_at timestamptz NOT NULL,
  leader_id text NOT NULL,
  name text PRIMARY KEY DEFAULT 'default',
  CONSTRAINT name_length CHECK (name = 'default'),
  CONSTRAINT leader_id_length CHECK (char_length(leader_id) > 0 AND char_length(leader_id) < 128)
);

-- Migration 004: Add pending state, create river_queue
ALTER TYPE river_job_state ADD VALUE IF NOT EXISTS 'pending' AFTER 'discarded';

CREATE TABLE IF NOT EXISTS river_queue(
  name text PRIMARY KEY NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  metadata jsonb NOT NULL DEFAULT '{}',
  paused_at timestamptz,
  updated_at timestamptz NOT NULL DEFAULT now()
);

-- Migration 005: Rebuild river_migration with line support, add unique_key, create river_client
DO $body$
BEGIN
  IF (SELECT to_regclass('river_migration') IS NOT NULL) THEN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='river_migration' AND column_name='line') THEN
      ALTER TABLE river_migration RENAME TO river_migration_old;
      CREATE TABLE river_migration(
        line TEXT NOT NULL,
        version bigint NOT NULL,
        created_at timestamptz NOT NULL DEFAULT NOW(),
        CONSTRAINT line_length CHECK (char_length(line) > 0 AND char_length(line) < 128),
        CONSTRAINT version_gte_1 CHECK (version >= 1),
        PRIMARY KEY (line, version)
      );
      INSERT INTO river_migration (created_at, line, version)
        SELECT created_at, 'main', version FROM river_migration_old;
      DROP TABLE river_migration_old;
    END IF;
  END IF;
END;
$body$ LANGUAGE plpgsql;

ALTER TABLE river_job ADD COLUMN IF NOT EXISTS unique_key bytea;
-- River's 005 also creates river_job_kind_unique_key_idx and 006 drops it again.
-- It must not exist here (AI-1148): it ignores job state, so a finished unique
-- job would block the next one. tests/installer/river_schema.bats guards this.

CREATE UNLOGGED TABLE IF NOT EXISTS river_client(
  id text PRIMARY KEY NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  metadata jsonb NOT NULL DEFAULT '{}',
  paused_at timestamptz,
  updated_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT name_length CHECK (char_length(id) > 0 AND char_length(id) < 128)
);

CREATE UNLOGGED TABLE IF NOT EXISTS river_client_queue(
  river_client_id text NOT NULL REFERENCES river_client(id) ON DELETE CASCADE,
  name text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  max_workers bigint NOT NULL DEFAULT 0,
  metadata jsonb NOT NULL DEFAULT '{}',
  num_jobs_completed bigint NOT NULL DEFAULT 0,
  num_jobs_running bigint NOT NULL DEFAULT 0,
  updated_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (river_client_id, name),
  CONSTRAINT name_length CHECK (char_length(name) > 0 AND char_length(name) < 128),
  CONSTRAINT num_jobs_completed_zero_or_positive CHECK (num_jobs_completed >= 0),
  CONSTRAINT num_jobs_running_zero_or_positive CHECK (num_jobs_running >= 0)
);

-- Migration 006: Add river_job_state_in_bitmask function and unique_states column
CREATE OR REPLACE FUNCTION river_job_state_in_bitmask(bitmask BIT(8), state river_job_state)
RETURNS boolean
LANGUAGE SQL
IMMUTABLE
AS $$
  SELECT CASE state
    WHEN 'available' THEN get_bit(bitmask, 7)
    WHEN 'cancelled' THEN get_bit(bitmask, 6)
    WHEN 'completed' THEN get_bit(bitmask, 5)
    WHEN 'discarded' THEN get_bit(bitmask, 4)
    WHEN 'pending'   THEN get_bit(bitmask, 3)
    WHEN 'retryable' THEN get_bit(bitmask, 2)
    WHEN 'running'   THEN get_bit(bitmask, 1)
    WHEN 'scheduled' THEN get_bit(bitmask, 0)
    ELSE 0
  END = 1;
$$;

ALTER TABLE river_job ADD COLUMN IF NOT EXISTS unique_states BIT(8);
CREATE UNIQUE INDEX IF NOT EXISTS river_job_unique_idx ON river_job (unique_key)
  WHERE unique_key IS NOT NULL AND unique_states IS NOT NULL AND river_job_state_in_bitmask(unique_states, state);

-- Record migration versions so River recognizes the schema
INSERT INTO river_migration (line, version) VALUES ('main', 1) ON CONFLICT DO NOTHING;
INSERT INTO river_migration (line, version) VALUES ('main', 2) ON CONFLICT DO NOTHING;
INSERT INTO river_migration (line, version) VALUES ('main', 3) ON CONFLICT DO NOTHING;
INSERT INTO river_migration (line, version) VALUES ('main', 4) ON CONFLICT DO NOTHING;
INSERT INTO river_migration (line, version) VALUES ('main', 5) ON CONFLICT DO NOTHING;
INSERT INTO river_migration (line, version) VALUES ('main', 6) ON CONFLICT DO NOTHING;
RIVERSQL

  docker cp "$sql_file" aiadminpanel_postgresql:/tmp/river-migrations.sql
  local river_rc=0
  docker exec aiadminpanel_postgresql psql -U aiadminpanel -d aiadminpanel -f /tmp/river-migrations.sql 2>&1 | tail -5 || river_rc=$?

  if [ "$river_rc" -eq 0 ]; then
    info "River queue tables created successfully"
  else
    warn "River table creation had errors (may be partially created -- panel will retry)"
  fi
  rm -f "$sql_file"
}

# retry_backoff <delays> <what> <command...> — run the command, and again after
# each delay in <delays> (seconds, space separated) until it succeeds. Each
# retried failure is logged with what is retried. AI-2456: Keycloak in
# production mode reports healthy only once ready, but its admin API can still
# answer 503 for a moment; one failed admin login used to end the install's
# admin setup.
retry_backoff() {
  local delays="$1" what="$2" delay attempt=1
  shift 2
  "$@" && return 0
  for delay in $delays; do
    warn "${what} failed (attempt ${attempt}); retrying in ${delay}s"
    sleep "$delay"
    attempt=$((attempt + 1))
    "$@" && return 0
  done
  return 1
}

# Seconds between Keycloak admin login attempts: about 45 s in all.
KC_ADMIN_LOGIN_RETRY_DELAYS="${KC_ADMIN_LOGIN_RETRY_DELAYS:-2 4 8 15 15}"

wait_for_keycloak() {
  local max_attempts=120
  local attempt=0

  info "Waiting for Keycloak to become healthy (up to 120s)..."

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "poll docker inspect aiadminpanel_keycloak health status up to 120s"
    return 0
  fi

  while [ "$attempt" -lt "$max_attempts" ]; do
    local health
    health=$(docker inspect --format='{{.State.Health.Status}}' aiadminpanel_keycloak 2>/dev/null || echo "unknown")
    if [ "$health" = "healthy" ]; then
      info "Keycloak is healthy"
      return 0
    fi
    attempt=$((attempt + 1))
    sleep 1
  done

  warn "Keycloak did not become healthy within 120s. Check logs:"
  warn "  docker logs aiadminpanel_keycloak"
  return 1
}

# ── Admin User Creation ──────────────────────────────────────────────────────

# kcadm_with_password <password> <kcadm args...> runs kcadm in the Keycloak
# container with the password in KC_CLI_PASSWORD, which kcadm reads when
# --password (config credentials) or --new-password (set-password) is absent.
# AI-2355: a password on the command line is readable by every local user
# through ps or /proc/<pid>/cmdline while docker exec runs. `-e KC_CLI_PASSWORD`
# names the variable without a value, so the docker client takes the value
# from its own environment (readable by root only) and sends it in the API
# request; argv carries only the name. The assignment applies to this one
# docker call, so later commands do not inherit it.
kcadm_with_password() {
  local password="$1"
  shift
  KC_CLI_PASSWORD="$password" docker exec -e KC_CLI_PASSWORD aiadminpanel_keycloak /opt/keycloak/bin/kcadm.sh "$@"
}

# AI-1184: the admin account is created in two steps. The Keycloak user needs
# only Keycloak; the panel's own users row needs the users table, which the
# panel creates in its migrations at start. Before this split the row was
# inserted right after Keycloak became healthy, possibly before the panel had
# started, and the failure was hidden. Until that row exists, the panel's old
# sign-up route could hand the first admin account to anyone.
create_keycloak_admin() {
  info "Creating admin user in Keycloak..."

  # Generate or use provided admin password
  if [ -n "${ADMIN_PASSWORD:-}" ]; then
    info "Using admin password from ADMIN_PASSWORD environment variable"
  else
    ADMIN_PASSWORD="$(gen_secret_alnum 20)"
    info "Generated random admin password"
  fi

  # AI-2792: the owner's e-mail when one was given (resolve_admin_email).
  local admin_email="${ADMIN_EMAIL:-admin@${PANEL_DOMAIN}}"

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "kcadm.sh config credentials --server http://localhost:8180 --realm master --user admin (password in KC_CLI_PASSWORD, not argv)"
    dryrun "kcadm.sh create users -r aiadminpanel -s username=${admin_email} -s email=${admin_email} -s enabled=true -s emailVerified=true"
    dryrun "kcadm.sh set-password -r aiadminpanel --username ${admin_email} (password in KC_CLI_PASSWORD, not argv)"
    dryrun "Write admin password to ${SECRETS_DIR}/admin_password"
    return 0
  fi

  # Authenticate kcadm.sh against Keycloak master realm
  local kc_admin_pw
  kc_admin_pw=$(cat "${SECRETS_DIR}/keycloak_admin_password" 2>/dev/null || echo "")
  if [ -z "$kc_admin_pw" ]; then
    warn "Keycloak admin password not found at ${SECRETS_DIR}/keycloak_admin_password — cannot create admin user"
    return 1
  fi

  if ! retry_backoff "$KC_ADMIN_LOGIN_RETRY_DELAYS" "Keycloak admin login" \
    kcadm_with_password "$kc_admin_pw" config credentials \
    --server http://localhost:8180 --realm master --user admin 2>/dev/null; then
    warn "Failed to authenticate with Keycloak admin API — cannot create admin user"
    return 1
  fi
  debug "Authenticated with Keycloak admin API"

  # Create user in Keycloak (idempotent — ignore "already exists" errors)
  local kc_create_output
  kc_create_output=$(docker exec aiadminpanel_keycloak /opt/keycloak/bin/kcadm.sh create users \
    -r aiadminpanel \
    -s "username=${admin_email}" \
    -s "email=${admin_email}" \
    -s "enabled=true" \
    -s "emailVerified=true" 2>&1) || true

  local user_existed=false
  if grep -qi "conflict\|already exists" <<<"$kc_create_output"; then
    user_existed=true
    info "Keycloak user ${admin_email} already exists, updating password"
  else
    info "Created Keycloak user: ${admin_email}"
  fi

  # Set user password. AI-2530: the realm's passwordHistory(3) (AI-2521) makes
  # Keycloak refuse the password the account already has, so a re-run with the
  # same ADMIN_PASSWORD (say, after a half-failed install) is refused here.
  # When the account existed and secrets/admin_password holds this very
  # password, that refusal means "unchanged"; any other refusal stops.
  if kcadm_with_password "$ADMIN_PASSWORD" set-password \
    -r aiadminpanel --username "${admin_email}" 2>/dev/null; then
    info "Admin password set in Keycloak"
  elif [ "$user_existed" = true ] && [ -f "${SECRETS_DIR}/admin_password" ] &&
    [ "$(cat "${SECRETS_DIR}/admin_password")" = "$ADMIN_PASSWORD" ]; then
    info "Keycloak refused to set the same password again; admin password unchanged"
  else
    warn "Failed to set admin password in Keycloak"
    return 1
  fi

  # Save admin password to secrets
  echo -n "${ADMIN_PASSWORD}" > "${SECRETS_DIR}/admin_password"
  chmod 600 "${SECRETS_DIR}/admin_password"
  info "Admin password saved to ${SECRETS_DIR}/admin_password"

  info "Keycloak admin user created: ${admin_email}"
}

# ensure_panel_admin_row runs after wait_for_ready, so the panel's migrations
# have created the users table. It inserts the admin row, then reads it back;
# no row stops the install, because the firewall opens only after this step.
ensure_panel_admin_row() {
  local admin_email="${ADMIN_EMAIL:-admin@${PANEL_DOMAIN}}"
  info "Ensuring the admin user in the panel database..."

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "INSERT INTO users (...) VALUES (...) for ${admin_email}, give it the Owner role on the platform organization, then SELECT both back"
    return 0
  fi

  if ! docker exec aiadminpanel_postgresql psql -U aiadminpanel -d aiadminpanel -v ON_ERROR_STOP=1 -q -c \
    "INSERT INTO users (id, email, password_hash, role, totp_enabled, created_at, updated_at) \
     VALUES (gen_random_uuid(), '${admin_email}', 'keycloak-managed', 'admin', false, now(), now()) \
     ON CONFLICT (email) DO NOTHING;"; then
    error "Could not write the admin user to the panel database. Check: docker compose -f ${PANEL_DIR}/docker-compose.yml logs panel"
    return 1
  fi

  local found
  found=$(docker exec aiadminpanel_postgresql psql -U aiadminpanel -d aiadminpanel -tAc \
    "SELECT count(*) FROM users WHERE email = '${admin_email}' AND role = 'admin';" 2>/dev/null || echo 0)
  if [ "${found//[[:space:]]/}" != "1" ]; then
    error "The admin user is missing from the panel database after the insert; stopping before the firewall opens."
    return 1
  fi

  # AI-2675: a panel login without a role on the panel's platform organization
  # holds no permission, so the admin gets the built-in Owner role there. The
  # panel created that organization at start-up, before it reported ready. An
  # admin that already holds a role there (a re-run) keeps it.
  if ! docker exec aiadminpanel_postgresql psql -U aiadminpanel -d aiadminpanel -v ON_ERROR_STOP=1 -q -c \
    "INSERT INTO organization_members (user_id, organization_id, role_id) \
     SELECT u.id, o.id, r.id FROM users u \
     CROSS JOIN LATERAL (SELECT id FROM organizations WHERE org_type = 'platform' AND parent_id IS NULL ORDER BY created_at, id LIMIT 1) o \
     JOIN roles r ON r.is_default AND r.name = 'Owner' \
     WHERE u.email = '${admin_email}' AND NOT EXISTS ( \
       SELECT 1 FROM organization_members m JOIN organizations po ON po.id = m.organization_id \
       WHERE m.user_id = u.id AND po.org_type = 'platform' AND m.role_id IS NOT NULL);"; then
    error "Could not give the admin user the Owner role. Check: docker compose -f ${PANEL_DIR}/docker-compose.yml logs panel"
    return 1
  fi
  found=$(docker exec aiadminpanel_postgresql psql -U aiadminpanel -d aiadminpanel -tAc \
    "SELECT count(*) FROM organization_members m JOIN organizations o ON o.id = m.organization_id \
     JOIN users u ON u.id = m.user_id \
     WHERE u.email = '${admin_email}' AND o.org_type = 'platform' AND m.role_id IS NOT NULL;" 2>/dev/null || echo 0)
  if [ "${found//[[:space:]]/}" = "0" ] || [ -z "${found//[[:space:]]/}" ]; then
    error "The admin user holds no role on the panel's organization after the insert; stopping before the firewall opens."
    return 1
  fi
  info "Admin user ensured in panel database: ${admin_email}"
}

# ── Setup code (AI-1184) ─────────────────────────────────────────────────────
# The setup wizard accepts saves only from a browser that presents the setup
# code. It is written outside generate_env_file, which returns early whenever
# .env already exists (every re-run after a half-failed install).

ensure_setup_token() {
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "Create or reuse ${SECRETS_DIR}/setup_token (mode 600) and write SETUP_TOKEN_SHA256 to ${PANEL_DIR}/.env"
    return 0
  fi
  if ! setup_token_ensure "$SECRETS_DIR" "${PANEL_DIR}/.env"; then
    error "Could not prepare the setup code (see the message above)."
    exit 1
  fi
  info "Setup code ready at ${SECRETS_DIR}/setup_token (root-only)"
}

# setup_link → the link that opens the wizard with the setup code. The part
# after # never reaches the server or its logs.
setup_link() {
  local code
  code="$(cat "${SECRETS_DIR}/setup_token" 2>/dev/null || true)"
  [ -n "$code" ] || return 0
  printf 'https://%s/setup#token=%s\n' "${PANEL_DOMAIN:-localhost}" "$code"
}

# write_setup_link_file → the setup link, root-only (0600), at
# ${SECRETS_DIR}/setup_link (AI-2331). Written next to every printed or withheld
# link, so a piped or unattended install (cloud-init, Vultr Vendor Data, CI)
# can point at a file instead of putting the code into a log.
write_setup_link_file() {
  local link
  link="$(setup_link)"
  [ -n "$link" ] || return 0
  ( umask 077; printf '%s\n' "$link" >"${SECRETS_DIR}/setup_link.tmp" ) &&
    chmod 600 "${SECRETS_DIR}/setup_link.tmp" &&
    mv -f "${SECRETS_DIR}/setup_link.tmp" "${SECRETS_DIR}/setup_link" ||
    { rm -f "${SECRETS_DIR}/setup_link.tmp"; warn "Could not write ${SECRETS_DIR}/setup_link"; }
}

# credentials_on_screen → 0 only for an interactive install: stdout is a real
# terminal and --unattended is not set (AI-2331). Anything else may be a log
# (cloud-init-output.log, a marketplace app_install.log, a CI job), so the
# final screen prints where the root-only files are, never their values.
credentials_on_screen() {
  [ "${UNATTENDED:-false}" != "true" ] && [ -t 1 ]
}

# new_setup_token is --new-setup-token: replace the setup code on an existing
# install and restart only the panel. The installed compose file must already
# pass SETUP_TOKEN_SHA256 to the panel; only the updater refreshes that file.
new_setup_token() {
  local compose="${AAP_COMPOSE_FILE:-${PANEL_DIR}/docker-compose.yml}"
  if ! grep -q 'SETUP_TOKEN_SHA256' "$compose" 2>/dev/null; then
    error "This panel's ${compose} does not pass a setup code yet: update the panel first (Settings > Updates), then run --new-setup-token again."
    return 1
  fi
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "Write a new ${SECRETS_DIR}/setup_token (mode 600) and SETUP_TOKEN_SHA256 to ${PANEL_DIR}/.env"
    dryrun "docker compose -f ${compose} up -d --no-deps --force-recreate panel"
    return 0
  fi
  if [ -z "${PANEL_DOMAIN:-}" ]; then
    PANEL_DOMAIN="$(sed -n 's/^PANEL_DOMAIN=//p' "${PANEL_DIR}/.env" 2>/dev/null | head -1)"
  fi
  setup_token_rotate "$SECRETS_DIR" "${PANEL_DIR}/.env" || return 1
  run docker compose -f "$compose" --env-file "${PANEL_DIR}/.env" up -d --no-deps --force-recreate panel
  write_setup_link_file
  if credentials_on_screen; then
    info "New setup code written. Open this link to finish the setup wizard:"
    echo ""
    echo "  $(setup_link)"
    echo ""
  else
    info "New setup code written. The setup link is in ${SECRETS_DIR}/setup_link (root-only):"
    echo ""
    echo "  sudo cat ${SECRETS_DIR}/setup_link"
    echo ""
  fi
}

# ── Config Generation ─────────────────────────────────────────────────────────

generate_config() {
  local config_file="${CONFIG_DIR}/config.yaml"
  if [ -f "$config_file" ] && [ "$DRY_RUN" = "false" ]; then
    info "Config file already exists at ${config_file}, keeping existing"
    return 0
  fi

  info "Generating config file..."
  run bash -c "cat > '${config_file}'" << 'EOF'
# AI Admin Panel Configuration
# Generated by installer. Edit as needed.

server:
  port: 8080
  log_level: info

database:
  max_conns: 25
  min_conns: 5

metrics:
  prometheus_enabled: false
  collection_interval: 15s

notifications:
  categories:
    service_events: true
    ai_ops: true
    system_alerts: true
    security_events: true

updater:
  check_enabled: true
  check_interval: 24h
EOF
  run chmod 644 "$config_file"
  info "Config written to ${config_file}"
}

# ── LiteLLM Proxy Config ─────────────────────────────────────────────────────

# AI-381: docker-compose.yml bind-mounts ${PANEL_DIR}/litellm-config.yaml onto
# /app/config.yaml (read-only). If that source path does not exist as a regular
# file before `docker compose up`, Docker silently creates it as a *directory*,
# and litellm then crash-loops forever with
#   IsADirectoryError: [Errno 21] Is a directory: '/app/config.yaml'
# so this MUST write a regular file before deploy_stack brings litellm up.
#
# AI-622: the config content is RAM-gated — select_metered_model / render_litellm_config
# (bundled from scripts/lib/ai.sh) pick deepseek-r1:7b on capable boxes and
# llama3.2:3b on small ones. It is therefore GENERATED here, not downloaded: a
# single static asset cannot be box-aware, and the gateway must agree with what
# Ollama actually has pulled from first boot (no runtime config-reload path exists).
setup_litellm_config() {
  local litellm_config="${PANEL_DIR}/litellm-config.yaml"

  # Decide the model now so the config and the later auto-pull use the same tag.
  select_metered_model

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "Write ${litellm_config} (LiteLLM → Ollama ${METERED_OLLAMA_TAG}; ${METERED_TOTAL_MB}MB RAM)"
    return 0
  fi

  # Self-heal a prior broken state: if Docker (or an aborted run) left a
  # directory here, remove it — leaving it is the exact crash-loop trigger.
  if [ -d "$litellm_config" ]; then
    warn "Removing directory at ${litellm_config} (would crash-loop litellm — AI-381)"
    rm -rf "$litellm_config"
  fi

  if [ -f "$litellm_config" ]; then
    info "LiteLLM config already exists at ${litellm_config}, keeping existing"
    return 0
  fi

  if [ "$METERED_IS_FALLBACK" = "true" ]; then
    info "Detected ${METERED_TOTAL_MB}MB RAM (< ${AAP_METERED_MIN_MB_DEEPSEEK}MB): metered AI will run ${METERED_OLLAMA_TAG} (deepseek-r1:7b needs more RAM)."
  else
    info "Detected ${METERED_TOTAL_MB}MB RAM: metered AI will run ${METERED_OLLAMA_TAG}."
  fi

  render_litellm_config > "$litellm_config"
  chmod 644 "$litellm_config"
  info "LiteLLM config ready at ${litellm_config}"
}

# pull_metered_model (AI-622) — pull the RAM-gated model into the Ollama singleton
# so the first metered AI call works with no manual `ollama pull` (Simple-UX /
# no-terminal). select_metered_model already ran in setup_litellm_config, so
# METERED_OLLAMA_TAG matches the model the gateway config routes to.
#
# Non-fatal by design: a failed/slow pull must never abort the install — the
# panel still works and the operator can pull the model later from the AI Models
# page. Idempotent: re-pulling a model that is already present is a fast no-op.
pull_metered_model() {
  [ -n "${METERED_OLLAMA_TAG:-}" ] || select_metered_model

  # Escape hatch for air-gapped installs and CI (the installer matrix runs a full
  # unattended install and would otherwise download a multi-GB model per distro).
  # The RAM-gated config is already written; only the download is skipped.
  if [ "${AAP_SKIP_MODEL_PULL:-false}" = "true" ]; then
    info "AAP_SKIP_MODEL_PULL=true — skipping metered-model pull. Pull ${METERED_OLLAMA_TAG} from the AI Models page when ready."
    return 0
  fi

  # AI-2746: the engine starts on demand. Unless it was started at install
  # (AAP_INSTALL_OLLAMA=true) or already existed, there is nothing to pull
  # into, and waiting for it would only add two minutes to the install.
  if ! ollama_profile_enabled "${PANEL_DIR}/.env"; then
    info "The local AI engine starts on demand: it is downloaded and started when you pull your first local model (${METERED_OLLAMA_TAG}) on the AI Models page."
    return 0
  fi

  # AI-2492: never pull a model the engine's memory limit cannot hold. Loading
  # it would only get the engine's runner killed on every chat request.
  if ! metered_model_fits "${METERED_OLLAMA_TAG}"; then
    warn "${METERED_OLLAMA_TAG} needs about $(( $(metered_model_size_mb "${METERED_OLLAMA_TAG}") + AAP_OLLAMA_MODEL_MARGIN_MB )) MB and does not fit the model engine's memory limit of $(ollama_mem_limit_mb) MB; not pulling it. Choose a smaller model on the AI Models page."
    return 0
  fi

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "docker exec aiadminpanel_ollama ollama pull ${METERED_OLLAMA_TAG}"
    return 0
  fi

  # Wait for the Ollama singleton to answer (deploy_stack started it with a 30s
  # healthcheck start_period). `ollama list` is the same probe compose uses.
  local attempt=0
  while [ "$attempt" -lt 60 ]; do
    if docker exec aiadminpanel_ollama ollama list >/dev/null 2>&1; then
      break
    fi
    attempt=$((attempt + 1))
    sleep 2
  done
  if [ "$attempt" -ge 60 ]; then
    warn "Ollama not ready after 120s; skipping the metered-model pull. Pull ${METERED_OLLAMA_TAG} later from the AI Models page."
    return 0
  fi

  info "Pulling metered model ${METERED_OLLAMA_TAG} into Ollama (one-time, may take a few minutes)..."
  if docker exec aiadminpanel_ollama ollama pull "${METERED_OLLAMA_TAG}"; then
    info "Metered model ${METERED_OLLAMA_TAG} is ready."
  else
    warn "Could not pull ${METERED_OLLAMA_TAG} now (network?). Metered AI will 404 until it is pulled from the AI Models page."
  fi
}

# ── Environment File Generation ──────────────────────────────────────────────

generate_env_file() {
  local env_file="${PANEL_DIR}/.env"
  info "Generating environment file for docker-compose..."

  # Idempotency: don't overwrite existing .env (secrets/tokens may differ)
  if [ -f "$env_file" ] && [ "$DRY_RUN" = "false" ]; then
    info "Environment file already exists at ${env_file}, keeping existing"
    # AI-2218: a re-run with UPGRADE_URL set changes only that line; without
    # it, the value already in .env stays.
    if [ -n "${UPGRADE_URL:-}" ]; then
      env_set "$env_file" UPGRADE_URL "$UPGRADE_URL"
      info "Upgrade button link set to ${UPGRADE_URL}"
    fi
    return 0
  fi

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "Write ${env_file} with PANEL_DOMAIN, ACME_EMAIL, ADMIN_EMAIL, PANEL_VERSION"
    [ -n "${UPGRADE_URL:-}" ] && dryrun "Write UPGRADE_URL=${UPGRADE_URL} to ${env_file}"
    dryrun "Write CERT_RESOLVER=$(tls_cert_resolver) (TLS_MODE=${TLS_MODE:-letsencrypt}) to ${env_file}"
    dryrun "Write Keycloak OIDC vars to ${env_file}"
    dryrun "Write PANEL_INTERNAL_URL=http://aiadminpanel_panel:8080 to ${env_file}"
    [ "${AAP_NVIDIA_RUNTIME_READY:-false}" = "true" ] &&
      dryrun "Write panel GPU visibility (PANEL_RUNTIME=nvidia, NVIDIA_VISIBLE_DEVICES=all) to ${env_file}"
    # (No managed-domain dry-run narration: a --dry-run never runs md_acquire_domain,
    # so MD_CLAIMED is always false here — the real keys are narrated by the claim
    # path itself when it actually claims.)
    return 0
  fi

  cat > "$env_file" <<ENVEOF
# AI Admin Panel - Docker Compose Environment
# Generated by install.sh. Edit as needed.
PANEL_DOMAIN=${PANEL_DOMAIN}
ACME_EMAIL=${ACME_EMAIL}
# AI-2792: the admin account's e-mail and sign-in name at install time. The
# panel pre-fills it on the sign-in page; a re-run of the installer keeps it.
ADMIN_EMAIL=${ADMIN_EMAIL:-admin@${PANEL_DOMAIN}}
PANEL_VERSION=${PANEL_VERSION}
GOMEMLIMIT=${GOMEMLIMIT:-off}
# AI-425: Traefik certresolver the panel/keycloak routers use. TLS_MODE=letsencrypt-dns
# selects the DNS-01 resolver (letsencrypt-dns) so TLS works with :80 closed;
# otherwise HTTP-01 (letsencrypt). docker-compose.yml reads this.
CERT_RESOLVER=$(tls_cert_resolver)
# AI-2293: how this panel was installed (anonymous telemetry, when it is on).
AAP_INSTALL_METHOD=installer
# To stop anonymous telemetry for good, uncomment the next line and run
# docker compose up -d panel (see docs: Privacy & Telemetry).
# DO_NOT_TRACK=1
ENVEOF

  # Optional variables -- only include if set
  # CF_DNS_API_TOKEN: with the DNS-01 bridge below, only the panel reads it
  # (until a token is saved in Settings → DNS); Traefik reads it only when
  # DNS01_PROVIDER is cloudflare (AI-2289, deprecated).
  if [ -n "${CF_DNS_API_TOKEN:-}" ]; then
    echo "CF_DNS_API_TOKEN=${CF_DNS_API_TOKEN}" >> "$env_file"
  fi

  # AI-2295: Traefik answers DNS-01 challenges through the panel's bridge
  # (lego httpreq) with this per-install secret (lib/secrets.sh). Only a new
  # .env gets it; an existing one keeps Traefik's Cloudflare provider. Without
  # the secret file the install goes on in that older mode.
  local bridge_secret
  bridge_secret=$(cat "${SECRETS_DIR}/dns01_bridge_secret" 2>/dev/null || echo "")
  if [ -n "$bridge_secret" ]; then
    echo "DNS01_PROVIDER=httpreq" >> "$env_file"
    echo "DNS01_BRIDGE_SECRET=${bridge_secret}" >> "$env_file"
  else
    warn "No DNS-01 bridge secret at ${SECRETS_DIR}/dns01_bridge_secret: Traefik keeps its own Cloudflare provider (CF_DNS_API_TOKEN) for DNS-01."
  fi

  if [ -n "${LICENSE_KEY:-}" ]; then
    echo "LICENSE_KEY=${LICENSE_KEY}" >> "$env_file"
  fi

  # AI-2218: the hosting provider's buy page (validated by check_upgrade_url).
  if [ -n "${UPGRADE_URL:-}" ]; then
    echo "UPGRADE_URL=${UPGRADE_URL}" >> "$env_file"
  fi

  # AI-244 Phase 2: license proxy at license.aiadminpanel.com.
  # Customer panels never see the keygen.sh admin token — the proxy holds
  # it server-side. LICENSE_SERVER_URL can be overridden in advance (e.g.
  # for staging or a self-hosted proxy) by exporting it before install.
  echo "LICENSE_SERVER_URL=${LICENSE_SERVER_URL:-https://license.aiadminpanel.com}" >> "$env_file"

  # Managed temporary domain (AI-544 plan 2): mark the install as managed and
  # record which claim service issued the domain, so the panel backend (plan 3)
  # can renew the lease against the same service (a staging-claimed box must
  # renew against staging). BYO-domain installs get neither key.
  if [ "${MD_CLAIMED:-false}" = "true" ]; then
    echo "MANAGED_DOMAIN=true" >> "$env_file"
    echo "MANAGED_DNS_URL=${MD_BASE_URL}" >> "$env_file"
  fi

  # Public URLs (used for browser redirects and OIDC callbacks)
  echo "PANEL_URL=https://${PANEL_DOMAIN}" >> "$env_file"
  echo "FRONTEND_URL=https://${PANEL_DOMAIN}" >> "$env_file"
  echo "PANEL_HOSTNAME=${PANEL_DOMAIN}" >> "$env_file"
  echo "PANEL_SERVICE_DOMAIN=${PANEL_DOMAIN}" >> "$env_file"
  # AI-832: the proxy and the AI gateway have a leg in tenant networks, where a
  # tenant container can answer a short Compose service name. They reach their
  # own dependencies by container name (here and in LITELLM_DATABASE_URL below).
  echo "PANEL_INTERNAL_URL=http://aiadminpanel_panel:8080" >> "$env_file"

  # Keycloak OIDC configuration
  echo "OIDC_DISCOVERY_URL=https://auth.${PANEL_DOMAIN}/realms/aiadminpanel/.well-known/openid-configuration" >> "$env_file"
  echo "OIDC_CLIENT_ID=panel-backend" >> "$env_file"
  echo "OIDC_REDIRECT_URI=https://${PANEL_DOMAIN}/api/v1/auth/oidc/callback" >> "$env_file"
  echo "KEYCLOAK_URL=http://keycloak:8180" >> "$env_file"
  echo "KEYCLOAK_REALM=aiadminpanel" >> "$env_file"
  echo "KEYCLOAK_ADMIN_USER=admin" >> "$env_file"
  echo "KEYCLOAK_HOSTNAME=auth.${PANEL_DOMAIN}" >> "$env_file"

  # Read secrets and write to .env (Keycloak doesn't support _FILE env vars)
  local db_pw kc_pw
  db_pw=$(cat "${SECRETS_DIR}/db_password" 2>/dev/null || echo "")
  kc_pw=$(cat "${SECRETS_DIR}/keycloak_admin_password" 2>/dev/null || echo "")
  echo "KC_DB_PASSWORD=${db_pw}" >> "$env_file"
  echo "KEYCLOAK_ADMIN_PASSWORD=${kc_pw}" >> "$env_file"

  # Per-install LiteLLM master key (lib/secrets.sh generated it — no shared
  # sk-litellm-master-key default reaching the litellm + panel containers).
  # AI-592: fail loud on empty. docker-compose.yml now requires this env var
  # (${LITELLM_MASTER_KEY:?...}) instead of falling back to the well-known
  # default, so writing nothing here would leave the AI gateway unstartable.
  # generate_secrets always creates the file, so an empty value here means the
  # secret is missing/unreadable — a real error, not a silent skip.
  local litellm_key
  litellm_key=$(cat "${SECRETS_DIR}/litellm_master_key" 2>/dev/null || echo "")
  if [ -z "$litellm_key" ]; then
    error "LITELLM_MASTER_KEY secret is missing or empty (${SECRETS_DIR}/litellm_master_key). The AI gateway will not start on a default key — re-run the installer to regenerate secrets."
  fi
  echo "LITELLM_MASTER_KEY=${litellm_key}" >> "$env_file"

  # 3a-2: LiteLLM DATABASE_URL — same postgres role as the panel/keycloak
  # (P1). db_password is alnum-only (secrets.sh gen_secret_alnum) → URL-safe.
  local litellm_db_password
  litellm_db_password=$(cat "${SECRETS_DIR}/db_password" 2>/dev/null || echo "")
  if [ -z "$litellm_db_password" ]; then
    error "db_password secret is missing or empty — cannot build LITELLM_DATABASE_URL"
  fi
  echo "LITELLM_DATABASE_URL=postgresql://aiadminpanel:${litellm_db_password}@aiadminpanel_postgresql:5432/litellm" >> "$env_file"

  # AI-1144: record the model the installer pulls, so the panel's "Local AI"
  # deploy source names a model this box has (lib/ai.sh is the one source).
  local_ai_model_env_block >> "$env_file"
  # AI-2492: the bundled model engine's memory limit, sized from host RAM.
  ollama_mem_limit_env_block >> "$env_file"
  # AI-2746: the engine starts on demand unless the operator asked for it now.
  if [ "${AAP_INSTALL_OLLAMA:-false}" = "true" ]; then
    add_ollama_profile "$env_file"
  fi

  # Install-bundled Provider AI (§6.6 / AI-447). Only written when the operator
  # exported a key — absent → no Provider AI seeded, panel stays sovereign by
  # default. The panel encrypts the key into the DB on first boot and never logs
  # it; we only persist it here so docker-compose can forward it to the panel
  # container (Rule 11: no real-key default, fail soft when unset).
  if [ -n "${AAP_PROVIDER_AI_API_KEY:-}" ]; then
    echo "AAP_PROVIDER_AI_API_KEY=${AAP_PROVIDER_AI_API_KEY}" >> "$env_file"
    [ -n "${AAP_PROVIDER_AI_BASE_URL:-}" ] && echo "AAP_PROVIDER_AI_BASE_URL=${AAP_PROVIDER_AI_BASE_URL}" >> "$env_file"
    [ -n "${AAP_PROVIDER_AI_MODEL:-}" ] && echo "AAP_PROVIDER_AI_MODEL=${AAP_PROVIDER_AI_MODEL}" >> "$env_file"
    [ -n "${AAP_PROVIDER_AI_PROVIDER_TYPE:-}" ] && echo "AAP_PROVIDER_AI_PROVIDER_TYPE=${AAP_PROVIDER_AI_PROVIDER_TYPE}" >> "$env_file"
  fi

  # Give the panel container its own GPU visibility when the installer configured
  # Docker's nvidia runtime (AI-420 opt 1). Emits nothing on CPU-only hosts, so
  # docker-compose.yml's runc/void defaults keep the panel container unchanged.
  nvidia_panel_env_block >> "$env_file"

  chmod 600 "$env_file"
  # Re-assert restrictive perms on the secrets dir + .env (self-healing).
  harden_perms "${SECRETS_DIR}" "$env_file"
  info "Environment file written to ${env_file}"
}

# generate_ollama_gpu_override — write (or remove) the GPU compose overlay that
# gives the bundled Ollama the host GPU (AI-428). On a GPU host
# (AAP_NVIDIA_RUNTIME_READY=true) ollama_gpu_override_yaml emits the reservation
# and we persist it to docker-compose.gpu.yml, which deploy_stack merges with an
# extra `-f`. On a CPU host it emits nothing, so we REMOVE any stale overlay —
# otherwise a box that lost its GPU (driver removed, card pulled) would keep an
# unconditional nvidia reservation and `docker compose up` would fail. Idempotent:
# safe to re-run on every install/upgrade, so an already-installed GPU box that
# re-runs the installer/updater gains the GPU (the AI-428 upgrade path).
generate_ollama_gpu_override() {
  local gpu_file="${PANEL_DIR}/docker-compose.gpu.yml"
  local yaml
  yaml="$(ollama_gpu_override_yaml)"

  if [ "$DRY_RUN" = "true" ]; then
    if [ -n "$yaml" ]; then
      dryrun "Write ${gpu_file} giving the bundled Ollama the host GPU (NVIDIA runtime detected)"
    elif [ -f "$gpu_file" ]; then
      dryrun "Remove stale GPU overlay ${gpu_file} (CPU-only host)"
    fi
    return 0
  fi

  if [ -n "$yaml" ]; then
    printf '%s\n' "$yaml" > "$gpu_file"
    chmod 644 "$gpu_file"
    info "Wrote GPU overlay ${gpu_file} — the bundled Ollama will use the host GPU."
  elif [ -f "$gpu_file" ]; then
    rm -f "$gpu_file"
    info "Removed stale GPU overlay (CPU-only host) — the bundled Ollama stays CPU."
  fi
}

# ── Docker Compose Deployment ─────────────────────────────────────────────────

deploy_infra() {
  info "Starting infrastructure services (PostgreSQL must be healthy before Keycloak DB setup)..."

  local compose_file="${PANEL_DIR}/docker-compose.yml"

  if [ ! -f "$compose_file" ]; then
    # Need to download compose file first — delegate to deploy_stack's download logic
    deploy_stack_download_compose
  fi

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "docker compose up -d postgresql valkey traefik"
    return 0
  fi

  local -a pull=()
  if baked_server; then pull=(--pull never); fi
  run docker compose -f "$compose_file" up -d "${pull[@]}" postgresql valkey traefik
  info "Waiting for PostgreSQL to be healthy..."
  local attempt=0
  while [ "$attempt" -lt 30 ]; do
    local health
    health=$(docker inspect --format='{{.State.Health.Status}}' aiadminpanel_postgresql 2>/dev/null || echo "unknown")
    if [ "$health" = "healthy" ]; then
      info "PostgreSQL is healthy"
      return 0
    fi
    attempt=$((attempt + 1))
    sleep 1
  done
  warn "PostgreSQL did not become healthy within 30s"
}

deploy_stack_download_compose() {
  local compose_file="${PANEL_DIR}/docker-compose.yml"
  [ -f "$compose_file" ] && return 0

  info "Downloading docker-compose.yml..."
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "curl -fsSL ${RELEASE_ASSET_BASE}/docker-compose.yml -o ${compose_file}"
    return 0
  fi

  if fetch_release_asset docker-compose.yml "$compose_file"; then
    info "Downloaded docker-compose.yml from ${RELEASE_ASSET_BASE}"
  else
    error "Could not download ${RELEASE_ASSET_BASE}/docker-compose.yml. Check network connectivity and retry. (A pinned PANEL_VERSION never falls back to the latest Compose file.)"
  fi
}

# keep_existing_ollama (AI-2746) — the bundled Ollama is on demand (Compose
# profile "ollama"). On a server where it already exists, put the profile in
# .env before any `docker compose` call, so a re-run keeps pulling and
# recreating it like before. Without the line Compose would leave the old
# container running but never update it.
keep_existing_ollama() {
  local env_file="${PANEL_DIR}/.env"
  [ -f "$env_file" ] || return 0
  ollama_profile_enabled "$env_file" && return 0
  docker inspect aiadminpanel_ollama >/dev/null 2>&1 || return 0
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "Add COMPOSE_PROFILES=ollama to ${env_file} (the local AI engine already exists)"
    return 0
  fi
  add_ollama_profile "$env_file" && info "The local AI engine already exists on this server; keeping it (COMPOSE_PROFILES=ollama in ${env_file})."
}

deploy_stack() {
  info "Deploying full panel stack..."

  local compose_file="${PANEL_DIR}/docker-compose.yml"
  keep_existing_ollama

  # AI-428: the installer pins -f explicitly, so docker-compose.override.yml is
  # NOT auto-merged — the GPU overlay must be named here to take effect.
  # generate_ollama_gpu_override (run before us) wrote docker-compose.gpu.yml iff
  # this is an NVIDIA host; on a CPU host the file is absent and we deploy the
  # CPU-only base. This is the ONLY full `up` that (re)creates ollama — the
  # updater/per-session deploys use `up --no-deps panel`, so they never revert it.
  local -a compose_files=(-f "$compose_file")
  if [ -f "${PANEL_DIR}/docker-compose.gpu.yml" ]; then
    compose_files+=(-f "${PANEL_DIR}/docker-compose.gpu.yml")
    info "GPU overlay present — deploying the bundled Ollama with host-GPU access."
  fi

  # AI-2747: a baked server (install.sh --bake) already holds every image the
  # Compose file names, recorded in the bake marker. Its first boot pulls
  # nothing: no 12 GB download, and no other image than the one baked.
  local -a pull=()
  if baked_server; then
    pull=(--pull never)
    info "Baked image: starting the images already on disk (no pull)."
  fi

  # Check if existing installation (upgrade path)
  if [ -f "$compose_file" ] && docker compose "${compose_files[@]}" ps --status running -q 2>/dev/null | grep -q .; then
    info "Existing installation detected -- performing upgrade"
    baked_server || run docker compose "${compose_files[@]}" pull
    run docker compose "${compose_files[@]}" up -d --remove-orphans "${pull[@]}"
    return 0
  fi

  # Ensure compose file exists (downloaded by deploy_infra or here)
  deploy_stack_download_compose

  run docker compose "${compose_files[@]}" up -d "${pull[@]}"
  info "Stack deployed"
}

# baked_server → 0 when install.sh --bake prepared this server: its bake
# marker exists (AI-2745). A normal install never writes one.
baked_server() { [ -f "${CONFIG_DIR}/baked.json" ]; }

# ── Readiness Wait ────────────────────────────────────────────────────────────

# panel_page_has PATH TEXT → true when the panel answers PATH (inside its own
# container: its port is not published to the host) and the reply contains
# TEXT. The reply is read in full before it is searched (AI-2201): piping it
# into `grep -q` let grep stop at the first match while docker was still
# writing, docker died of SIGPIPE, and `set -o pipefail` turned a healthy panel
# into a failed check about one install in twenty.
panel_page_has() {
  local body
  body="$(docker exec aiadminpanel_panel wget -qO- "http://localhost:8080$1" 2>/dev/null)" || return 1
  case "$body" in
    *"$2"*) return 0 ;;
  esac
  return 1
}

wait_for_ready() {
  local max_attempts=60
  local attempt=0

  info "Waiting for panel to become ready (up to 60s)..."

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "poll panel healthcheck up to ${max_attempts}s"
    return 0
  fi

  while [ "$attempt" -lt "$max_attempts" ]; do
    if panel_page_has /healthz '"status":"ok"'; then
      info "Panel is ready"
      return 0
    fi
    attempt=$((attempt + 1))
    sleep 1
  done

  warn "Panel did not become ready within 60s. Check logs with: docker compose -f ${PANEL_DIR}/docker-compose.yml logs panel"
  return 1
}

# ── Smoke Tests ───────────────────────────────────────────────────────────────

smoke_tests() {
  info "Running post-install smoke tests..."

  local all_pass=true

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "curl -f http://localhost/healthz"
    dryrun "curl -f http://localhost/readyz"
    dryrun "curl -f http://localhost/"
    return 0
  fi

  # Test healthz (via docker exec — panel port not exposed to host)
  if panel_page_has /healthz '"status":"ok"'; then
    info "[PASS] /healthz returns 200 with status ok"
  else
    warn "[FAIL] /healthz did not return expected response"
    all_pass=false
  fi

  # Test frontend (via docker exec)
  if panel_page_has / "html"; then
    info "[PASS] Frontend is serving HTML"
  else
    warn "[FAIL] Frontend did not return HTML"
    all_pass=false
  fi

  if [ "$all_pass" = "false" ]; then
    warn "Some smoke tests failed. Check container logs:"
    warn "  docker compose -f ${PANEL_DIR}/docker-compose.yml logs"
    return 1
  fi

  info "All smoke tests passed"
}

# ── Security Baselines ────────────────────────────────────────────────────────

run_security_baselines() {
  local baselines_script
  baselines_script="$(dirname "$0")/security-baselines.sh"

  if [ -f "$baselines_script" ]; then
    info "Applying security baselines..."
    local dry_arg=""
    [ "$DRY_RUN" = "true" ] && dry_arg="--dry-run"
    run bash "$baselines_script" $dry_arg
  else
    warn "Security baselines script not found at ${baselines_script} -- skipping"
  fi
}

# ── Print Success ─────────────────────────────────────────────────────────────

print_success() {
  local domain="${PANEL_DOMAIN:-localhost}"
  local PASSWORD_LINE
  # AI-2792 (one way in): the signed-in admin opens the setup wizard, so the
  # screen no longer prints the setup link. The setup code is still written
  # (and ${SECRETS_DIR}/setup_link with it) because the panel accepts it for
  # one more release; DEPRECATED, remove with the server side.
  write_setup_link_file
  # AI-2331: the password only on an interactive terminal; a piped or
  # unattended run (cloud-init, marketplace scripts, CI) gets its root-only file.
  if credentials_on_screen; then
    PASSWORD_LINE="${ADMIN_PASSWORD:-<not set>}"
  else
    PASSWORD_LINE="sudo cat ${SECRETS_DIR}/admin_password"
  fi
  # AI-2792: the address the admin account was created with.
  local SIGNIN_EMAIL="${ADMIN_EMAIL:-admin@${domain}}" EMAIL_NOTE=""
  if [ "${ADMIN_EMAIL_FALLBACK:-false}" = true ] || [ -z "${ADMIN_EMAIL:-}" ]; then
    EMAIL_NOTE="
                  (the setup wizard asks for your own e-mail and moves
                  the sign-in to it; set ADMIN_EMAIL to skip that)"
  fi
  local elapsed_secs=$(( $(date +%s) - INSTALL_START ))
  local elapsed_min=$(( elapsed_secs / 60 ))
  local elapsed_sec=$(( elapsed_secs % 60 ))
  local ELAPSED_DISPLAY="${elapsed_min}m ${elapsed_sec}s"
  cat <<EOF

${COLOR_GREEN}${COLOR_BOLD}===========================================================
  AI Admin Panel installed successfully!
===========================================================${COLOR_RESET}

  Panel URL:      https://${domain}
  Sign-in e-mail: ${SIGNIN_EMAIL}${EMAIL_NOTE}
  Admin password: ${PASSWORD_LINE}
  Health check:   https://${domain}/healthz
  API docs:       https://${domain}/api/docs

  Configuration:  ${CONFIG_DIR}/config.yaml
  Credentials:    ${SECRETS_DIR}/admin_password
  Logs:           ${LOG_DIR}/install.log

  To check status:
    docker compose -f ${PANEL_DIR}/docker-compose.yml ps

  To view logs:
    docker compose -f ${PANEL_DIR}/docker-compose.yml logs -f panel

  Next steps:
  1. Open the panel URL above and sign in with the sign-in e-mail and the
     admin password above. The setup wizard opens next; when you finish it,
     you land on the dashboard.
  2. Configure notifications in Settings > Notifications

  Lost the admin password? On this server, run:
    sudo docker compose -f ${PANEL_DIR}/docker-compose.yml exec -e ADMIN_EMAIL=<sign-in e-mail> panel panel reset-password

  Elapsed time:  ${ELAPSED_DISPLAY}

${COLOR_GREEN}${COLOR_BOLD}===========================================================${COLOR_RESET}
EOF

  print_openbao_recovery_key

  if [ "${MD_CLAIMED:-false}" = "true" ]; then
    cat <<EOF
${COLOR_YELLOW}${COLOR_BOLD}  Temporary domain notice${COLOR_RESET}
  ${domain} is a free temporary domain with a 7-day provisional lease
  (expires ${MD_LEASE_EXPIRES:-in 7 days} unless verified). Verify your email in the
  panel to keep it. The claim token at ${SECRETS_DIR}/managed_domain_token
  (root-only) is what renews the lease — do not delete it.

EOF
  fi
}

# ── OpenBao unseal key at rest (AI-2146) ────────────────────────────────────
# A new install encrypts the unseal key with systemd-creds (TPM2 + host key when
# the host has a TPM2, the host key only otherwise) once OpenBao runs, proves
# OpenBao unseals from the memory copy, and only then deletes the clear key.
# print_success shows the recovery key once. Existing installs are not touched:
# their owner runs `aap-openbao-key protect`. Hosts without systemd-creds 250+
# (Ubuntu 22.04) keep the clear key, with a warning. A failure here never stops
# the install: the tool puts OpenBao back on the clear key first.
OPENBAO_KEY_NEW=false
OPENBAO_KEY_PROTECTED=false
protect_openbao_key() {
  local tool="${PANEL_DIR}/aap-openbao-key.sh"
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "${tool} protect --yes (new installs only: encrypt the OpenBao unseal key with systemd-creds, recreate OpenBao on the /run copy, delete the clear key)"
    return 0
  fi
  if [ "$OPENBAO_KEY_NEW" != "true" ]; then
    info "Existing unseal key left as it is. To encrypt it at rest: aap-openbao-key protect"
    return 0
  fi
  if [ ! -x "$tool" ]; then
    warn "The unseal key tool is not installed (no systemd); the OpenBao unseal key stays in clear at ${SECRETS_DIR}/openbao_unseal_key."
    return 0
  fi
  local out rc=0
  out="$(env PANEL_DIR="$PANEL_DIR" "$tool" protect --yes 2>&1)" || rc=$?
  [ -z "$out" ] || printf '%s\n' "$out" | sed 's/^/  unseal key: /'
  if [ "$rc" -eq 0 ]; then
    OPENBAO_KEY_PROTECTED=true
    info "OpenBao unseal key encrypted at rest ($(cat "${SECRETS_DIR}/openbao_unseal_key.mode" 2>/dev/null || echo host))."
  else
    warn "The OpenBao unseal key stays in clear at ${SECRETS_DIR}/openbao_unseal_key (see the lines above). Protect the host as you protect customer data."
  fi
}

# print_openbao_recovery_key — the recovery key, once, on the final screen.
# Only to a terminal: a piped or logged install (CI, cloud-init) must not put
# the key into a log; it gets the command to print it instead.
print_openbao_recovery_key() {
  [ "$OPENBAO_KEY_PROTECTED" = "true" ] || return 0
  local mode
  mode="$(cat "${SECRETS_DIR}/openbao_unseal_key.mode" 2>/dev/null || echo host)"
  cat <<EOF
${COLOR_YELLOW}${COLOR_BOLD}  OpenBao recovery key${COLOR_RESET}
  The vault's unseal key is now encrypted for this host only (${mode}).
  If this server is lost, only the recovery key opens your vault backups.
  Store it offline now (password manager or paper), not on this server.
EOF
  if [ "$mode" = "host" ]; then
    cat <<EOF
  Partial protection: this host has no TPM2, so a copy of ${PANEL_DIR} cannot
  open the vault, but a full-disk copy or provider snapshot still can.
EOF
  fi
  if [ -t 1 ]; then
    printf '\n  Recovery key: '
    "${PANEL_DIR}/aap-openbao-key.sh" export 2>/dev/null || echo "(could not print it; run: aap-openbao-key export)"
    echo ""
  else
    printf '\n  Print it with: aap-openbao-key export   (as root, on this server)\n\n'
  fi
}

# ── Host updater (AI-431 2B) ────────────────────────────────────────────────
# Installs scripts/aap-update.sh + the systemd path/oneshot units that apply
# one-click updates AS ROOT. The update path needs no docker.sock in a
# container: this host unit is the only actor that swaps the panel. (The panel
# and Traefik containers do mount the Docker socket, for deploying services and
# for routing; that is separate from updates.) Idempotent:
# re-running only rewrites files whose content changed; `enable` is a no-op when
# already enabled. The script + units are embedded into this installer at build
# time (build-installer.sh), so a fresh install always ships a working updater.

#
# AI-1471: a changed file is written next to its destination and renamed over
# it, never rewritten in place. bash reads a running script as it goes, so an
# in-place rewrite under a running update or backup made it run a mix of two
# versions. A rename leaves the running copy's file intact, and replaces a link
# at the destination instead of writing through it.
_write_if_changed() {
  local dest="$1" content="$2" mode="$3" tmp
  if [ -f "$dest" ] && [ ! -L "$dest" ] && [ "$(cat "$dest")" = "$content" ]; then
    debug "Unchanged: $dest"
    chmod "$mode" "$dest"
    return 0
  fi
  tmp="$(mktemp "$(dirname "$dest")/.$(basename "$dest").XXXXXX")" || { warn "Could not write $dest"; return 1; }
  if printf '%s\n' "$content" > "$tmp" && chmod "$mode" "$tmp" && mv -fT "$tmp" "$dest"; then
    info "Wrote: $dest"
  else
    rm -f "$tmp"
    warn "Could not write $dest"
    return 1
  fi
}

# install_updater_marker <installed updater> — update/updater.json for the panel
# UI (AI-1471): {"selfRefresh":1,"sha256":"<hex of that script>"}, the same file
# a self-refreshing updater writes. A hint, never a security gate. Built in the
# root-only work area and renamed into place, so a link planted in update/ is
# replaced, not followed. An updater without the self-refresh marker line gets
# no file, and a stale one is removed so it cannot claim otherwise.
install_updater_marker() {
  local script="$1" update_dir="${PANEL_DIR}/update" work_dir="${PANEL_DIR}/.update-work" tmp sha
  if ! grep -qx 'UPDATER_SELF_REFRESH=1' "$script" 2>/dev/null; then
    rm -f "${update_dir}/updater.json"
    return 0
  fi
  sha="$(sha256sum "$script" | cut -d' ' -f1)"
  if [ -L "$work_dir" ] || ! mkdir -p "$work_dir" "$update_dir" || ! chmod 700 "$work_dir" \
      || ! tmp="$(mktemp "${work_dir}/marker.XXXXXX")"; then
    warn "Could not write ${update_dir}/updater.json"
    return 0
  fi
  if printf '{"selfRefresh":1,"sha256":"%s"}\n' "$sha" > "$tmp" && chmod 644 "$tmp" \
      && mv -fT "$tmp" "${update_dir}/updater.json"; then
    info "Wrote: ${update_dir}/updater.json"
  else
    rm -f "$tmp"
    warn "Could not write ${update_dir}/updater.json"
  fi
}

# The updater script needs cosign (verify-or-refuse) and jq + curl (GHCR tag
# query + request/result parsing). curl/flock are part of the Docker install;
# cosign and jq are not, so fetch them as distro-independent static binaries.
# cosign is pinned to the version the release pipeline signs with (v2.5.2,
# `cosign-release` in .github/workflows/release.yml): the updater has to read
# the manifest signature bundle that version writes (AI-1185).
ensure_updater_deps() {
  local arch
  case "$(uname -m)" in
    x86_64|amd64)  arch=amd64 ;;
    aarch64|arm64) arch=arm64 ;;
    *)             arch=amd64 ;;
  esac
  if ! command -v cosign >/dev/null 2>&1; then
    info "Installing cosign (image signature verification)..."
    if run curl -fsSL "https://github.com/sigstore/cosign/releases/download/v2.5.2/cosign-linux-${arch}" -o /usr/local/bin/cosign; then
      run chmod 755 /usr/local/bin/cosign
    else
      warn "Could not download cosign — one-click updates will refuse to apply (fail-closed) until it is installed."
    fi
  fi
  ensure_jq
}

# jq: the updater parses update requests with it, and the Docker address-pool
# merge (AI-1446) edits daemon.json with it.
# Already downloaded counts too: under sudo on Rocky/Alma, /usr/local/bin is
# not on PATH, and lib/docker.sh aap_find_jq looks there by absolute path.
ensure_jq() {
  aap_find_jq >/dev/null && return 0
  local arch
  case "$(uname -m)" in
    x86_64|amd64)  arch=amd64 ;;
    aarch64|arm64) arch=arm64 ;;
    *)             arch=amd64 ;;
  esac
  info "Installing jq..."
  if run curl -fsSL "https://github.com/jqlang/jq/releases/download/jq-1.7.1/jq-linux-${arch}" -o /usr/local/bin/jq; then
    run chmod 755 /usr/local/bin/jq
  else
    warn "Could not download jq — one-click updates need it to parse update requests, and the Docker address-pool merge needs it to edit daemon.json."
  fi
}

install_host_updater() {
  info "Installing host updater (systemd path + oneshot)..."
  local script_dest="${PANEL_DIR}/aap-update.sh"
  # SYSTEMD_UNIT_DIR exists for tests (a temporary root); hosts use the default.
  local unit_dir="${SYSTEMD_UNIT_DIR:-/etc/systemd/system}"
  local path_unit="${unit_dir}/aap-updater.path"
  local service_unit="${unit_dir}/aap-updater.service"
  # AI-1345: root's command to close the old secret format for one kind of
  # secret before the next update does it automatically.
  local close_dest="${PANEL_DIR}/close-legacy-secret-format.sh"

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "ensure cosign+jq; write ${script_dest} (755) + ${close_dest} (700) + ${path_unit} + ${service_unit}, each by rename; systemctl daemon-reload; systemctl enable --now aap-updater.path; write ${PANEL_DIR}/update/updater.json; remove ${PANEL_DIR}/.update-work/updater-release"
    install_host_backup
    return 0
  fi

  ensure_updater_deps

  if ! command -v systemctl >/dev/null 2>&1; then
    warn "systemd not found — skipping host updater install. One-click updates from the panel will be inert on this host."
    return 0
  fi

  _write_if_changed "$script_dest"  "$(_aap_update_script)"          755
  _write_if_changed "$close_dest"   "$(_aap_embed_close_legacy)"     700
  _write_if_changed "$path_unit"    "$(_aap_updater_path_unit)"      644
  _write_if_changed "$service_unit" "$(_aap_updater_service_unit)"   644

  # AI-1471: the updater keeps the release it was last refreshed to here, as
  # the floor below which it never installs an older updater. This installer
  # does not know which release it was published with, so the record goes and
  # the floor falls back to the running panel's release.
  rm -f "${PANEL_DIR}/.update-work/updater-release"
  install_updater_marker "$script_dest"

  systemctl daemon-reload
  if systemctl enable --now aap-updater.path >/dev/null 2>&1; then
    info "Host updater active — watching ${PANEL_DIR}/update/request.json"
  else
    warn "Could not enable aap-updater.path; one-click updates will be inert until it is enabled."
  fi

  install_host_backup
}

# ── Nightly backup set (AI-925) ─────────────────────────────────────────────
# Installs backup-databases.sh (the entry point), backup-openbao.sh (the vault
# step) and restore-openbao.sh next to the updater, and a systemd timer that
# runs the backup daily at 03:00 host time. Each run writes one root-only set:
# a cold copy of the OpenBao volume, both database dumps and a manifest that
# names the unseal key by fingerprint only. Shipped with the updater so that
# --refresh-updater brings it to an existing install. Idempotent like the
# updater: unchanged files are left alone; enable is a no-op when enabled.
install_host_backup() {
  # SYSTEMD_UNIT_DIR exists for tests (a temporary root); hosts use the default.
  local unit_dir="${SYSTEMD_UNIT_DIR:-/etc/systemd/system}"
  local backup_unit="${unit_dir}/aap-backup.service"
  local timer_unit="${unit_dir}/aap-backup.timer"

  if [ "$DRY_RUN" = "true" ]; then
    if [ "$INSTALL_PHASE" = bake ]; then
      dryrun "write ${PANEL_DIR}/backup-databases.sh, ${PANEL_DIR}/backup-openbao.sh, ${PANEL_DIR}/restore-openbao.sh, ${PANEL_DIR}/aap-openbao-key.sh (700) + ${backup_unit} + ${timer_unit} + ${unit_dir}/aap-openbao-key.service; link /usr/local/sbin/aap-openbao-key; systemctl daemon-reload (bake: aap-backup.timer stays off until the first boot)"
    else
      dryrun "write ${PANEL_DIR}/backup-databases.sh, ${PANEL_DIR}/backup-openbao.sh, ${PANEL_DIR}/restore-openbao.sh, ${PANEL_DIR}/aap-openbao-key.sh (700) + ${backup_unit} + ${timer_unit} + ${unit_dir}/aap-openbao-key.service; link /usr/local/sbin/aap-openbao-key; systemctl daemon-reload; systemctl enable --now aap-backup.timer"
    fi
    return 0
  fi
  if ! command -v systemctl >/dev/null 2>&1; then
    warn "systemd not found — skipping the nightly backup timer. Run ${PANEL_DIR}/backup-databases.sh daily yourself."
    return 0
  fi

  _write_if_changed "${PANEL_DIR}/backup-databases.sh" "$(_aap_embed_backup_databases)" 700
  _write_if_changed "${PANEL_DIR}/backup-openbao.sh"   "$(_aap_embed_backup_openbao)"   700
  _write_if_changed "${PANEL_DIR}/restore-openbao.sh"  "$(_aap_embed_restore_openbao)"  700
  _write_if_changed "$backup_unit" "$(_aap_embed_backup_service)" 644
  _write_if_changed "$timer_unit"  "$(_aap_embed_backup_timer)"   644
  # AI-2146: the unseal key tool and its boot unit. Shipped here so that
  # --refresh-updater brings `aap-openbao-key protect` to an existing install.
  # The unit is enabled only by `protect` (or `import`), never here.
  _write_if_changed "${PANEL_DIR}/aap-openbao-key.sh" "$(_aap_embed_openbao_key)" 700
  _write_if_changed "${unit_dir}/aap-openbao-key.service" "$(_aap_embed_openbao_key_service)" 644
  if [ -d /usr/local/sbin ] && [ -z "${SYSTEMD_UNIT_DIR:-}" ]; then
    ln -sfn "${PANEL_DIR}/aap-openbao-key.sh" /usr/local/sbin/aap-openbao-key 2>/dev/null || true
  fi
  # AI-2745: a bake writes the files and stops here. The key status file
  # (update/openbao-key.json) describes this server's key, and a backup timer
  # on an image with no stack only produces failures (spec 1.3 item 20, 2.1).
  # The first boot runs this again (first_boot_step_backups, AI-2747), which
  # turns the timer on and writes the status file.
  if [ "$INSTALL_PHASE" = bake ]; then
    systemctl daemon-reload
    info "Nightly backup files written; aap-backup.timer is turned on at the first boot."
    return 0
  fi
  # Tell the panel how the key is kept (update/openbao-key.json); read-only.
  env PANEL_DIR="$PANEL_DIR" "${PANEL_DIR}/aap-openbao-key.sh" status >/dev/null 2>&1 || true

  systemctl daemon-reload
  if systemctl enable --now aap-backup.timer >/dev/null 2>&1; then
    info "Nightly backup active — sets in ${PANEL_DIR}/backups (aap-backup.timer, 03:00 host time)"
  else
    warn "Could not enable aap-backup.timer; nothing backs up the vault until it is enabled."
  fi
}

# Container egress guard (AI-1104): a root script that keeps containers off the
# cloud metadata addresses and tenant containers off the host's own ports, with
# a oneshot service (also run when Docker starts) and a 5-minute timer that put
# the rules back after a reboot or a firewall reload. Applied once here, then
# the timer is started, so the installer and the timer never run it at once.
# Without systemd nothing is installed: rules applied once would vanish at the
# next reboot, and the panel logs "tenant egress guard not active" instead.
install_egress_guard() {
  info "Installing the container egress guard (host firewall)..."
  local script_dest="${PANEL_DIR}/aap-egress-guard.sh"
  local service_unit="/etc/systemd/system/aap-egress-guard.service"
  local timer_unit="/etc/systemd/system/aap-egress-guard.timer"

  if [ "$DRY_RUN" = "true" ]; then
    dryrun "write ${script_dest} (755) + ${service_unit} + ${timer_unit}; systemctl daemon-reload; ${script_dest} apply; systemctl enable aap-egress-guard.service; systemctl enable --now aap-egress-guard.timer"
    info "Tenant host-port allow-list: AAP_EGRESS_GUARD_TENANT_HOST_PORTS in ${PANEL_DIR}/.env. Empty means customer apps cannot reach a model server on this host; to allow Ollama, add AAP_EGRESS_GUARD_TENANT_HOST_PORTS=\"11434\" and run ${script_dest} apply."
    return 0
  fi

  if ! command -v systemctl >/dev/null 2>&1; then
    warn "systemd not found — skipping the container egress guard. Containers can reach cloud metadata addresses and this host's ports; the panel logs 'tenant egress guard not active'."
    return 0
  fi

  _write_if_changed "$script_dest"  "$(_aap_egress_guard_script)"       755
  _write_if_changed "$service_unit" "$(_aap_egress_guard_service_unit)" 644
  _write_if_changed "$timer_unit"   "$(_aap_egress_guard_timer_unit)"   644

  systemctl daemon-reload
  # Its output is shown: it names platform endpoints it re-attached and why a
  # run failed.
  local rc=0 out
  out="$("$script_dest" apply 2>&1)" || rc=$?
  [ -z "$out" ] || printf '%s\n' "$out" | sed 's/^/  egress guard: /'

  case "$rc" in
    0) info "Container egress guard active." ;;
    3)
      warn "Container egress guard is unsupported here (no DOCKER-USER chain, or Docker older than 28 for the host-port rule); see the lines above. The dashboard shows this."
      docker_host_rule_check
      ;;
    *) warn "Container egress guard did not apply (exit ${rc}); see '${script_dest} status'. The timer retries every 5 minutes." ;;
  esac
  # Say what customer apps may reach on this host, and how to change it.
  # The plan is captured whole before it is searched: a reader that stops at
  # the first match (grep -m1) closes the pipe while plan still writes, and
  # under pipefail that SIGPIPE (exit 141) ended the installer (CI, AI-1104).
  local plan_out allow_list="" line
  plan_out="$("$script_dest" plan 2>/dev/null)" || true
  while IFS= read -r line; do
    case "$line" in
      *"tenant host-port allow-list"*) allow_list="${line#\# }"; break ;;
    esac
  done <<<"$plan_out"
  [ -z "$allow_list" ] || info "Container egress guard: ${allow_list}"
  systemctl enable aap-egress-guard.service >/dev/null 2>&1 \
    || warn "Could not enable aap-egress-guard.service; the guard then waits for its timer after a reboot."
  systemctl enable --now aap-egress-guard.timer >/dev/null 2>&1 \
    || warn "Could not enable aap-egress-guard.timer; the guard will not be re-applied after a reboot until it is enabled."
}

# The functions below emit the embedded payloads. build-installer.sh
# replaces each @MARKER@ line with the verbatim contents of the repo source of
# truth (scripts/aap-update.sh, scripts/systemd/aap-updater.{path,service},
# scripts/aap-egress-guard.sh, scripts/systemd/aap-egress-guard.{service,timer}).
_aap_update_script() {
  cat <<'AAP_UPDATE_SCRIPT_EOF'
#!/usr/bin/env bash
#
# aap-update.sh — AI Admin Panel host updater (AI-431 Slice 2B).
#
# The PANEL decides; this script EXECUTES. The unprivileged panel container
# writes ${PANEL_DIR}/update/request.json (target tag derived from its own
# cached status — never a client-supplied value). A host systemd path-unit
# notices the file and runs THIS script as root. It then:
#
#   validate target → verify the release's signed manifest and every file it
#   will install against it (AI-1185) → pg_dump backup (retain 3) →
#   cosign-verify the target image → install the release's Compose file and
#   missing host files → switch platform host names to container names (AI-832)
#   → set PANEL_VERSION in .env (in place) → pull the verified image digest +
#   recreate → poll /healthz → success, or auto-rollback to the prior version.
#
# It writes the terminal state to ${PANEL_DIR}/update/result.json, which the
# panel polls via GET /system/update/result to drive the UI.
#
# aap-update.sh --reapply (run by the operator, as root) needs no request: it
# takes the release that is RUNNING as the target and brings the host to that
# release's Compose file, with the same backup and signature gates. This is how
# a current install gets a host change it missed, above all the forwarding pin
# (AI-832). It pulls no image and leaves PANEL_VERSION alone; it fails, and
# says why, when the running release cannot be worked out, when that release's
# Compose file cannot be fetched, when PANEL_VERSION names another release
# than the one running, or when a platform container still forwards packets
# afterwards. The panel offers the same thing without a shell:
# Settings → Updates → "Apply again" requests the version already installed.
# Both are refused for a release from before release manifests (up to
# LAST_RELEASE_WITHOUT_MANIFEST): there is nothing signed to apply.
#
# SECURITY (Product Principle #2 — secure & sovereign):
#   * verify-or-refuse: the target image MUST carry a valid cosign signature
#     produced by OUR release pipeline (keyless, GitHub Actions OIDC), in the
#     release run of exactly the target version. An unsigned or wrongly-signed
#     image is refused and nothing is swapped. This is fail-closed and has no
#     bypass. The digest that was verified is the digest that is pulled.
#   * the same for everything else a release brings (AI-1185): the Compose file
#     and the host files it mounts are installed only when their SHA-256 is the
#     one named in the release's manifest, and the manifest only counts when it
#     is signed by the release run of exactly that version. A release newer
#     than LAST_RELEASE_WITHOUT_MANIFEST without a valid manifest is refused.
#     No bypass, and no fallback to the bucket's main-tracking copies.
#   * The update path needs no docker.sock in a container: this host unit is
#     the only actor that swaps the panel. (The panel and Traefik containers do
#     mount the Docker socket, for deploying services and for routing; that is
#     separate from updates and not changed here.)
#   * The panel container can write to update/, so that folder is treated as
#     untrusted input: the request is first renamed into a root-only work area
#     outside it (AI-2443) and read only when the claimed entry is a small
#     regular file with a well-formed target; the lock, every download and the
#     half-written result live in that work area too.
#
# SELF-REFRESH (AI-1471). A release is applied by its own updater. When the
# target's signed manifest names aap-update.sh and both systemd units, this
# script (stage 1) checks them against the manifest, probes the new script,
# swaps all three in by rename (keeping its own copies), runs the new script
# as a child with --stage2 and waits. Stage 2 does the whole update as above.
# If stage 2 does not report success for this run, stage 1 puts its own files
# back. The updater is never replaced by one from an older release. Spec:
# docs/specs/2026-10-14-ai-1471-updater-self-refresh.md.
#
# Hermetic test: scripts/tests/aap-update.bats stubs docker/cosign/crane/curl
# and systemctl.

set -uo pipefail

# ── Configuration (overridable via environment) ──────────────────────────────
PANEL_DIR="${PANEL_DIR:-/opt/aiadminpanel}"
UPDATE_DIR="${PANEL_DIR}/update"
BACKUP_DIR="${PANEL_DIR}/backups"
ENV_FILE="${PANEL_DIR}/.env"
COMPOSE_FILE="${COMPOSE_FILE:-${PANEL_DIR}/docker-compose.yml}"
REQUEST_FILE="${UPDATE_DIR}/request.json"
RESULT_FILE="${UPDATE_DIR}/result.json"
# The updater's own work area: its lock, the downloads of this run (the manifest
# and every file checked against it) and the result while it is being written.
# Under PANEL_DIR, not under update/, and mode 0700: the panel container can
# write to update/, and a fixed file name there is something it could replace
# with a link, or swap after the file was verified.
WORK_DIR="${PANEL_DIR}/.update-work"
STAGE_DIR="${WORK_DIR}/stage"
LOCK_FILE="${WORK_DIR}/lock"
# The panel's request once claimed (AI-2443, see claim_request), and its limit.
CLAIMED_REQUEST="${WORK_DIR}/request.json"
REQUEST_LIMIT=4096
# AI-2746: the panel asks for the on-demand local AI engine with this file and
# reads the outcome from the other (see start_ollama_engine). The request
# carries nothing the updater reads: only its presence counts.
OLLAMA_REQUEST_FILE="${UPDATE_DIR}/ollama-request.json"
OLLAMA_RESULT_FILE="${UPDATE_DIR}/ollama-result.json"

REGISTRY_HOST="${REGISTRY_HOST:-ghcr.io}"
IMAGE_PATH="${IMAGE_PATH:-aiadminpanel/ai-admin-panel}"
REGISTRY="${PANEL_IMAGE:-${REGISTRY_HOST}/${IMAGE_PATH}}"
PANEL_CONTAINER="${PANEL_CONTAINER:-aiadminpanel_panel}"
PG_CONTAINER="${PG_CONTAINER:-aiadminpanel_postgresql}"
OLLAMA_CONTAINER="${OLLAMA_CONTAINER:-aiadminpanel_ollama}"
TRAEFIK_CONTAINER="${TRAEFIK_CONTAINER:-aiadminpanel_traefik}"
LITELLM_CONTAINER="${LITELLM_CONTAINER:-aiadminpanel_litellm}"
# Valkey major move (AI-2657, see snapshot_valkey_before_major): the panel's
# Valkey, the one-off container that rewrites its data for the older major on a
# rollback, and how long that one may take to load the file.
VALKEY_CONTAINER="${VALKEY_CONTAINER:-aiadminpanel_valkey}"
VALKEY_ROLLBACK_CONTAINER="${VALKEY_ROLLBACK_CONTAINER:-aiadminpanel_valkey_rollback}"
VALKEY_LOAD_TIMEOUT="${VALKEY_LOAD_TIMEOUT:-60}"
GATEWAY_CONFIG="${GATEWAY_CONFIG:-${PANEL_DIR}/litellm-config.yaml}"
PG_USER="${PG_USER:-aiadminpanel}"
PG_DB="${PG_DB:-aiadminpanel}"
# Keycloak's database on the same Postgres (docker-compose.yml KC_DB_URL_DATABASE).
PG_KEYCLOAK_DB="${PG_KEYCLOAK_DB:-keycloak}"
# The AI gateway's database on the same Postgres (.env LITELLM_DATABASE_URL, AI-2221).
PG_LITELLM_DB="${PG_LITELLM_DB:-litellm}"

# Keyless cosign identity of OUR release pipeline. Confirmed against the signed
# v2.6.0 image: subject .../release.yml@refs/tags/vX.Y.Z, issuer below.
#
# The image and the manifest of a release must both be signed by the release
# run of exactly that release: <workflow>@refs/tags/v<version>. Until AI-1185
# the image check was a pattern that accepted the workflow on ANY ref, so an
# older, validly signed image published under a new tag passed.
COSIGN_CERT_OIDC_ISSUER="${COSIGN_CERT_OIDC_ISSUER:-https://token.actions.githubusercontent.com}"
RELEASE_WORKFLOW_IDENTITY="${RELEASE_WORKFLOW_IDENTITY:-https://github.com/aiadminpanel/ai-admin-panel/.github/workflows/release.yml}"

# The newest release published WITHOUT a signed manifest (AI-1185). Releases up
# to and including it never get one: updating to one installs the image only.
# Every newer release must carry a valid manifest or is refused. The line is
# fixed here, in a root-owned file, on purpose: if "no manifest in the bucket"
# alone meant "old release", deleting a manifest would reopen the unsigned path.
LAST_RELEASE_WITHOUT_MANIFEST="${LAST_RELEASE_WITHOUT_MANIFEST:-2.14.3}"

# ── Self-refresh (AI-1471) ────────────────────────────────────────────────────
# This line is a fixed marker: release checks read it from a tag's copy of this
# script to know that the updater of that release refreshes itself.
UPDATER_SELF_REFRESH=1
# The first release whose updater refreshes itself. Fixed here for the same
# reason as LAST_RELEASE_WITHOUT_MANIFEST: from it on, a manifest that names no
# updater is refused instead of applied with the old one, so deleting the
# entries cannot reopen that path. It is also the lowest updater release this
# updater will ever install. The placeholder 999.0.0 keeps both rules, and so
# the whole swap, switched off until the release PR of that release sets its
# own number. Nothing enforces that yet: slice 4 of AI-1471 adds the check to
# release-preflight.sh. Until then F stays 999.0.0 and no host swaps.
FIRST_SELF_REFRESH_RELEASE="${FIRST_SELF_REFRESH_RELEASE:-999.0.0}"
# Where the installed updater and its units live. Overridable for the tests.
UPDATER_PATH="${UPDATER_PATH:-${PANEL_DIR}/aap-update.sh}"
UPDATER_UNIT_DIR="${UPDATER_UNIT_DIR:-/etc/systemd/system}"
# The names the release publishes them under, in the order they are swapped.
UPDATER_FILES=(aap-update.sh aap-updater.service aap-updater.path)
# Root-only records in the work area: the previous updater, the release of the
# installed one (the downgrade floor) and stage 2's result for stage 1. The
# panel container cannot write here; it mounts only update/.
UPDATER_PREV_DIR="${WORK_DIR}/updater-prev"
UNIT_PREV_DIR="${UPDATER_UNIT_DIR}/.aap-updater-prev"
UPDATER_RELEASE_FILE="${WORK_DIR}/updater-release"
STAGE2_RESULT="${WORK_DIR}/stage2-result.json"
# A hint for the panel UI (never a security gate): this updater refreshes
# itself, and which script is installed.
UPDATER_MARKER="${UPDATE_DIR}/updater.json"

HEALTH_CHECK_TIMEOUT="${HEALTH_CHECK_TIMEOUT:-120}"
HEALTH_CHECK_INTERVAL="${HEALTH_CHECK_INTERVAL:-3}"
BACKUP_RETAIN="${BACKUP_RETAIN:-3}"

# PostgreSQL major upgrade (AI-2653, see upgrade_postgres_major). The containers
# that hold connections to the panel's Postgres and are stopped while it is
# dumped, and the name of the one-off container that rebuilds the cluster.
PG_CLIENT_CONTAINERS="${PG_CLIENT_CONTAINERS:-aiadminpanel_panel aiadminpanel_keycloak aiadminpanel_litellm}"
PG_UPGRADE_CONTAINER="${PG_UPGRADE_CONTAINER:-aiadminpanel_pg_upgrade}"
PG_SECRET_FILE="${PG_SECRET_FILE:-${PANEL_DIR}/secrets/db_password}"
PG_UPGRADE_STATE="${WORK_DIR}/pg-upgrade.state"
# Free space the upgrade needs on the data volume beyond twice the databases'
# size (the old cluster stays until the operator removes it), in KiB.
PG_UPGRADE_MARGIN_KB="${PG_UPGRADE_MARGIN_KB:-524288}"

# Asset source for compose reconciliation (AI-746).
#
# Two keys live under this host and they are NOT interchangeable:
#   ${GET_BASE}/v<version>/<name> — published once, at release, and never rewritten
#   ${GET_BASE}/<name>        — tracks main; a daily self-heal keeps it at HEAD
#
# Only the VERSIONED key is ever read. The unversioned one can serve a compose
# newer than the image being installed, and no manifest covers it (AI-1185).
#
# GitHub release assets are deliberately NOT used, despite being the obvious
# versioned source: this repository is PRIVATE, so every unauthenticated
# releases/download/... fetch answers 404 — verified against v2.11.0, which has
# docker-compose.yml genuinely attached. A box has no GitHub credentials and must
# not be given any, so R2 is the only channel it can actually read.
GET_BASE="${GET_BASE:-https://get.aiadminpanel.com}"

# Host paths docker-compose.yml bind-mounts, and how to obtain each if a box
# does not have it yet. Compose creates a DIRECTORY at any absent bind-mount
# path, so a service whose file is missing starts broken — which is why a naive
# compose refresh would be worse than none at all.
#
#   asset:<name>:<mode>  published release file, fetched, checked against the
#                        manifest and chmod'ed
#   tar:<name>           published tarball, checked against the manifest and
#                        extracted under PANEL_DIR
#   mkdir                just needs to exist (Traefik's ACME store)
#   local                rendered by the installer and published nowhere; if it
#                        is absent we must refuse, never guess
#   local-sealed:<rel>   like local, but present enough when <rel> exists:
#                        a protected box keeps the OpenBao unseal key only
#                        encrypted (secrets/openbao_unseal_key.cred) and compose
#                        mounts its memory copy instead (AI-2146)
#   secretfile:<name>:<mode>
#                        a compose file secret whose empty file is a valid,
#                        safe value: created empty with <mode> if absent, never
#                        touched if present (AI-1345)
#
# scripts/tests/aap-update.bats asserts this table covers every bind mount and
# every file secret in docker-compose.yml, so a new one cannot be added without
# landing here. Compose refuses to start a service whose file secret is absent.
HOST_ASSETS=(
  "openbao/config|local"
  "openbao/openbao-log-rotate.sh|asset:openbao-log-rotate.sh:755"
  "keycloak-realm-export.json|asset:keycloak-realm-export.json:644"
  "keycloak-theme|tar:keycloak-theme.tar.gz"
  "litellm-config.yaml|asset:litellm-config.yaml:644"
  "letsencrypt|mkdir"
  "secrets/master_key|local"
  "secrets/db_password|local"
  "secrets/keycloak_admin_password|local"
  "secrets/managed_domain_token|secretfile:managed_domain_token:600"
  "secrets/openbao_unseal_key|local-sealed:secrets/openbao_unseal_key.cred"
  "secrets/legacy_closed|secretfile:legacy_closed:600"
)

# AI-1345: the marker file listing the kinds of stored secret that refuse the
# old encryption format. Only root on the host writes it; the panel reads it.
LEGACY_CLOSED_REL="secrets/legacy_closed"

# ── State (initialized so `set -u` is satisfied on every code path) ───────────
TARGET_TAG=""
ASSET_TAG=""
CHANNEL="stable"
CURRENT=""
PREV_VERSION=""
BACKUP_PATH=""
STARTED_AT=""
FAIL_REASON=""
HOLD_LOCK=0
RESULT_WRITTEN=0
COMPOSE_CHANGED=0
COMPOSE_BACKUP=""
COMPOSE_ARGS=()
PLATFORM_HOSTS_CHANGED=0
OLLAMA_LIMIT_CHANGED=0
# 1 while this run starts the on-demand engine instead of updating (AI-2746).
ENGINE_RUN=0
ENGINE_RESULT_WRITTEN=0
REAPPLY=0
MANIFEST_RELEASE=0
MANIFEST_FILE=""
IMAGE_DIGEST=""
STAGED_COMPOSE=""
STAGED_ASSETS=()
STAGED_THEME=""
THEME_CHANGED=0
VALKEY_SNAPSHOT=""
VALKEY_OLD_IMAGE=""
VALKEY_VOLUME=""
VALKEY_FROM=""
VALKEY_TO=""
STAGE2=0
RUN_ID=""
RESULT_EXTRA='{}'
UPDATER_SWAPPED=0
PATH_UNIT_CHANGED=0
PG_UPGRADE_FROM=""
PG_UPGRADE_TO=""
PG_UPGRADE_IMAGE=""
PG_UPGRADE_VOLUME=""
PG_UPGRADE_DIR=""
PG_UPGRADE_STARTED=0

log() { echo "[$(date -u '+%Y-%m-%dT%H:%M:%SZ')] [aap-update] $*"; }
now() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }

# run_logged <command...> — run quietly; when it fails, put the last lines of
# what it printed in the log (the journal) before returning its exit code. The
# v2.15.0 upgrade from 2.14.3 rolled back on a missing file secret, and the
# journal said only "pulling or recreating the new image failed": Docker's own
# answer had gone to /dev/null (AI-1470). The result's reason stays the
# canonical string the panel translates; the detail is for the operator.
run_logged() {
  local out rc
  out="$("$@" 2>&1)" && return 0
  rc=$?
  log "'$1 ${2:-}' failed (exit ${rc}); its output ends:"
  printf '%s\n' "$out" | tail -n 20 | while IFS= read -r line; do log "  ${line}"; done
  return "$rc"
}

# ── Terminal result + cleanup ─────────────────────────────────────────────────

# write_result STATUS [REASON] — overwrite result.json with the terminal state.
# Compact JSON (no spaces) so it is trivially greppable and small.
#
# jq builds it, so a quote or a backslash in any value is escaped instead of
# ending the string. It is written in the work area and renamed into update/:
# a rename replaces whatever sits at result.json, where writing to a fixed
# temporary name in update/ would follow a link planted there.
#
# `mv -T` (GNU coreutils) is what makes it a rename in every case. Without it,
# mv treats a result.json that is a folder, or a link to one, as "move the file
# INTO that folder": root would write wherever the panel container pointed the
# link, and the panel would never get its result. With -T a link is replaced
# like any other name, and a real folder is refused instead of filled.
#
# AI-1471: a stage 2 run adds its run id and first keeps the same JSON in the
# root-only work area, where stage 1 reads it: update/ is the panel's to write.
# RESULT_EXTRA (a JSON object) is merged in; stage 1 adds updaterRestored.
write_result() {
  local status="$1" reason="${2:-}" new_version rolled finished tmp
  finished="$(now)"
  case "$status" in
    succeeded)   new_version="$TARGET_TAG"; rolled="false" ;;
    rolled-back) new_version="$PREV_VERSION"; rolled="true" ;;
    *)           new_version="$PREV_VERSION"; rolled="false" ;;
  esac
  mkdir -p "$UPDATE_DIR"
  tmp="$(mktemp "${WORK_DIR}/result.XXXXXX")" || { log "could not write the result: no work area at ${WORK_DIR}"; return 1; }
  if ! jq -cn \
      --arg status "$status" --arg targetTag "$TARGET_TAG" --arg fromVersion "$PREV_VERSION" \
      --arg newVersion "$new_version" --argjson rolledBack "$rolled" --arg reason "$reason" \
      --arg backupPath "$BACKUP_PATH" --arg startedAt "$STARTED_AT" --arg finishedAt "$finished" \
      --arg runId "$RUN_ID" --argjson extra "$RESULT_EXTRA" \
      '{status: $status, targetTag: $targetTag, fromVersion: $fromVersion, newVersion: $newVersion, rolledBack: $rolledBack, reason: $reason, backupPath: $backupPath, startedAt: $startedAt, finishedAt: $finishedAt}
       + (if $runId == "" then {} else {runId: $runId} end) + $extra' \
      > "$tmp"; then
    rm -f "$tmp"
    log "could not write the result (${status}${reason:+: $reason})"
    return 1
  fi
  if [ "$STAGE2" = "1" ] && ! keep_stage2_result "$tmp"; then
    log "could not keep this run's result for stage 1 at ${STAGE2_RESULT}"
  fi
  publish_result "$tmp" || { log "(${status}${reason:+: $reason})"; return 1; }
  RESULT_WRITTEN=1
  log "result: $status${reason:+ — $reason}"
}

# publish_result <file> — put a finished result file from the work area in
# place as update/result.json, by rename (see write_result).
publish_result() {
  local tmp="$1"
  # The panel runs as an ordinary user and reads this file.
  chmod 644 "$tmp"
  if ! mv -fT "$tmp" "$RESULT_FILE" 2>/dev/null; then
    rm -f "$tmp"
    log "could not put the result in place at ${RESULT_FILE}"
    return 1
  fi
}

# keep_stage2_result <file> — a root-only copy (mode 600) for stage 1.
keep_stage2_result() {
  local copy
  copy="$(mktemp "${WORK_DIR}/stage2.XXXXXX")" || return 1
  if ! cat "$1" > "$copy" || ! mv -fT "$copy" "$STAGE2_RESULT"; then
    rm -f "$copy"
    return 1
  fi
}

finish_failed()   { write_result "failed" "$1"; }
finish_rollback() { write_result "rolled-back" "$1"; }
# A succeeded run may carry a note: what the operator still has to do.
finish_ok()       { write_result "succeeded" "${1:-}"; }

# Always leave a terminal result and consume the request — but only if we are
# the instance holding the lock (never disturb another run's files).
cleanup() {
  local rc=$?
  # AI-2746: an engine run has its own request and result. An update request
  # that arrived meanwhile is the next run's, and result.json reports updates.
  if [ "$ENGINE_RUN" = "1" ]; then
    if [ "$HOLD_LOCK" = "1" ] && [ "$ENGINE_RESULT_WRITTEN" != "1" ]; then
      write_ollama_result "failed" "the host updater exited unexpectedly (rc=${rc})"
    fi
    return
  fi
  if [ "$HOLD_LOCK" = "1" ]; then
    if [ "$RESULT_WRITTEN" != "1" ]; then
      write_result "failed" "updater exited unexpectedly (rc=${rc})"
    fi
    rm -rf "$STAGE_DIR"
    # A --reapply run was not started by a request; one that is waiting
    # belongs to the run the path unit starts for it.
    [ "$REAPPLY" = "1" ] || rm -f "$REQUEST_FILE"
    rm -f "$CLAIMED_REQUEST"
    if [ "$UPDATER_SWAPPED" = "1" ]; then
      # Name the script that is installed now: B's, or A's own after a restore.
      write_updater_marker
      # daemon-reload does not change the watch of a running .path unit. Only
      # now, with the request gone, can a restart not fire it during this run.
      if [ "$PATH_UNIT_CHANGED" = "1" ] && ! systemctl restart aap-updater.path >/dev/null 2>&1; then
        log "WARNING: could not restart aap-updater.path; it watches with its previous definition until the next reboot"
      fi
    fi
  fi
}
trap cleanup EXIT

# ── Steps ─────────────────────────────────────────────────────────────────────

acquire_lock() {
  [ "$STAGE2" = "1" ] && { adopt_lock; return; }
  mkdir -p "$UPDATE_DIR"
  # PANEL_DIR belongs to root. A work area that is a link is not ours.
  if [ -L "$WORK_DIR" ] || ! mkdir -p "$WORK_DIR" || ! chmod 700 "$WORK_DIR"; then
    log "cannot use the updater's work area ${WORK_DIR}"
    exit 1
  fi
  exec 9>"$LOCK_FILE"
  # The nightly backup (backup-databases.sh, AI-925) takes this same lock while
  # it stops OpenBao for a few seconds. Wait for it rather than give up: a
  # request dropped here stays in update/ and no run would pick it up.
  # A retry loop, not `flock -w`: BusyBox flock (the CI test image) has no -w.
  local waited=0
  until flock -n 9; do
    if [ "$waited" -ge "${UPDATE_LOCK_WAIT:-600}" ]; then
      log "another update is already running; leaving its state untouched"
      exit 0
    fi
    sleep 1
    waited=$((waited + 1))
  done
  HOLD_LOCK=1
}

# adopt_lock — stage 2 (AI-1471) runs under the lock stage 1 took, on the fd 9
# it inherited, and never opens its own. It checks both halves, because
# `flock -n 9` alone succeeds on any file nobody has locked: fd 9 must be the
# lock file (same device and inode), and a fresh open of the lock file must be
# refused (someone holds it). Otherwise it exits without touching anything, so
# a stage 2 started by hand cannot run unlocked.
adopt_lock() {
  local fd lockf
  if [ -L "$WORK_DIR" ] || [ ! -d "$WORK_DIR" ] || [ ! -f "$LOCK_FILE" ]; then
    log "stage 2 refused: no updater work area or lock at ${WORK_DIR}"
    exit 1
  fi
  fd="$(stat -L -c '%d:%i' /proc/self/fd/9 2>/dev/null)"
  lockf="$(stat -c '%d:%i' "$LOCK_FILE" 2>/dev/null)"
  if [ -z "$fd" ] || [ "$fd" != "$lockf" ]; then
    log "stage 2 refused: file descriptor 9 is not the updater's lock"
    exit 1
  fi
  if flock -n "$LOCK_FILE" true 2>/dev/null; then
    log "stage 2 refused: the updater's lock is not held"
    exit 1
  fi
  if ! [[ "${AAP_UPDATE_RUN_ID:-}" =~ ^[0-9a-f]{32}$ ]]; then
    log "stage 2 refused: no valid run id"
    exit 1
  fi
  RUN_ID="$AAP_UPDATE_RUN_ID"
  HOLD_LOCK=1
}

# claim_request — move update/request.json into the root-only work area before
# anything looks at it (AI-2443). update/ is the panel's to write: a check on
# that path followed by reads of it is a race in which the panel swaps in a
# FIFO (the updater hangs) or a link (root parses a file the panel chose). A
# rename moves the entry itself, never what it points to, and after it the
# panel cannot change what is read. Stage 2 acts on the copy stage 1 claimed.
claim_request() {
  if [ "$STAGE2" = "1" ] && [ -f "$CLAIMED_REQUEST" ] && [ ! -L "$CLAIMED_REQUEST" ]; then
    return 0
  fi
  rm -rf -- "$CLAIMED_REQUEST"
  if [ ! -e "$REQUEST_FILE" ] && [ ! -L "$REQUEST_FILE" ]; then
    FAIL_REASON="no update request found"
    return 1
  fi
  # Across filesystems mv copies instead of renaming: the one-link check would
  # then prove nothing and a huge file would be copied in full. The request is
  # removed (unlink, never followed), so the path unit does not fire again.
  if [ "$(stat -c %d -- "$WORK_DIR" 2>/dev/null)" != "$(stat -c %d -- "$UPDATE_DIR" 2>/dev/null)" ]; then
    rm -f -- "$REQUEST_FILE"
    FAIL_REASON="the updater's work area ${WORK_DIR} is not on the same filesystem as ${UPDATE_DIR}; the request was removed unread"
    return 1
  fi
  if ! mv -T -- "$REQUEST_FILE" "$CLAIMED_REQUEST" 2>/dev/null; then
    FAIL_REASON="no update request found"
    [ ! -e "$REQUEST_FILE" ] && [ ! -L "$REQUEST_FILE" ] || FAIL_REASON="could not claim request.json"
    return 1
  fi
}

# recover_interrupted_run — a claimed request still in the work area when stage
# 1 starts (under the lock, so no other run holds it) is what a run left that
# died before its cleanup: power loss, reboot, OOM kill. update/request.json is
# gone by then, so nothing would fire again, and result.json would stay
# "in-progress", which makes the panel refuse every later update. The run is
# not resumed (PANEL_VERSION may already name the target, so a second run
# would not know the release to roll back to); it is reported as interrupted,
# so the operator can check and start it again. A newer request in update/
# supersedes it. aap-updater.path also watches the claimed copy, so this runs
# at boot.
recover_interrupted_run() {
  [ "$STAGE2" = "1" ] && return 0
  [ -e "$CLAIMED_REQUEST" ] || [ -L "$CLAIMED_REQUEST" ] || return 0
  rm -rf -- "$CLAIMED_REQUEST"
  if [ "$REAPPLY" = "1" ] || [ -e "$REQUEST_FILE" ] || [ -L "$REQUEST_FILE" ]; then
    log "dropped the request of an interrupted run; this run replaces it"
    return 0
  fi
  PREV_VERSION="$(read_env_version)"
  if [ -f "$PG_UPGRADE_STATE" ]; then
    # AI-2653: the box may be between two PostgreSQL majors. Not resumed: the
    # operator follows the recovery steps the upgrade notes give.
    log "the interrupted run was upgrading PostgreSQL: $(tr '\n' ' ' < "$PG_UPGRADE_STATE")"
    finish_failed "the previous update run was interrupted while it upgraded PostgreSQL; nothing was started again: follow the recovery steps in the upgrade notes (PostgreSQL 18) before you start the update again"
    return 1
  fi
  finish_failed "the previous update run was interrupted before it finished (power loss, reboot or the updater was stopped); check which version the panel runs, then start the update again"
  return 1
}

# The request is written by the panel container, which is not root. Everything
# in it is input to be checked, not an instruction to follow. It is claimed
# first, then the claimed entry must be a regular file (not a link, FIFO or
# folder) with one link and at most REQUEST_LIMIT bytes; it is read once,
# bounded. Anything else is removed unread. There is no owner check: the panel
# image has no USER and writes as uid 0, like root on the host, so an owner
# rule would accept everything the panel can write and refuse nothing.
read_request() {
  local target body
  claim_request || return 1
  if [ -L "$CLAIMED_REQUEST" ] || [ ! -f "$CLAIMED_REQUEST" ] \
      || [ "$(stat -c %h -- "$CLAIMED_REQUEST" 2>/dev/null)" != 1 ] \
      || [ "$(stat -c %s -- "$CLAIMED_REQUEST" 2>/dev/null || echo "$((REQUEST_LIMIT + 1))")" -gt "$REQUEST_LIMIT" ]; then
    rm -rf -- "$CLAIMED_REQUEST"
    FAIL_REASON="malformed request.json"
    return 1
  fi
  # Bounded even if a writer still holds the file open and keeps writing.
  body="$(head -c "$((REQUEST_LIMIT + 1))" -- "$CLAIMED_REQUEST" 2>/dev/null)" || body=""
  [ "${#body}" -le "$REQUEST_LIMIT" ] || { FAIL_REASON="malformed request.json"; return 1; }
  target="$(jq -r '.targetTag // ""' <<<"$body" 2>/dev/null)" || { FAIL_REASON="malformed request.json"; return 1; }
  CHANNEL="$(jq -r '.channel // "stable"' <<<"$body" 2>/dev/null)"
  CURRENT="$(jq -r '.currentVersion // ""' <<<"$body" 2>/dev/null)"
  # The channel only selects a rule and the current version is only compared;
  # neither may carry anything but a plain word into the log and the result.
  [[ "$CHANNEL" =~ ^[a-z]+$ ]] || CHANNEL="stable"
  is_release_version "${CURRENT#v}" || CURRENT=""
  if [ -z "$target" ] || [ "$target" = "null" ]; then
    FAIL_REASON="request.json has no target tag"
    return 1
  fi
  # A target is a release version and nothing else. It ends up in URLs, in the
  # image name, in .env and in the result; a line break or a quote in it must
  # never get that far. TARGET_TAG stays empty, so the refusal does not carry it.
  if ! is_release_version "$target"; then
    FAIL_REASON="malformed request.json"
    return 1
  fi
  TARGET_TAG="$target"
  # GHCR semver tags omit v; release.yml publishes assets under github.ref_name
  # (vX.Y.Z). Keep the registry tag unchanged for validation, signatures and .env.
  ASSET_TAG="v${TARGET_TAG#v}"
  return 0
}

read_env_version_raw() {
  grep -E '^PANEL_VERSION=' "$ENV_FILE" 2>/dev/null | head -1 | cut -d= -f2- | tr -d '"' | tr -d "'"
}

# read_env_version — PANEL_VERSION as an image tag. GitHub names a release
# v2.22.0, GHCR tags its image 2.22.0 (AI-2172), so a release name written into
# .env by hand or by an installer from before 2.23 is read as its tag.
read_env_version() {
  local v
  v="$(read_env_version_raw)"
  if [[ "$v" =~ ^[vV] ]] && is_release_version "${v:1}"; then
    v="${v:1}"
  fi
  printf '%s\n' "$v"
}

# A release version as the registry tags it: 2.7.0, 2.8.0-rc.1. "latest" and
# "main" are not: they name whatever was published last, and no Compose file is
# published under them.
is_release_version() {
  [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]
}

# running_release — the release the panel container was built as, read from the
# image's own label. Empty when there is no panel container or the image is a
# development build.
running_release() {
  local v
  v="$(docker inspect -f '{{index .Config.Labels "org.opencontainers.image.version"}}' "$PANEL_CONTAINER" 2>/dev/null | head -1)"
  v="${v#v}"
  is_release_version "$v" && printf '%s\n' "$v"
}

# set_env_version V — edit PANEL_VERSION in place (NEVER truncate the file);
# append the line only if it is genuinely absent.
set_env_version() {
  local v="$1"
  if [ -f "$ENV_FILE" ] && grep -qE '^PANEL_VERSION=' "$ENV_FILE"; then
    sed -i "s/^PANEL_VERSION=.*/PANEL_VERSION=${v}/" "$ENV_FILE"
  else
    printf 'PANEL_VERSION=%s\n' "$v" >> "$ENV_FILE"
  fi
}

# List the image's tags from GHCR via the anonymous pull-token flow — the same
# approach the Go detector uses (internal/updater/registry.go), so the host
# needs only curl + jq (no crane binary). n=1000 returns every tag in one page
# for a repo this size.
list_remote_tags() {
  local token
  token="$(curl -fsS --max-time 15 \
    "https://${REGISTRY_HOST}/token?scope=repository:${IMAGE_PATH}:pull&service=${REGISTRY_HOST}" \
    2>/dev/null | jq -r '.token // .access_token // empty')"
  [ -n "$token" ] || return 1
  curl -fsS --max-time 15 -H "Authorization: Bearer ${token}" \
    "https://${REGISTRY_HOST}/v2/${IMAGE_PATH}/tags/list?n=1000" \
    2>/dev/null | jq -r '.tags[]? // empty'
}

# Defense in depth: the host re-validates the panel-chosen tag against the
# registry and refuses a pre-release on the stable channel.
validate_target() {
  if [ "$CHANNEL" = "stable" ] && [[ "$TARGET_TAG" == *-* ]]; then
    FAIL_REASON="pre-release target '${TARGET_TAG}' rejected on the stable channel"
    return 1
  fi
  if ! list_remote_tags | grep -Fxq "$TARGET_TAG"; then
    FAIL_REASON="target tag '${TARGET_TAG}' not found on the registry"
    return 1
  fi
  return 0
}

# pg_dump BEFORE any image change. Abort the whole apply if the dump fails, so a
# bad migration on the new image can always be restored. Keep the newest N.
backup_db() {
  local ts file
  ts="$(date -u '+%Y%m%d-%H%M%S')"
  file="${BACKUP_DIR}/backup-pre-update-${ts}.sql.gz"
  mkdir -p "$BACKUP_DIR"
  if ! docker exec "$PG_CONTAINER" pg_dump -U "$PG_USER" -d "$PG_DB" | gzip > "$file"; then
    rm -f "$file"
    return 1
  fi
  if [ ! -s "$file" ]; then
    rm -f "$file"
    return 1
  fi
  BACKUP_PATH="$file"
  prune_backups "backup-pre-update"
  backup_side_db "$ts" "$PG_KEYCLOAK_DB" keycloak-pre-update Keycloak || return 1
  backup_side_db "$ts" "$PG_LITELLM_DB" litellm-pre-update "AI gateway" || return 1
  return 0
}

# backup_side_db <ts> <database> <file prefix> <label> — dump another database
# on the panel's Postgres before any image change. Keycloak (AI-2048) and the
# AI gateway's LiteLLM (AI-2221) both migrate their tables one way at the first
# start of a new version: a dump from right before the swap is the only way
# back that does not lose the day since the nightly backup. Each prefix keeps
# its own newest BACKUP_RETAIN. A box without the database (none was ever
# created) skips it; a dump that fails aborts the update like the panel's own.
backup_side_db() {
  local ts="$1" db="$2" prefix="$3" label="$4" file exists
  exists="$(docker exec "$PG_CONTAINER" psql -U "$PG_USER" -d "$PG_DB" -At \
    -c "SELECT 1 FROM pg_database WHERE datname = '${db}'" 2>/dev/null || true)"
  if [ "$exists" != "1" ]; then
    log "no ${db} database; skipping the ${label} pre-update dump"
    return 0
  fi
  file="${BACKUP_DIR}/${prefix}-${ts}.sql.gz"
  if ! docker exec "$PG_CONTAINER" pg_dump -U "$PG_USER" -d "$db" | gzip > "$file"; then
    rm -f "$file"
    return 1
  fi
  if [ ! -s "$file" ]; then
    rm -f "$file"
    return 1
  fi
  log "${label} database dumped to ${file}"
  prune_backups "$prefix"
  return 0
}

# prune_backups <prefix> — keep the newest BACKUP_RETAIN <prefix>-*.sql.gz.
prune_backups() {
  local prefix="$1"
  shopt -s nullglob
  local files=( "${BACKUP_DIR}/${prefix}"-*.sql.gz )
  shopt -u nullglob
  [ "${#files[@]}" -le "$BACKUP_RETAIN" ] && return 0
  local sorted=()
  # Timestamped names sort chronologically; newest first, drop everything past N.
  mapfile -t sorted < <(printf '%s\n' "${files[@]}" | sort -r)
  rm -f "${sorted[@]:$BACKUP_RETAIN}"
}

# ── PostgreSQL major upgrade (AI-2653) ────────────────────────────────────────
# PostgreSQL cannot start on a data folder written by an older major version,
# so a release that moves the bundled Postgres to a new major (16 → 18) cannot
# just swap the image. When the release's Compose file names a newer major than
# the data on this box, the updater moves the data across itself:
#
#   plan (before anything changes): read the data's major from PG_VERSION and
#     the target's from the release's Compose file; refuse a downgrade, a data
#     folder it cannot read, and a disk without room for both clusters.
#   run (after the compose swap, before the new images start):
#     1. stop the panel, Keycloak and the AI gateway, the only clients;
#     2. count every table's rows in every database (the "before" list);
#     3. pg_dumpall with the NEW major's client, as the PostgreSQL docs
#        recommend, into backups/postgres-<old>-to-<new>-<time>/;
#     4. stop the old server, then in a one-off container of the new image move
#        the old cluster within its volume from the root to <old>/docker (the
#        layout the 18+ image uses), initialise <new>/aap-upgrade, restore the
#        dump into it (ON_ERROR_STOP) and count again (the "after" list);
#     5. only when both lists are identical, rename <new>/aap-upgrade to
#        <new>/docker, where the new Compose file's Postgres finds it.
#   Anything failing from step 1 on is rolled back: the half-built cluster is
#   removed, the old cluster moved back to the volume root, the previous Compose
#   file restored and the old stack started again (undo_postgres_upgrade).
#
# The old cluster is never written to. After a good upgrade it stays in the
# volume under <old>/docker, next to the new one, until the operator removes it
# (upgrade notes, "PostgreSQL 18"). An updater or a hand-run `docker compose up`
# that does not know about this cannot do harm either: the 18+ image refuses to
# start while the old data sits where 16 left it, rather than creating an empty
# database.

# staged_postgres_image <compose> — the image of the postgresql service.
staged_postgres_image() {
  sed -nE '/^  postgresql:[[:space:]]*$/,/^  [A-Za-z0-9_-]+:[[:space:]]*$/ s/^    image:[[:space:]]*["'"'"']?([^"'"'"'[:space:]#]+).*/\1/p' "$1" | head -n 1
}

# image_major <image> — the major version a postgres image tag names
# (postgres:18.7-alpine@sha256:… → 18), or nothing.
image_major() {
  local ref="${1%@*}" tag major
  case "$ref" in *:*) ;; *) return 0 ;; esac
  tag="${ref##*:}"
  major="${tag%%[.-]*}"
  [[ "$major" =~ ^[0-9]+$ ]] && echo "$major"
  return 0
}

# plan_postgres_upgrade — decide, before anything on the box changes, whether
# this update moves the data to a new PostgreSQL major. Sets PG_UPGRADE_* when
# it does; refuses (FAIL_REASON) what it cannot do safely.
plan_postgres_upgrade() {
  local image new old vol size_kb avail_kb need_kb host_kb running running_major
  [ -n "$STAGED_COMPOSE" ] || return 0
  image="$(staged_postgres_image "$STAGED_COMPOSE")"
  [ -n "$image" ] || return 0
  new="$(image_major "$image")"
  [ -n "$new" ] || return 0
  # The volume that holds the data where every release up to PostgreSQL 16 put
  # it. None: the box is on the 18+ layout already (or has no named volume).
  vol="$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/var/lib/postgresql/data"}}{{.Name}}{{end}}{{end}}' "$PG_CONTAINER" 2>/dev/null)"
  if [ -z "$vol" ]; then
    running="$(docker exec "$PG_CONTAINER" cat "/var/lib/postgresql/${new}/docker/PG_VERSION" 2>/dev/null | tr -d '[:space:]')"
    running_major="$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$PG_CONTAINER" 2>/dev/null | sed -n 's/^PG_MAJOR=//p')"
    if [[ "$running_major" =~ ^[0-9]+$ ]] && [ "$running_major" != "$new" ] && [ "$running" != "$new" ]; then
      FAIL_REASON="the PostgreSQL upgrade from ${running_major} to ${new} cannot run: this updater upgrades only data in the PostgreSQL 16 layout; nothing was changed"
      return 1
    fi
    return 0
  fi
  old="$(docker exec "$PG_CONTAINER" cat /var/lib/postgresql/data/PG_VERSION 2>/dev/null | tr -d '[:space:]')"
  if ! [[ "$old" =~ ^[0-9]+$ ]]; then
    FAIL_REASON="the PostgreSQL upgrade to ${new} cannot run: the version of the data in volume ${vol} could not be read; nothing was changed"
    return 1
  fi
  if [ "$old" = "$new" ]; then
    # Same major, old layout: a Compose file this updater does not expect.
    FAIL_REASON="the PostgreSQL upgrade from ${old} to ${new} cannot run: the release's Compose file mounts the data differently for the same major; nothing was changed"
    return 1
  fi
  if [ "$old" -gt "$new" ]; then
    FAIL_REASON="the PostgreSQL upgrade from ${old} to ${new} cannot run: it would be a downgrade; nothing was changed"
    return 1
  fi
  size_kb="$(docker exec "$PG_CONTAINER" psql -U "$PG_USER" -d "$PG_DB" -At \
    -c "SELECT (COALESCE(sum(pg_database_size(datname)), 0) / 1024)::bigint FROM pg_database" 2>/dev/null | tr -d '[:space:]')"
  avail_kb="$(docker exec "$PG_CONTAINER" df -Pk /var/lib/postgresql/data 2>/dev/null | awk 'NR == 2 { print $4 }')"
  mkdir -p "$BACKUP_DIR"
  host_kb="$(df -Pk "$BACKUP_DIR" 2>/dev/null | awk 'NR == 2 { print $4 }')"
  if ! [[ "$size_kb" =~ ^[0-9]+$ && "$avail_kb" =~ ^[0-9]+$ && "$host_kb" =~ ^[0-9]+$ ]]; then
    FAIL_REASON="the PostgreSQL upgrade from ${old} to ${new} cannot run: the size of the databases or the free disk space could not be read; nothing was changed"
    return 1
  fi
  # The new cluster is about as big as the old one, which stays; the dump
  # (compressed, on the host) is smaller than the data.
  need_kb=$(( size_kb * 2 + PG_UPGRADE_MARGIN_KB ))
  if [ "$avail_kb" -lt "$need_kb" ] || [ "$host_kb" -lt $(( size_kb + PG_UPGRADE_MARGIN_KB / 2 )) ]; then
    FAIL_REASON="the PostgreSQL upgrade from ${old} to ${new} cannot run: not enough free disk space (the databases use $(( size_kb / 1024 )) MB, the upgrade needs $(( need_kb / 1024 )) MB free, $(( avail_kb / 1024 )) MB are free); nothing was changed"
    return 1
  fi
  PG_UPGRADE_FROM="$old"
  PG_UPGRADE_TO="$new"
  PG_UPGRADE_IMAGE="$image"
  PG_UPGRADE_VOLUME="$vol"
  log "this update moves PostgreSQL from ${old} to ${new} (volume ${vol}, databases $(( size_kb / 1024 )) MB)"
  return 0
}

# pg_upgrade_helper_script — the script the one-off container of the new image
# runs. Modes: count (prints the row count of every table in every database,
# and the number of roles; also run in the OLD server's container), relayout,
# restore, finalize, undo. The new cluster is initialised with the image's own
# entrypoint functions, so it gets exactly the pg_hba.conf and settings a fresh
# install of that image gets.
pg_upgrade_helper_script() {
  cat <<'HELPER'
#!/usr/bin/env bash
set -Eeuo pipefail
mode="$1"; old="${2:-}"; new="${3:-}"
root=/var/lib/postgresql
legacy="${root}/${old}/docker"
stage="${root}/${new}/aap-upgrade"
final="${root}/${new}/docker"
work=/aap-upgrade

count_rows() {
  local q db
  q="SELECT n.nspname || '.' || c.relname || ' ' || (xpath('/row/c/text()', query_to_xml(format('SELECT count(*) AS c FROM %I.%I', n.nspname, c.relname), false, true, '')))[1]::text
     FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
     WHERE c.relkind IN ('r', 'p') AND n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg_toast%'
     ORDER BY 1"
  psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d postgres \
    -c "SELECT 'roles ' || count(*) FROM pg_roles WHERE rolname !~ '^pg_'"
  psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d postgres \
    -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate ORDER BY 1" |
  while IFS= read -r db; do
    echo "database ${db}"
    psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$db" -c "$q" | sed "s|^|${db} |"
  done
}

# move_entries <from> <to> — every entry of <from> except the version folders.
move_entries() {
  local e
  for e in "$1"/* "$1"/.[!.]* "$1"/..?*; do
    [ -e "$e" ] || [ -L "$e" ] || continue
    case "${e##*/}" in "$old"|"$new") [ "$1" = "$root" ] && continue ;; esac
    mv "$e" "$2/"
  done
}

case "$mode" in
  count)
    count_rows
    ;;
  relayout)
    # As root. The old cluster sits at the volume root (16's PGDATA).
    if [ -s "${root}/PG_VERSION" ]; then
      [ "$(cat "${root}/PG_VERSION")" = "$old" ] || { echo "the data is not PostgreSQL ${old}" >&2; exit 3; }
      [ ! -e "${root}/${old}" ] || { echo "${root}/${old} exists already" >&2; exit 4; }
      mkdir -p "$legacy"
      chown postgres:postgres "${root}/${old}" "$legacy"
      chmod 700 "${root}/${old}" "$legacy"
      move_entries "$root" "$legacy"
    elif [ ! -s "${legacy}/PG_VERSION" ]; then
      echo "no PostgreSQL ${old} data in the volume" >&2; exit 3
    fi
    rm -rf "$stage"
    # The new image creates an empty <new>/docker when it refuses to start on
    # the old data (an update by an older updater, a hand-run compose up).
    if [ -e "$final" ]; then
      rmdir "$final" 2>/dev/null || { echo "${final} exists and is not empty" >&2; exit 4; }
    fi
    mkdir -p "${root}/${new}"
    chown postgres:postgres "$root" "${root}/${new}"
    # The restore runs as postgres, which writes its log and counts here.
    chown -R postgres "$work"
    # Read the secret as root, like the image's entrypoint does before it
    # drops to postgres: the host file is root's alone.
    POSTGRES_PASSWORD="$(cat "$POSTGRES_PASSWORD_FILE")"
    export POSTGRES_PASSWORD
    unset POSTGRES_PASSWORD_FILE
    exec gosu postgres "$0" restore "$old" "$new"
    ;;
  restore)
    # As postgres. A PGDATA that is not the image's default skips the
    # entrypoint's check for old data, which is the point here.
    export PGDATA="$stage"
    # shellcheck disable=SC1091
    source /usr/local/bin/docker-entrypoint.sh
    docker_setup_env
    docker_create_db_directories
    docker_verify_minimum_env
    docker_init_database_dir
    pg_setup_hba_conf postgres
    docker_temp_server_start postgres
    # The dump creates every role and database, except the bootstrap superuser
    # initdb just made: that one line would stop ON_ERROR_STOP.
    if ! gunzip -c "${work}/dumpall.sql.gz" | sed "/^CREATE ROLE ${POSTGRES_USER};\$/d" |
        psql -X -q -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d postgres > "${work}/restore.log" 2>&1; then
      tail -n 20 "${work}/restore.log" >&2
      docker_temp_server_stop || true
      exit 5
    fi
    count_rows > "${work}/counts-after.txt"
    docker_temp_server_stop
    sync
    ;;
  finalize)
    [ -s "${stage}/PG_VERSION" ] && [ ! -e "$final" ] || { echo "nothing to finalize" >&2; exit 6; }
    mv "$stage" "$final"
    sync
    ;;
  undo)
    # Only ever with the old cluster still present, in either place.
    if [ ! -s "${root}/PG_VERSION" ] && [ ! -s "${legacy}/PG_VERSION" ]; then
      echo "no PostgreSQL ${old} data found; nothing removed" >&2; exit 7
    fi
    rm -rf "$stage" "$final"
    rmdir "${root}/${new}" 2>/dev/null || true
    if [ ! -e "${root}/PG_VERSION" ]; then
      move_entries "$legacy" "$root"
      rmdir "$legacy" "${root}/${old}"
    fi
    [ -s "${root}/PG_VERSION" ]
    sync
    ;;
  *) echo "unknown mode ${mode}" >&2; exit 2 ;;
esac
HELPER
}

# pg_helper <mode> [docker run options…] — run the helper in a one-off
# container of the new image with the data volume at /var/lib/postgresql.
pg_helper() {
  local mode="$1"; shift
  docker rm -f "$PG_UPGRADE_CONTAINER" >/dev/null 2>&1 || true
  run_logged docker run --rm --name "$PG_UPGRADE_CONTAINER" --network none \
    -v "${PG_UPGRADE_VOLUME}:/var/lib/postgresql" \
    -v "${PG_UPGRADE_DIR}:/aap-upgrade" \
    -v "${PG_SECRET_FILE}:/run/secrets/db_password:ro" \
    -e POSTGRES_USER="$PG_USER" -e POSTGRES_PASSWORD_FILE=/run/secrets/db_password \
    -e POSTGRES_DB=postgres \
    "$@" --entrypoint bash "$PG_UPGRADE_IMAGE" /aap-upgrade/helper.sh \
    "$mode" "$PG_UPGRADE_FROM" "$PG_UPGRADE_TO"
}

# stop_pg_clients — stop every running container that talks to the database.
stop_pg_clients() {
  local c
  for c in $PG_CLIENT_CONTAINERS; do
    [ "$(docker inspect -f '{{.State.Running}}' "$c" 2>/dev/null)" = "true" ] || continue
    run_logged docker stop -t 60 "$c" || return 1
  done
}

# upgrade_postgres_major — the run half (see the top of this section). Returns
# non-zero on any failure; the caller rolls back, and rollback() calls
# undo_postgres_upgrade first.
upgrade_postgres_major() {
  local ts
  [ -n "$PG_UPGRADE_TO" ] || return 0
  ts="$(date -u '+%Y%m%d-%H%M%S')"
  PG_UPGRADE_DIR="${BACKUP_DIR}/postgres-${PG_UPGRADE_FROM}-to-${PG_UPGRADE_TO}-${ts}"
  ( umask 077; mkdir -p "$PG_UPGRADE_DIR" ) || return 1
  pg_upgrade_helper_script > "${PG_UPGRADE_DIR}/helper.sh" || return 1
  chmod 755 "${PG_UPGRADE_DIR}/helper.sh"
  printf 'volume=%s\nfrom=%s\nto=%s\ndir=%s\n' "$PG_UPGRADE_VOLUME" "$PG_UPGRADE_FROM" \
    "$PG_UPGRADE_TO" "$PG_UPGRADE_DIR" > "$PG_UPGRADE_STATE" || return 1
  log "PostgreSQL ${PG_UPGRADE_FROM} → ${PG_UPGRADE_TO}: pulling ${PG_UPGRADE_IMAGE}"
  run_logged docker pull "$PG_UPGRADE_IMAGE" || return 1

  PG_UPGRADE_STARTED=1
  log "PostgreSQL upgrade: stopping the database's clients"
  stop_pg_clients || return 1
  log "PostgreSQL upgrade: counting rows before the dump"
  if ! docker exec -i -u postgres "$PG_CONTAINER" bash -s count \
      < "${PG_UPGRADE_DIR}/helper.sh" > "${PG_UPGRADE_DIR}/counts-before.txt" 2>"${PG_UPGRADE_DIR}/count.err" \
      || [ ! -s "${PG_UPGRADE_DIR}/counts-before.txt" ]; then
    log "could not count the rows of the PostgreSQL ${PG_UPGRADE_FROM} databases"
    return 1
  fi
  log "PostgreSQL upgrade: dumping every database with the ${PG_UPGRADE_TO} client"
  # Loopback in the old server's own network namespace: the image trusts it,
  # so no password is handled here, and nothing listens beyond the container.
  if ! docker run --rm --network "container:${PG_CONTAINER}" "$PG_UPGRADE_IMAGE" \
      pg_dumpall -h 127.0.0.1 -U "$PG_USER" 2>"${PG_UPGRADE_DIR}/dump.err" \
      | gzip > "${PG_UPGRADE_DIR}/dumpall.sql.gz" \
      || [ "$(gunzip -c "${PG_UPGRADE_DIR}/dumpall.sql.gz" 2>/dev/null | head -c 64 | wc -c)" -lt 64 ]; then
    log "pg_dumpall failed: $(tail -n 3 "${PG_UPGRADE_DIR}/dump.err" 2>/dev/null | tr '\n' ' ')"
    return 1
  fi
  log "PostgreSQL upgrade: stopping PostgreSQL ${PG_UPGRADE_FROM}"
  run_logged docker stop -t 120 "$PG_CONTAINER" || return 1
  log "PostgreSQL upgrade: restoring into a new PostgreSQL ${PG_UPGRADE_TO} cluster"
  pg_helper relayout || return 1
  if ! cmp -s "${PG_UPGRADE_DIR}/counts-before.txt" "${PG_UPGRADE_DIR}/counts-after.txt"; then
    log "the restored PostgreSQL ${PG_UPGRADE_TO} cluster does not hold the same rows; differences:"
    diff "${PG_UPGRADE_DIR}/counts-before.txt" "${PG_UPGRADE_DIR}/counts-after.txt" 2>&1 | head -n 20 \
      | while IFS= read -r line; do log "  ${line}"; done
    return 1
  fi
  pg_helper finalize || return 1
  log "PostgreSQL upgrade: ${PG_UPGRADE_TO} holds the same $(grep -c . "${PG_UPGRADE_DIR}/counts-after.txt") counted entries; the ${PG_UPGRADE_FROM} data is kept in volume ${PG_UPGRADE_VOLUME} under ${PG_UPGRADE_FROM}/docker"
  return 0
}

# undo_postgres_upgrade — put the old cluster back where the previous Compose
# file expects it. Stops whatever runs on the volume first. Never removes the
# new cluster unless the old one is still there (the helper checks).
undo_postgres_upgrade() {
  [ "$PG_UPGRADE_STARTED" = "1" ] || return 0
  log "PostgreSQL upgrade: putting the ${PG_UPGRADE_FROM} data back"
  stop_pg_clients || true
  docker stop -t 120 "$PG_CONTAINER" >/dev/null 2>&1 || true
  pg_helper undo || return 1
  PG_UPGRADE_STARTED=0
  return 0
}

# verify-or-refuse — fail-closed. No bypass.
#
# Sets IMAGE_DIGEST to the one digest that was verified; apply_target pulls
# exactly that. A release with a manifest names its digest there, and the
# signature is checked for that digest. An older release has only its tag: the
# tag is verified, and the digest cosign reports the signature is for is kept,
# so a tag moved after the check cannot change what is pulled.
verify_image() {
  local identity="${RELEASE_WORKFLOW_IDENTITY}@refs/tags/${ASSET_TAG}" out
  IMAGE_DIGEST=""
  if [ "$MANIFEST_RELEASE" = "1" ]; then
    IMAGE_DIGEST="$(jq -r '.image.digest // ""' "$MANIFEST_FILE" 2>/dev/null)"
    [[ "$IMAGE_DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]] || return 1
    cosign verify "${REGISTRY}@${IMAGE_DIGEST}" \
      --certificate-identity "$identity" \
      --certificate-oidc-issuer "$COSIGN_CERT_OIDC_ISSUER" \
      >/dev/null 2>&1
    return
  fi
  out="$(cosign verify "${REGISTRY}:${TARGET_TAG}" \
    --certificate-identity "$identity" \
    --certificate-oidc-issuer "$COSIGN_CERT_OIDC_ISSUER" \
    2>/dev/null)" || return 1
  IMAGE_DIGEST="$(jq -r '.[0].critical.image."docker-manifest-digest" // ""' <<<"$out" 2>/dev/null)"
  [[ "$IMAGE_DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]]
}

# ── The release manifest (AI-1185) ────────────────────────────────────────────
# The image was signed from the start; the files that say how to run it were
# not. They came from the download bucket as plain files and were followed as
# root, so write access to the bucket was root on every box that updated. Each
# release now publishes release-manifest.json — the image digest and the
# SHA-256 of every published file — signed by its own release run. Think of the
# signed SHA256SUMS next to a distribution's ISO images.

# version_newer A B — true when release A is newer than release B. Major, minor
# and patch are compared as NUMBERS: as text, 2.9.0 sorts after 2.14.3. A
# pre-release suffix is dropped first, so 2.14.3-rc.1 counts as 2.14.3.
version_newer() {
  local a="${1#v}" b="${2#v}" i x y
  local -a pa pb
  a="${a%%-*}"; b="${b%%-*}"
  IFS=. read -r -a pa <<<"$a"
  IFS=. read -r -a pb <<<"$b"
  for i in 0 1 2; do
    x=$((10#${pa[i]:-0})); y=$((10#${pb[i]:-0}))
    [ "$x" -gt "$y" ] && return 0
    [ "$x" -lt "$y" ] && return 1
  done
  return 1
}

# release_newer A B — like version_newer, but a pre-release counts as OLDER
# than its own release (2.17.0-rc.1 < 2.17.0), and two pre-releases of one
# release are compared by their dot-separated suffix, numbers as numbers. Used
# for the updater's downgrade floor only: there, dropping the suffix would let
# the rc of a release replace the updater of that release.
release_newer() {
  local a="${1#v}" b="${2#v}" sa="" sb="" i x y
  local -a fa fb
  version_newer "$a" "$b" && return 0
  version_newer "$b" "$a" && return 1
  [[ "$a" == *-* ]] && sa="${a#*-}"
  [[ "$b" == *-* ]] && sb="${b#*-}"
  [ "$sa" = "$sb" ] && return 1
  [ -z "$sa" ] && return 0
  [ -z "$sb" ] && return 1
  IFS=. read -r -a fa <<<"$sa"
  IFS=. read -r -a fb <<<"$sb"
  for (( i=0; i<${#fa[@]} || i<${#fb[@]}; i++ )); do
    x="${fa[i]:-}"; y="${fb[i]:-}"
    [ "$x" = "$y" ] && continue
    [ -z "$x" ] && return 1
    [ -z "$y" ] && return 0
    if [[ "$x" =~ ^[0-9]+$ ]] && [[ "$y" =~ ^[0-9]+$ ]]; then
      [ $((10#$x)) -gt $((10#$y)) ]
      return
    fi
    [[ "$x" > "$y" ]]
    return
  done
  return 1
}

# needs_manifest V — false only for a release at or below
# LAST_RELEASE_WITHOUT_MANIFEST. Anything that is not a plain release version,
# on either side, needs one: when in doubt, the unsigned path stays shut.
needs_manifest() {
  is_release_version "${1#v}" || return 0
  is_release_version "${LAST_RELEASE_WITHOUT_MANIFEST#v}" || return 0
  version_newer "$1" "$LAST_RELEASE_WITHOUT_MANIFEST"
}

same_release() { [ -n "${2:-}" ] && [ "${1#v}" = "${2#v}" ]; }

# target_is_installed — the request asks for the release that is already here:
# --reapply, or the panel's "Apply again".
target_is_installed() {
  [ "$REAPPLY" = "1" ] && return 0
  same_release "$TARGET_TAG" "$PREV_VERSION" && return 0
  same_release "$TARGET_TAG" "$CURRENT" && return 0
  same_release "$TARGET_TAG" "$(running_release)"
}

prepare_stage() {
  rm -rf "$STAGE_DIR"
  mkdir -m 700 "$STAGE_DIR"
}

# unpack_archive <archive> <dest> <top> — unpack a verified archive into the
# work area, and only if it holds nothing but plain files and directories under
# <top>/. The manifest says the archive is ours; this says it cannot write
# anywhere else even when it is not what we meant to publish. Checked on the
# listing BEFORE unpacking, then unpacked without the owner and permission bits
# it carries, then looked at once more on disk.
unpack_archive() {
  local archive="$1" dest="$2" top="$3" names listing line
  names="$(tar -tzf "$archive" 2>/dev/null)" || return 1
  [ -n "$names" ] || return 1
  while IFS= read -r line; do
    case "$line" in
      "$top"|"$top"/*) ;;
      *) log "archive refused: ${line} is outside ${top}/"; return 1 ;;
    esac
    case "/${line}/" in
      */../*) log "archive refused: ${line} climbs out of ${top}/"; return 1 ;;
    esac
  done <<<"$names"
  # First character of each verbose line is the member type: - file, d directory.
  # A link (l, h), a device or a pipe is refused.
  listing="$(tar -tvzf "$archive" 2>/dev/null)" || return 1
  while IFS= read -r line; do
    case "$line" in
      -*|d*) ;;
      *) log "archive refused: it holds something that is not a plain file or directory"; return 1 ;;
    esac
  done <<<"$listing"
  mkdir -m 700 "$dest" || return 1
  tar -xzf "$archive" -C "$dest" --no-same-owner --no-same-permissions 2>/dev/null || return 1
  [ -d "${dest}/${top}" ] || return 1
  [ -z "$(find "$dest" ! -type f ! -type d 2>/dev/null | head -1)" ]
}

# fetch_manifest — download the target's manifest and signature bundle, and
# accept the manifest only when it is signed by the release run of exactly this
# version and describes exactly this version and this image repository.
fetch_manifest() {
  local m="${STAGE_DIR}/release-manifest.json" b="${STAGE_DIR}/release-manifest.json.bundle"
  FAIL_REASON="release manifest of ${TARGET_TAG} is missing or not valid; nothing was changed"
  curl -fsSL --max-time 60 "${GET_BASE}/${ASSET_TAG}/release-manifest.json" -o "$m" 2>/dev/null || return 1
  curl -fsSL --max-time 60 "${GET_BASE}/${ASSET_TAG}/release-manifest.json.bundle" -o "$b" 2>/dev/null || return 1
  [ -s "$m" ] && [ -s "$b" ] || return 1
  cosign verify-blob \
    --bundle "$b" \
    --certificate-identity "${RELEASE_WORKFLOW_IDENTITY}@refs/tags/${ASSET_TAG}" \
    --certificate-oidc-issuer "$COSIGN_CERT_OIDC_ISSUER" \
    "$m" >/dev/null 2>&1 || return 1
  jq -e --arg version "$ASSET_TAG" --arg repository "$REGISTRY" '
      (.version == $version)
      and (.image.repository == $repository)
      and ((.image.digest | type) == "string")
      and (.image.digest | test("^sha256:[0-9a-f]{64}$"))
      and ((.files | type) == "object")
    ' "$m" >/dev/null 2>&1 || return 1
  MANIFEST_FILE="$m"
  FAIL_REASON=""
  return 0
}

# fetch_release_file <name> <dest> — the release's own copy of a file, kept only
# when its SHA-256 is the one the manifest names.
#   0  downloaded and verified
#   1  could not be downloaded (the caller words the reason)
#   2  downloaded, but not the file the manifest names (FAIL_REASON is set)
fetch_release_file() {
  local name="$1" dest="$2" want have
  rm -f "$dest"
  if ! curl -fsSL --max-time 60 "${GET_BASE}/${ASSET_TAG}/${name}" -o "$dest" 2>/dev/null || [ ! -s "$dest" ]; then
    rm -f "$dest"
    return 1
  fi
  want="$(jq -r --arg name "$name" '.files[$name] // ""' "$MANIFEST_FILE" 2>/dev/null)"
  have="$(sha256sum "$dest" | cut -d' ' -f1)"
  if [ -z "$want" ] || [ "$want" != "$have" ]; then
    rm -f "$dest"
    FAIL_REASON="file ${name} of release ${TARGET_TAG} does not match its release manifest; nothing was changed"
    return 2
  fi
  return 0
}

# ── Self-refresh: stage 1 supervises stage 2 (AI-1471) ────────────────────────
# Think of `apt` upgrading itself: the running updater (A) puts the target
# release's updater (B) in place, lets B do the update as a child process and
# waits. A stays in charge: when B does not report success for this run, A
# puts its own files back. Every file is replaced by a rename, never rewritten
# in place: bash reads a script while it runs, so a rewrite would make a
# running updater execute a mix of two versions. A keeps running from the file
# it started from after the rename.

declare -A SWAP_PREV=() SWAP_SRC=()
SWAP_DONE=()
UPDATER_FLOOR=""
UPDATER_FLOOR_IS_FIRST=0
HANDOFF_RC=1

# installed_path / prev_path <name> — where a published updater file lives on
# this host, and where its previous copy is kept: on the same filesystem, so
# putting it back is a rename and needs no room for file data.
installed_path() {
  case "$1" in
    aap-update.sh) printf '%s' "$UPDATER_PATH" ;;
    *)             printf '%s/%s' "$UPDATER_UNIT_DIR" "$1" ;;
  esac
}
prev_path() {
  case "$1" in
    aap-update.sh) printf '%s/%s' "$UPDATER_PREV_DIR" "$1" ;;
    *)             printf '%s/%s' "$UNIT_PREV_DIR" "$1" ;;
  esac
}
file_label() {
  case "$1" in
    aap-update.sh) printf 'updater script' ;;
    *)             printf 'unit %s' "$1" ;;
  esac
}

sha256_of() { sha256sum "$1" 2>/dev/null | cut -d' ' -f1; }

# write_updater_marker — update/updater.json for the panel UI: this updater
# refreshes itself, and the SHA-256 of the script installed right now. A hint,
# never a security gate: the panel can write update/ and would only lie to
# itself. Built in the work area and renamed into place, like the result.
write_updater_marker() {
  local script="$UPDATER_PATH" tmp
  [ -f "$script" ] || script="${BASH_SOURCE[0]}"
  tmp="$(mktemp "${WORK_DIR}/marker.XXXXXX" 2>/dev/null)" || { log "WARNING: could not write ${UPDATER_MARKER}"; return 0; }
  if jq -cn --arg sha "$(sha256_of "$script")" '{selfRefresh: 1, sha256: $sha}' > "$tmp" \
      && chmod 644 "$tmp" && mv -fT "$tmp" "$UPDATER_MARKER" 2>/dev/null; then
    return 0
  fi
  rm -f "$tmp"
  log "WARNING: could not write ${UPDATER_MARKER}"
}

# updater_floor — sets UPDATER_FLOOR to the oldest release whose updater may
# replace this one: the newest of the release recorded when an updater was last
# kept, the release of the running panel image, and FIRST_SELF_REFRESH_RELEASE.
# The request comes from the panel, which could ask for an older signed release
# to get its older updater installed as root. Read from the root-only work area
# and the image label only, never from update/.
updater_floor() {
  local v
  UPDATER_FLOOR=""
  UPDATER_FLOOR_IS_FIRST=0
  if [ -L "$UPDATER_RELEASE_FILE" ] || { [ -e "$UPDATER_RELEASE_FILE" ] && [ ! -f "$UPDATER_RELEASE_FILE" ]; }; then
    log "ignoring the recorded updater release: ${UPDATER_RELEASE_FILE} is not a plain file"
  elif [ -f "$UPDATER_RELEASE_FILE" ]; then
    v="$(head -n1 "$UPDATER_RELEASE_FILE" 2>/dev/null)"
    if is_release_version "${v#v}"; then
      UPDATER_FLOOR="${v#v}"
    else
      log "ignoring the recorded updater release in ${UPDATER_RELEASE_FILE}: not a release version"
    fi
  fi
  v="$(running_release)"
  if [ -n "$v" ] && { [ -z "$UPDATER_FLOOR" ] || release_newer "$v" "$UPDATER_FLOOR"; }; then
    UPDATER_FLOOR="$v"
  fi
  v="${FIRST_SELF_REFRESH_RELEASE#v}"
  if [ "$UPDATER_SELF_REFRESH" = "1" ] && { [ -z "$UPDATER_FLOOR" ] || release_newer "$v" "$UPDATER_FLOOR"; }; then
    UPDATER_FLOOR="$v"
    UPDATER_FLOOR_IS_FIRST=1
  fi
}

# record_updater_release — the release of the updater just kept, the floor of
# the next run.
record_updater_release() {
  local tmp
  tmp="$(mktemp "${WORK_DIR}/release.XXXXXX")" || { log "WARNING: could not record the updater release"; return 0; }
  if printf '%s\n' "${TARGET_TAG#v}" > "$tmp" && mv -fT "$tmp" "$UPDATER_RELEASE_FILE"; then
    return 0
  fi
  rm -f "$tmp"
  log "WARNING: could not record the updater release in ${UPDATER_RELEASE_FILE}"
}

# restore_one <name> — put the previous copy of one file back by rename: link
# it to a temporary name next to the file, then rename that over the file. The
# previous copy stays where it is. If the link cannot be made, the copy itself
# is moved back. A file the host did not have before is removed.
restore_one() {
  local name="$1" inst prev tmp
  inst="$(installed_path "$name")"
  prev="$(prev_path "$name")"
  if [ "${SWAP_PREV[$name]:-}" = "absent" ]; then
    rm -f "$inst"
    return
  fi
  tmp="$(mktemp -u "$(dirname "$inst")/.aap-swap.XXXXXX")"
  if ln -T "$prev" "$tmp" 2>/dev/null && mv -fT "$tmp" "$inst" 2>/dev/null; then
    return 0
  fi
  rm -f "$tmp"
  mv -fT "$prev" "$inst"
}

# undo_renames — reverse the renames done so far, newest first. Prints nothing;
# sets UNDO_FAILED to the names that could not be put back.
UNDO_FAILED=""
undo_renames() {
  local i name
  UNDO_FAILED=""
  for (( i=${#SWAP_DONE[@]}-1; i>=0; i-- )); do
    name="${SWAP_DONE[i]}"
    restore_one "$name" || UNDO_FAILED="${UNDO_FAILED:+$UNDO_FAILED }${name}"
  done
  SWAP_DONE=()
}

# drop_swap_temps — the staged units next to their targets, if still there.
drop_swap_temps() {
  local name
  for name in aap-updater.service aap-updater.path; do
    [ -n "${SWAP_SRC[$name]:-}" ] && rm -f "${SWAP_SRC[$name]}"
  done
}

# swap_updater <staged-dir> — steps 5 to 8 of the spec. Any failing step undoes
# everything before it; the caller then ends the run as failed.
swap_updater() {
  local staged="$1" name inst prev tmp d
  FAIL_REASON="could not install the updater of release ${TARGET_TAG}; the previous updater was kept; nothing else was changed"
  # Keep the installed copies, each by copy to a temporary name and rename. A
  # failure here (a full disk) has changed nothing that matters.
  for d in "$UPDATER_PREV_DIR" "$UNIT_PREV_DIR"; do
    if [ -L "$d" ] || ! mkdir -p "$d" || ! chmod 700 "$d"; then
      log "cannot keep the previous updater in ${d}"
      return 1
    fi
  done
  for name in "${UPDATER_FILES[@]}"; do
    inst="$(installed_path "$name")"
    prev="$(prev_path "$name")"
    if [ ! -e "$inst" ]; then
      SWAP_PREV[$name]="absent"
      continue
    fi
    tmp="$(mktemp "$(dirname "$prev")/.aap-swap.XXXXXX")" || { log "could not keep a copy of ${inst}"; return 1; }
    if ! cp -p "$inst" "$tmp" || ! mv -fT "$tmp" "$prev"; then
      rm -f "$tmp"
      log "could not keep a copy of ${inst} in $(dirname "$prev")"
      return 1
    fi
    SWAP_PREV[$name]="kept"
  done
  # Stage the units next to their targets, so their renames are atomic too.
  # The script is staged in the work area, under PANEL_DIR like its target.
  SWAP_SRC[aap-update.sh]="${staged}/aap-update.sh"
  for name in aap-updater.service aap-updater.path; do
    tmp="$(mktemp "${UPDATER_UNIT_DIR}/.aap-swap.XXXXXX")" || { drop_swap_temps; log "could not stage ${name} in ${UPDATER_UNIT_DIR}"; return 1; }
    SWAP_SRC[$name]="$tmp"
    if ! cp "${staged}/${name}" "$tmp" || ! chmod 644 "$tmp"; then
      drop_swap_temps
      log "could not stage ${name} in ${UPDATER_UNIT_DIR}"
      return 1
    fi
  done
  # Rename the three into place, the script first.
  SWAP_DONE=()
  for name in "${UPDATER_FILES[@]}"; do
    inst="$(installed_path "$name")"
    if ! mv -fT "${SWAP_SRC[$name]}" "$inst"; then
      log "could not rename the new ${name} into place; putting back what was already renamed"
      undo_renames
      drop_swap_temps
      [ -z "$UNDO_FAILED" ] || log "WARNING: could not put back: ${UNDO_FAILED}"
      return 1
    fi
    SWAP_DONE+=("$name")
    log "installed the $(file_label "$name") of release ${TARGET_TAG}: $(sha256_of "$(prev_path "$name")") -> $(sha256_of "$inst")"
  done
  # A running oneshot is not affected by a reload; drop-ins under
  # aap-updater.service.d/ were never touched.
  if ! systemctl daemon-reload >/dev/null 2>&1; then
    log "systemctl daemon-reload failed; putting the previous updater back"
    undo_renames
    [ -z "$UNDO_FAILED" ] || log "WARNING: could not put back: ${UNDO_FAILED}"
    systemctl daemon-reload >/dev/null 2>&1 || log "WARNING: systemctl daemon-reload failed again"
    return 1
  fi
  FAIL_REASON=""
  log "previous updater kept in ${UPDATER_PREV_DIR} and ${UNIT_PREV_DIR}"
  return 0
}

# restore_updater — A puts all three of its files back after stage 2, then
# reloads systemd. Fails when any file could not be put back.
restore_updater() {
  SWAP_DONE=("${UPDATER_FILES[@]}")
  undo_renames
  systemctl daemon-reload >/dev/null 2>&1 || log "WARNING: systemctl daemon-reload failed after restoring the updater"
  if [ -n "$UNDO_FAILED" ]; then
    log "ERROR: could not put back the previous updater's ${UNDO_FAILED}; the copies are in ${UPDATER_PREV_DIR} and ${UNIT_PREV_DIR}"
    return 1
  fi
  log "restored the previous updater"
}

# run_stage2 — run B as a child under our lock (fd 9 is inherited), then
# decide from the result B kept in the root-only work area, and from nothing
# else. Sets HANDOFF_RC.
run_stage2() {
  local run_id rc status="" rid="" matched=0 restored=true tmp
  local -a args=(--stage2)
  [ "$REAPPLY" = "1" ] && args+=(--reapply)
  run_id="$(head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \n')"
  rm -f "$STAGE2_RESULT"
  log "handing the update to the updater of release ${TARGET_TAG} (stage 2, run ${run_id})"
  AAP_UPDATE_RUN_ID="$run_id" "$UPDATER_PATH" "${args[@]}"
  rc=$?
  if [ -f "$STAGE2_RESULT" ] && [ ! -L "$STAGE2_RESULT" ]; then
    status="$(jq -r '.status // ""' "$STAGE2_RESULT" 2>/dev/null)"
    rid="$(jq -r '.runId // ""' "$STAGE2_RESULT" 2>/dev/null)"
    [ -n "$rid" ] && [ "$rid" = "$run_id" ] && matched=1
  fi
  if [ "$matched" = "1" ] && [ "$status" = "succeeded" ]; then
    record_updater_release
    log "kept the updater of release ${TARGET_TAG}"
    # Publish the result again from the work area: what is in update/ now is
    # the panel's to change.
    # Stage 2 already published this result itself, so a failure here must not
    # turn a success into "updater exited unexpectedly".
    if ! { tmp="$(mktemp "${WORK_DIR}/result.XXXXXX")" && cat "$STAGE2_RESULT" > "$tmp" && publish_result "$tmp"; }; then
      rm -f "${tmp:-}"
      log "WARNING: could not publish stage 2's result again; update/result.json is the copy stage 2 wrote"
    fi
    RESULT_WRITTEN=1
    rm -f "$STAGE2_RESULT"
    HANDOFF_RC=0
    return
  fi
  log "stage 2 did not succeed (exit ${rc}, status '${status:-none}'); restoring the previous updater"
  restore_updater || restored=false
  RESULT_EXTRA="{\"updaterRestored\":${restored}}"
  if [ "$matched" = "1" ]; then
    # A stage 2 from before AI-2443 looks for update/request.json, which this
    # stage 1 has already claimed, and says "no update request found". That
    # would mislead: say what happened instead.
    tmp="$(mktemp "${WORK_DIR}/result.XXXXXX")" \
      && jq -c --argjson r "$restored" \
        --arg why "the updater of release ${TARGET_TAG} could not take over this update: it cannot read the request the way this updater hands it over (AI-2443). The previous updater was restored and nothing was changed; update with the installer instead" \
        '. + {updaterRestored: $r} | if .reason == "no update request found" then .reason = $why else . end' "$STAGE2_RESULT" > "$tmp" \
      && publish_result "$tmp" && RESULT_WRITTEN=1
  else
    write_result "failed" "updater exited unexpectedly (rc=${rc})"
  fi
  rm -f "$STAGE2_RESULT"
  HANDOFF_RC=1
}

# refresh_updater — stage 1, after the manifest was verified and before
# anything else is fetched or changed. Returns
#   0  no swap: this run applies the release itself, as before
#   1  refused or failed with nothing changed; FAIL_REASON says why
#   3  stage 2 ran and the result is written; HANDOFF_RC is the exit code
refresh_updater() {
  local name named=0 staged="${STAGE_DIR}/updater" rc identical=1 out
  [ "$STAGE2" = "1" ] && return 0
  [ "$MANIFEST_RELEASE" = "1" ] || return 0
  if ! is_release_version "${FIRST_SELF_REFRESH_RELEASE#v}"; then
    log "WARNING: FIRST_SELF_REFRESH_RELEASE '${FIRST_SELF_REFRESH_RELEASE}' is not a release version; this updater applies ${TARGET_TAG} itself"
    return 0
  fi
  for name in "${UPDATER_FILES[@]}"; do
    jq -e --arg n "$name" '.files[$n] | type == "string"' "$MANIFEST_FILE" >/dev/null 2>&1 && named=$((named + 1))
  done
  # A release from before self-refresh names none: applied by this updater.
  if [ "$named" = "0" ] && version_newer "$FIRST_SELF_REFRESH_RELEASE" "$TARGET_TAG"; then
    return 0
  fi
  # No downgrade: an older release is applied by this, newer updater, whose
  # HOST_ASSETS is a superset. Nothing of the target's updater is installed,
  # so what its manifest says about it does not matter here.
  updater_floor
  if [ -n "$UPDATER_FLOOR" ] && release_newer "$UPDATER_FLOOR" "$TARGET_TAG"; then
    if [ "$UPDATER_FLOOR_IS_FIRST" = "1" ]; then
      log "self-refresh starts with release ${UPDATER_FLOOR} (FIRST_SELF_REFRESH_RELEASE); this updater applies ${TARGET_TAG} itself"
    else
      log "keeping the updater of ${UPDATER_FLOOR}: release ${TARGET_TAG} is older"
    fi
    return 0
  fi
  # Fail-closed: part of the updater, or none from a release that must name
  # it. A deleted entry must not quietly reopen "apply with the old updater".
  if [ "$named" != "${#UPDATER_FILES[@]}" ]; then
    FAIL_REASON="release manifest of ${TARGET_TAG} does not name its updater; nothing was changed"
    return 1
  fi

  # Fetch the three into the work area, each checked against the manifest.
  if ! mkdir -m 700 "$staged"; then
    FAIL_REASON="could not create the updater's work area ${WORK_DIR}"
    return 1
  fi
  for name in "${UPDATER_FILES[@]}"; do
    fetch_release_file "$name" "${staged}/${name}"; rc=$?
    if [ "$rc" = "1" ]; then
      FAIL_REASON="required host file ${name} could not be obtained"
      return 1
    fi
    [ "$rc" = "0" ] || return 1
    cmp -s "${staged}/${name}" "$(installed_path "$name")" || identical=0
  done
  if [ "$identical" = "1" ]; then
    rm -rf "$staged"
    log "the updater of release ${TARGET_TAG} is the one installed"
    return 0
  fi
  cmp -s "${staged}/aap-updater.path" "$(installed_path aap-updater.path)" || PATH_UNIT_CHANGED=1

  # Probe it the way systemd will start it: through its own interpreter line.
  chmod 755 "${staged}/aap-update.sh"
  out="$(timeout 10 "${staged}/aap-update.sh" --capabilities 2>/dev/null)"
  rc=$?
  if [ "$rc" != "0" ] || [ "$out" != "aap-update stage2 1" ]; then
    out="${out:0:80}"
    log "the updater of release ${TARGET_TAG} failed its start probe (exit ${rc}, answer '${out//[^[:print:]]/?}')"
    FAIL_REASON="the updater of release ${TARGET_TAG} could not be started on this host; nothing was changed"
    PATH_UNIT_CHANGED=0
    return 1
  fi

  if ! swap_updater "$staged"; then
    PATH_UNIT_CHANGED=0
    return 1
  fi
  UPDATER_SWAPPED=1
  run_stage2
  return 3
}

# ── Compose reconciliation (AI-746) ───────────────────────────────────────────
# Until this existed the updater swapped the panel image and NOTHING else, so
# every compose-level change — a new sidecar, healthcheck, volume, mem_limit —
# reached fresh installs only. A box installed before AI-611 kept its day-one
# compose forever, never got the audit-log rotator, and filled its disk while
# its panel reported it was up to date. demo2 died exactly that way for 3 weeks.
#
# It runs in two steps (AI-1185). stage_release downloads the Compose file and
# every host file the box is missing into the work area and checks each against
# the manifest; it changes nothing on the box. install_release then moves them
# into place. So a single file that does not verify stops the update before the
# first one is installed, and "nothing was changed" in the reason is true.

# host_path_missing <target> <kind> — a path the Compose file mounts is absent.
# A box that ever ran `up` against a compose whose bind-mount target was missing
# has a DOCKER-CREATED EMPTY DIRECTORY sitting where a file belongs; for a file
# asset that counts as absent too.
host_path_missing() {
  local target="$1" kind="$2"
  case "$kind" in
    local-sealed:*) [ -s "${PANEL_DIR}/${kind#local-sealed:}" ] && return 1 ;;
  esac
  [ -e "$target" ] || return 0
  case "$kind" in
    asset:*|secretfile:*) [ -d "$target" ] && [ -z "$(ls -A "$target" 2>/dev/null)" ] && return 0 ;;
  esac
  return 1
}

# stage_host_assets <compose> — fetch and verify every host path the NEW compose
# mounts and the box does not have. Existing files are never touched: box-local
# edits (a hand-tuned litellm-config.yaml, live ACME certs) outrank our copy,
# and the defect is absence, not staleness.
stage_host_assets() {
  local compose="$1" entry rel kind target name staged rc n=0
  for entry in "${HOST_ASSETS[@]}"; do
    rel="${entry%%|*}"
    kind="${entry#*|}"
    # Only reconcile what this compose actually references — a service we drop
    # must not keep resurrecting its files.
    grep -qF -- "$rel" "$compose" || continue
    target="${PANEL_DIR}/${rel}"
    host_path_missing "$target" "$kind" || continue

    staged=""
    case "$kind" in
      mkdir|secretfile:*) ;;
      asset:*|tar:*)
        if [ "${kind%%:*}" = "tar" ]; then
          name="${kind#tar:}"
        else
          name="${kind#asset:}"; name="${name%:*}"
        fi
        n=$((n + 1))
        staged="${STAGE_DIR}/host-${n}"
        fetch_release_file "$name" "$staged"; rc=$?
        if [ "$rc" = "1" ]; then
          # No fallback to the main-tracking copy: nothing signed covers it.
          FAIL_REASON="required host file ${rel} could not be obtained"
          return 1
        fi
        [ "$rc" = "0" ] || return 1
        if [ "${kind%%:*}" = "tar" ]; then
          # Unpacked here, in the work area, never straight into PANEL_DIR:
          # that is where aap-update.sh and .env live.
          if ! unpack_archive "$staged" "${STAGE_DIR}/unpack-${n}" "$rel"; then
            FAIL_REASON="required host file ${rel} could not be obtained"
            return 1
          fi
          rm -f "$staged"
          staged="${STAGE_DIR}/unpack-${n}/${rel}"
        fi
        ;;
      local|local-sealed:*)
        # Rendered by the installer from a template we publish nowhere. Guessing
        # at it would be worse than refusing.
        FAIL_REASON="required host file ${rel} could not be obtained"
        return 1
        ;;
    esac
    STAGED_ASSETS+=("${rel}|${kind}|${staged}")
  done
  return 0
}

# stage_release — fetch and verify the TARGET TAG's compose and, if it differs
# from the box's, every host file it needs. Nothing on the box changes here.
stage_release() {
  local new="${STAGE_DIR}/docker-compose.yml" rc
  STAGED_COMPOSE=""
  STAGED_ASSETS=()
  # The VERSIONED key only — never the unversioned one, which tracks main and
  # could hand a pinned update a compose newer than the image it is installing.
  fetch_release_file docker-compose.yml "$new"; rc=$?
  if [ "$rc" = "1" ]; then
    # A release with a manifest has a Compose file. One that cannot be
    # downloaded is a failed update, not an "image only" one: the image may
    # need the services its own Compose file defines.
    FAIL_REASON="the Compose file of release ${TARGET_TAG} could not be fetched from ${GET_BASE}/${ASSET_TAG}/docker-compose.yml; nothing was changed"
    return 1
  fi
  [ "$rc" = "0" ] || return 1

  # Byte-identical: leave the box completely alone, including the narrow
  # panel-only apply below. This is the common case.
  if [ -f "$COMPOSE_FILE" ] && cmp -s "$new" "$COMPOSE_FILE"; then
    rm -f "$new"
    return 0
  fi

  stage_host_assets "$new" || return 1
  STAGED_COMPOSE="$new"
  return 0
}

# install_release — put what stage_release verified into place: first the host
# paths the new compose mounts (compose creates a DIRECTORY at any absent
# bind-mount path, so a service whose file is missing starts broken), then the
# compose itself.
install_release() {
  local entry rel kind staged target mode ts backup
  [ -n "$STAGED_COMPOSE" ] || return 0

  for entry in ${STAGED_ASSETS[@]+"${STAGED_ASSETS[@]}"}; do
    rel="${entry%%|*}"; staged="${entry##*|}"
    kind="${entry#*|}"; kind="${kind%|*}"
    target="${PANEL_DIR}/${rel}"
    # Same reason string for every way this can fail on purpose — to the
    # operator all of them mean "the box could not be brought to the new
    # compose", and one fewer canonical reason is one fewer key in seven locales.
    FAIL_REASON="required host file ${rel} could not be obtained"
    case "$kind" in
      mkdir)
        mkdir -p "$target" || return 1
        ;;
      asset:*)
        # `rmdir` is the whole safety argument: it succeeds only on an empty
        # directory, so this can never destroy a real, populated config dir.
        if [ -d "$target" ]; then
          rmdir "$target" 2>/dev/null || return 1
          log "cleared the empty directory docker left at ${rel}"
        fi
        mode="${kind##*:}"
        mkdir -p "$(dirname "$target")" || return 1
        # Whole, verified, and on the same filesystem: the move is atomic.
        mv -f "$staged" "$target" || return 1
        chmod "$mode" "$target" || return 1
        ;;
      tar:*)
        # Already unpacked and checked by stage_host_assets; only the one
        # directory it may contain is moved into place.
        mkdir -p "$(dirname "$target")" || return 1
        mv "$staged" "$target" || return 1
        ;;
      secretfile:*)
        # Empty is a valid value of this secret (AI-1345: closes nothing), so
        # it is created, never fetched. An existing file is never touched: it
        # may already hold lines root wrote.
        if [ -d "$target" ]; then
          rmdir "$target" 2>/dev/null || return 1
          log "cleared the empty directory docker left at ${rel}"
        fi
        mode="${kind##*:}"
        ( umask 077; mkdir -p "$(dirname "$target")" ) || return 1
        if [ ! -e "$target" ]; then
          ( umask 077; : > "$target" ) || return 1
          chmod "$mode" "$target" || return 1
        fi
        ;;
    esac
    FAIL_REASON=""
    log "reconciled missing host path ${rel}"
  done

  # AI-2416: the compose that recreates Keycloak under uid 10001 needs the
  # files Keycloak mounts readable to it, before it is put in place.
  if grep -qE '^    user: "10001:0"' "$STAGED_COMPOSE"; then
    FAIL_REASON="required host file keycloak-realm-export.json could not be obtained"
    keycloak_mounts_readable || return 1
    FAIL_REASON=""
  fi

  ts="$(date -u '+%Y%m%d-%H%M%S')"
  backup="${BACKUP_DIR}/docker-compose.yml.pre-update-${ts}"
  mkdir -p "$BACKUP_DIR"
  if [ -f "$COMPOSE_FILE" ] && ! cp -p "$COMPOSE_FILE" "$backup"; then
    FAIL_REASON="could not back up the existing compose file"
    return 1
  fi
  if ! mv -f "$STAGED_COMPOSE" "$COMPOSE_FILE"; then
    FAIL_REASON="could not install the new compose file"
    return 1
  fi
  COMPOSE_BACKUP="$backup"
  COMPOSE_CHANGED=1
  log "compose reconciled to ${TARGET_TAG} (previous kept at ${backup})"
  return 0
}

# ── Login theme refresh (AI-2491) ─────────────────────────────────────────────
# stage_host_assets fetches a host file only when the box has none, so a box
# keeps the files of its first install. For the login theme that is wrong: it
# is a release file, nothing on the box edits it, and its fixes (AI-1808, the
# dark password field) never reached a box installed before them. So every
# update brings the theme to the release's copy when the two differ.
#
# stage_theme_refresh fetches and checks it into the work area and changes
# nothing; install_theme_refresh swaps it in after the image is verified. The
# box's previous theme is kept as backups/keycloak-theme.pre-update-<time> (the
# last one only). A theme the box points elsewhere (a symbolic link) is the
# operator's and is left alone. A theme that does not match the signed manifest
# refuses the update, like every other release file; one that cannot be
# downloaded only keeps the old theme, with a warning. A rollback keeps the new
# theme: it is CSS and messages for the same login pages.
stage_theme_refresh() {
  local rel="keycloak-theme" archive="${STAGE_DIR}/theme-refresh.tar.gz"
  local unpacked="${STAGE_DIR}/theme-refresh" target compose rc entry
  STAGED_THEME=""
  target="${PANEL_DIR}/${rel}"
  compose="${STAGED_COMPOSE:-$COMPOSE_FILE}"
  grep -qF -- "$rel" "$compose" 2>/dev/null || return 0
  # Absent (or the empty folder Docker leaves): stage_host_assets fetches it.
  for entry in ${STAGED_ASSETS[@]+"${STAGED_ASSETS[@]}"}; do
    [ "${entry%%|*}" = "$rel" ] && return 0
  done
  [ -d "$target" ] || return 0
  if [ -L "$target" ]; then
    log "left the login theme as it is: ${rel} is a symbolic link"
    return 0
  fi
  jq -e '.files | has("keycloak-theme.tar.gz")' "$MANIFEST_FILE" >/dev/null 2>&1 || return 0
  fetch_release_file keycloak-theme.tar.gz "$archive"; rc=$?
  case "$rc" in
    0) ;;
    1) log "WARNING: could not download the login theme of release ${TARGET_TAG}; keeping the current one"; return 0 ;;
    *) return 1 ;;
  esac
  rm -rf "$unpacked"
  if ! unpack_archive "$archive" "$unpacked" "$rel"; then
    FAIL_REASON="required host file ${rel} could not be obtained"
    return 1
  fi
  rm -f "$archive"
  if diff -rq "$target" "${unpacked}/${rel}" >/dev/null 2>&1; then
    rm -rf "$unpacked"
    return 0
  fi
  STAGED_THEME="${unpacked}/${rel}"
  return 0
}

install_theme_refresh() {
  local target="${PANEL_DIR}/keycloak-theme" ts backup old
  [ -n "$STAGED_THEME" ] || return 0
  ts="$(date -u '+%Y%m%d-%H%M%S')"
  backup="${BACKUP_DIR}/keycloak-theme.pre-update-${ts}"
  mkdir -p "$BACKUP_DIR" || return 1
  for old in "${BACKUP_DIR}"/keycloak-theme.pre-update-*; do
    [ -d "$old" ] && [ ! -L "$old" ] && rm -rf -- "$old"
  done
  # Two renames on one filesystem: Keycloak never sees a half-written theme.
  if ! mv "$target" "$backup"; then
    FAIL_REASON="required host file keycloak-theme could not be obtained"
    return 1
  fi
  if ! mv "$STAGED_THEME" "$target"; then
    mv "$backup" "$target" 2>/dev/null || true
    FAIL_REASON="required host file keycloak-theme could not be obtained"
    return 1
  fi
  chmod -R go+rX "$target" 2>/dev/null || true
  THEME_CHANGED=1
  log "login theme refreshed to release ${TARGET_TAG} (previous kept at ${backup})"
  return 0
}

# The GPU overlay is named with an explicit -f by install.sh and is NEVER
# auto-merged (AI-428). Omitting it from a full `up` would recreate ollama
# without host-GPU access — which is exactly why this script only ever touched
# `--no-deps panel` before compose reconciliation existed.
compose_args_init() {
  COMPOSE_ARGS=(--project-directory "$PANEL_DIR" -f "$COMPOSE_FILE")
  if [ -f "${PANEL_DIR}/docker-compose.gpu.yml" ]; then
    COMPOSE_ARGS+=(-f "${PANEL_DIR}/docker-compose.gpu.yml")
  fi
}

# migrate_platform_hostnames — AI-832. The proxy and the AI gateway have a leg in
# every tenant network they serve, and Docker answers a container's lookups from
# the tenant network first. A tenant service named "ollama" or "postgresql" (two
# catalog templates are) would then answer the gateway's lookup of its own
# upstream or database. So the three places where an install written before
# AI-832 names a platform dependency by its Compose service name are switched to
# the container name, which no tenant container can carry:
#
#   .env                 PANEL_INTERNAL_URL=http://panel:…        → aiadminpanel_panel
#   .env                 LITELLM_DATABASE_URL=…@postgresql:…      → aiadminpanel_postgresql
#   litellm-config.yaml  api_base: http://ollama:…                → aiadminpanel_ollama
#
# Only those exact short names are rewritten; a host the operator chose (an IP,
# a full host name) is left alone. Idempotent. The container names resolve on
# every release's networks, so this is not undone on rollback. Until it has run
# the panel refuses the deploys that would be affected and says why.
#
# AI-1213: the same pass adds PANEL_INTERNAL_URL when .env has no value for it.
# The installer writes it, but keeps an .env that already existed, so a box
# first installed before 2026-03 lacks it, and the panel then refuses to deploy
# the apps that must be locked (AI-1186). A value that is there is never
# replaced; an empty one counts as missing, as it does for the panel.
migrate_platform_hostnames() {
  local ts env_backup="" rename=0 add_internal=0
  ts="$(date -u '+%Y%m%d-%H%M%S')"
  if [ -f "$ENV_FILE" ]; then
    grep -qE '^(PANEL_INTERNAL_URL=http://panel:|LITELLM_DATABASE_URL=[^[:space:]]*@postgresql:)' "$ENV_FILE" && rename=1
    grep -qE '^PANEL_INTERNAL_URL=[^[:space:]]' "$ENV_FILE" || add_internal=1
  fi
  if [ "$rename" = "1" ] || [ "$add_internal" = "1" ]; then
    mkdir -p "$BACKUP_DIR"
    env_backup="${BACKUP_DIR}/env.pre-platform-names-${ts}"
    # .env holds credentials: the copy is created owner-only.
    if ! (umask 077 && cp "$ENV_FILE" "$env_backup") || ! chmod 600 "$env_backup"; then
      FAIL_REASON="could not back up .env before switching platform host names"
      return 1
    fi
  fi
  if [ "$rename" = "1" ]; then
    if ! sed -i -E \
        -e "s#^(PANEL_INTERNAL_URL=http://)panel:#\\1${PANEL_CONTAINER}:#" \
        -e "s#^(LITELLM_DATABASE_URL=[^[:space:]]*@)postgresql:#\\1${PG_CONTAINER}:#" \
        "$ENV_FILE"; then
      FAIL_REASON="could not switch platform host names in .env"
      return 1
    fi
    PLATFORM_HOSTS_CHANGED=1
    log "platform host names in .env switched to container names (previous kept at ${env_backup})"
  fi
  if [ "$add_internal" = "1" ]; then
    # Drop an empty assignment, end the last line if it is open, then append.
    # The panel is recreated by every update and --reapply, so it reads the
    # new value without anything else being restarted here. The value is the
    # literal the installer writes, not $PANEL_CONTAINER: that variable can be
    # overridden, and the proxy must reach the panel by its host-unique
    # container name, never a short name a tenant container could answer to
    # (AI-832 F1, guarded by tests/installer/platform_container_names.bats).
    if ! sed -i -E '/^PANEL_INTERNAL_URL=[[:space:]]*$/d' "$ENV_FILE" \
        || ! { [ -z "$(tail -c1 "$ENV_FILE")" ] || echo >> "$ENV_FILE"; } \
        || ! echo "PANEL_INTERNAL_URL=http://aiadminpanel_panel:8080" >> "$ENV_FILE"; then
      FAIL_REASON="could not add PANEL_INTERNAL_URL to .env"
      return 1
    fi
    log "PANEL_INTERNAL_URL=http://aiadminpanel_panel:8080 added to .env (previous kept at ${env_backup})"
  fi
  if [ -f "$GATEWAY_CONFIG" ] && grep -qE "^[[:space:]]*api_base:[[:space:]]*[\"']?http://ollama:" "$GATEWAY_CONFIG"; then
    mkdir -p "$BACKUP_DIR"
    if ! cp -p "$GATEWAY_CONFIG" "${BACKUP_DIR}/litellm-config.yaml.pre-platform-names-${ts}"; then
      FAIL_REASON="could not back up the gateway config before switching platform host names"
      return 1
    fi
    if ! sed -i -E "s#^([[:space:]]*api_base:[[:space:]]*[\"']?http://)ollama:#\\1${OLLAMA_CONTAINER}:#" "$GATEWAY_CONFIG"; then
      FAIL_REASON="could not switch the gateway upstream to its container name"
      return 1
    fi
    PLATFORM_HOSTS_CHANGED=1
    log "gateway upstream switched to its container name (previous kept at ${BACKUP_DIR}/litellm-config.yaml.pre-platform-names-${ts})"
  fi
  return 0
}

# ollama_mem_limit_mb — AI-2492. The bundled model engine's memory limit in MB,
# sized from host RAM: min(total / 2, total - 3072), never below 1024. A copy of
# the installer's function in scripts/lib/ai.sh (this file runs standalone);
# tests/installer/ai_2492_ollama_memory_cap.bats keeps the two identical.
ollama_mem_limit_mb() {
  if [ -n "${AAP_OLLAMA_MEM_LIMIT_MB:-}" ] && [ "$AAP_OLLAMA_MEM_LIMIT_MB" -gt 0 ] 2>/dev/null; then
    echo "$AAP_OLLAMA_MEM_LIMIT_MB"
    return 0
  fi
  local kb total=0 half rest limit
  kb="$(awk '/^MemTotal:/ { print $2; exit }' "${MEMINFO_FILE:-/proc/meminfo}" 2>/dev/null || true)"
  if [ -n "$kb" ] && [ "$kb" -gt 0 ] 2>/dev/null; then total=$(( kb / 1024 )); fi
  half=$(( total / 2 ))
  rest=$(( total - 3072 ))
  limit=$half
  [ "$rest" -lt "$limit" ] && limit=$rest
  [ "$limit" -lt 1024 ] && limit=1024
  echo "$limit"
}

# reconcile_ollama_mem_limit — AI-2492. The release's Compose file caps the
# bundled model engine at OLLAMA_MEM_LIMIT (no swap on top) and falls back to
# 3g when .env has no value. The installer writes a host-sized value, but keeps
# an .env that already existed, so an install from before AI-2492 gets one
# here. A value that is there is never replaced (the operator may have set
# it); an empty one counts as missing. Not undone on rollback: an older
# Compose file ignores the line.
reconcile_ollama_mem_limit() {
  local ts env_backup limit
  [ -f "$ENV_FILE" ] || return 0
  grep -qE '^OLLAMA_MEM_LIMIT=[^[:space:]]' "$ENV_FILE" && return 0
  ts="$(date -u '+%Y%m%d-%H%M%S')"
  mkdir -p "$BACKUP_DIR"
  env_backup="${BACKUP_DIR}/env.pre-ollama-mem-limit-${ts}"
  # .env holds credentials: the copy is created owner-only.
  if ! (umask 077 && cp "$ENV_FILE" "$env_backup") || ! chmod 600 "$env_backup"; then
    FAIL_REASON="could not back up .env before setting the model engine memory limit"
    return 1
  fi
  limit="$(ollama_mem_limit_mb)"
  if ! sed -i -E '/^OLLAMA_MEM_LIMIT=[[:space:]]*$/d' "$ENV_FILE" \
      || ! { [ -z "$(tail -c1 "$ENV_FILE")" ] || echo >> "$ENV_FILE"; } \
      || ! echo "OLLAMA_MEM_LIMIT=${limit}m" >> "$ENV_FILE"; then
    FAIL_REASON="could not set the model engine memory limit in .env"
    return 1
  fi
  OLLAMA_LIMIT_CHANGED=1
  log "OLLAMA_MEM_LIMIT=${limit}m added to .env from host memory (previous kept at ${env_backup})"
  return 0
}

# ── On-demand local AI engine (AI-2746) ───────────────────────────────────────
# docker-compose.yml puts the bundled Ollama behind the Compose profile
# "ollama": a fresh install neither pulls nor starts the 8.5 GB engine. The
# panel downloads its image and then asks for it with update/ollama-request.json;
# this updater, the only actor on the host that runs `docker compose`, starts
# it. COMPOSE_PROFILES in .env (Compose reads it from the project directory)
# makes every later `docker compose` call include the engine.
#
# The installer (scripts/lib/ai.sh) carries the same two .env functions;
# tests/installer/ai_2746_ollama_on_demand.bats keeps them identical.

# ollama_profile_enabled <env_file> — true when COMPOSE_PROFILES there names
# the "ollama" profile.
ollama_profile_enabled() {
  local line
  line="$(grep -E '^COMPOSE_PROFILES=' "$1" 2>/dev/null | tail -1)" || return 1
  line="${line#COMPOSE_PROFILES=}"
  line="$(printf '%s' "$line" | tr -d "\"' ")"
  case ",${line}," in
    *,ollama,*) return 0 ;;
  esac
  return 1
}

# add_ollama_profile <env_file> — add "ollama" to COMPOSE_PROFILES, keeping any
# profile already named there. Idempotent; ends an open last line first.
add_ollama_profile() {
  local env_file="$1" current
  ollama_profile_enabled "$env_file" && return 0
  current="$(grep -E '^COMPOSE_PROFILES=' "$env_file" 2>/dev/null | tail -1)"
  current="$(printf '%s' "${current#COMPOSE_PROFILES=}" | tr -d "\"' ")"
  sed -i -E '/^COMPOSE_PROFILES=/d' "$env_file" || return 1
  if [ -s "$env_file" ] && [ -n "$(tail -c1 "$env_file")" ]; then
    echo >> "$env_file" || return 1
  fi
  echo "COMPOSE_PROFILES=${current:+${current},}ollama" >> "$env_file"
}

# reconcile_ollama_profile — an install from before AI-2746 runs the engine
# without the profile line. Compose would leave that container running but
# never pull or recreate it again (a new pin, a new memory limit), so the line
# is added when the engine's container exists. Backed up first: .env holds
# credentials. Not undone on rollback: an older Compose file has no profile.
reconcile_ollama_profile() {
  local ts env_backup
  [ -f "$ENV_FILE" ] || return 0
  ollama_profile_enabled "$ENV_FILE" && return 0
  docker inspect "$OLLAMA_CONTAINER" >/dev/null 2>&1 || return 0
  ts="$(date -u '+%Y%m%d-%H%M%S')"
  mkdir -p "$BACKUP_DIR"
  env_backup="${BACKUP_DIR}/env.pre-ollama-profile-${ts}"
  if ! (umask 077 && cp "$ENV_FILE" "$env_backup") || ! chmod 600 "$env_backup"; then
    FAIL_REASON="could not back up .env before keeping the local AI engine"
    return 1
  fi
  if ! add_ollama_profile "$ENV_FILE"; then
    FAIL_REASON="could not add COMPOSE_PROFILES=ollama to .env"
    return 1
  fi
  log "COMPOSE_PROFILES=ollama added to .env: the local AI engine exists on this host (previous kept at ${env_backup})"
}

# write_ollama_result <status> [reason] — update/ollama-result.json for the
# panel, by rename like publish_result (a link there is replaced, not followed).
write_ollama_result() {
  local status="$1" reason="${2:-}" tmp
  mkdir -p "$UPDATE_DIR"
  tmp="$(mktemp "${WORK_DIR}/ollama-result.XXXXXX")" || { log "could not write the engine result: no work area at ${WORK_DIR}"; return 1; }
  if ! jq -cn --arg status "$status" --arg reason "$reason" --arg at "$(now)" \
      '{status: $status, reason: $reason, finishedAt: $at}' > "$tmp"; then
    rm -f "$tmp"
    return 1
  fi
  chmod 644 "$tmp"
  if ! mv -fT "$tmp" "$OLLAMA_RESULT_FILE" 2>/dev/null; then
    rm -f "$tmp"
    log "could not put the engine result in place at ${OLLAMA_RESULT_FILE}"
    return 1
  fi
  [ "$status" = "in-progress" ] || ENGINE_RESULT_WRITTEN=1
  log "local AI engine: ${status}${reason:+ — $reason}"
}

# start_ollama_engine — the panel asked for the on-demand engine. The request
# is consumed unread (it names nothing: the service, its image and its settings
# all come from the host's own Compose file). Adds the profile to .env, then
# starts the one service with the host's Compose arguments (the GPU overlay
# included). Compose pulls the image only when the panel has not already.
start_ollama_engine() {
  local out
  rm -rf -- "$OLLAMA_REQUEST_FILE"
  write_ollama_result "in-progress"
  if [ -f "$ENV_FILE" ] && ! add_ollama_profile "$ENV_FILE"; then
    write_ollama_result "failed" "could not add COMPOSE_PROFILES=ollama to ${ENV_FILE}"
    return 1
  fi
  if ! out="$(docker compose "${COMPOSE_ARGS[@]}" --profile ollama up -d --no-deps ollama 2>&1)"; then
    log "$out"
    write_ollama_result "failed" "docker compose could not start the local AI engine: $(printf '%s' "$out" | tail -n 3 | tr '\n' ' ' | cut -c1-300)"
    return 1
  fi
  write_ollama_result "succeeded"
}

# ensure_forwarding_pin — AI-832 (review F3). The proxy, the AI gateway and the
# bundled Ollama have a leg in every customer network they serve, and Docker
# starts a container with IP forwarding on: such a container routes between
# customers. The Compose definition switches it off (net.ipv4.ip_forward=0), and
# the panel refuses to attach a platform container that runs without it. A full
# `up` after a Compose change recreates them anyway; this covers the box whose
# Compose file already is the release's while a container still runs from the
# older definition (a file replaced by hand, an earlier run cut short). Plain
# `up -d <service>` recreates only when the definition differs from the running
# container, so a Compose file without the setting changes nothing — and then
# this says so, because the panel keeps refusing until a Compose file with the
# setting is installed. Never fails the update: the panel is what enforces it.
forwarding_pinned() {
  [ "$(docker inspect -f '{{index .HostConfig.Sysctls "net.ipv4.ip_forward"}}' "$1" 2>/dev/null)" = "0" ]
}

ensure_forwarding_pin() {
  local services pair svc name
  services="$(docker compose "${COMPOSE_ARGS[@]}" config --services 2>/dev/null)" || return 0
  for pair in "traefik:${TRAEFIK_CONTAINER}" "litellm:${LITELLM_CONTAINER}" "ollama:${OLLAMA_CONTAINER}"; do
    svc="${pair%%:*}"; name="${pair#*:}"
    grep -qx "$svc" <<<"$services" || continue
    forwarding_pinned "$name" && continue
    docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps "$svc" >/dev/null 2>&1 || true
    if forwarding_pinned "$name"; then
      log "${name} recreated with packet forwarding switched off; the panel re-attaches it to customer networks"
    else
      log "WARNING: ${name} still runs with packet forwarding on, because the Compose file on this host does not switch it off; the panel will not attach it to customer networks until an update installs this release's Compose file (see the upgrade notes, \"Proxy and gateway containers\")"
    fi
  done
  return 0
}

# unpinned_platforms — the platform containers of this install that still run
# with packet forwarding on, space separated. Read from Docker after the run,
# not inferred from what the run did.
unpinned_platforms() {
  local services pair svc name out=""
  services="$(docker compose "${COMPOSE_ARGS[@]}" config --services 2>/dev/null)" || return 0
  for pair in "traefik:${TRAEFIK_CONTAINER}" "litellm:${LITELLM_CONTAINER}" "ollama:${OLLAMA_CONTAINER}"; do
    svc="${pair%%:*}"; name="${pair#*:}"
    grep -qx "$svc" <<<"$services" || continue
    forwarding_pinned "$name" || out="${out:+$out }${name}"
  done
  printf '%s' "$out"
}

# bring_up — recreate what changed. After a compose change this must be a FULL
# `up`: `--no-deps panel` cannot create a service that did not exist before, so
# refreshing compose without widening this would have fixed nothing. Plain
# `up -d` still only touches containers whose definition actually changed.
# keycloak_mounts_readable — AI-2416. Keycloak used to run as the image's
# uid 1000 and now runs as uid 10001, group 0, so no host login user can read
# its environment. The realm export and the login theme it mounts read-only
# then have to be readable by that uid. The installer and this updater write
# them 644 and 755, owned by root; a box where they were left owned by uid 1000
# and closed to others would start Keycloak without them. Group and others get
# read on files and read and search on folders; nothing else changes, and an
# entry that already has those bits is not touched, so a second run does
# nothing. Both are public release files that hold no secret.
#
# Root changing modes where another user can still add or swap entries could
# be raced: that user swaps an entry for a symlink, or plants a hard link to a
# system file, and root opens up its target. So:
#   - a path that is a symlink, or a tree with a folder group or others can
#     write, is left as it is with a warning;
#   - folders owned by another user (uid 1000) are first handed to this
#     updater's uid with `chown -R -h`, which changes links themselves and never
#     follows one, so that user can add nothing while modes change;
#   - only files with a single link are opened up; others get a warning.
# An unreadable theme costs the branded login page. An unreadable realm export
# stops Keycloak at start ("Failed to run import ... Permission denied", seen
# with 26.8.2), even when the realm already exists, so then this returns 1 and
# the update is refused before the new compose file is put in place.
keycloak_mounts_readable() {
  local rel target me changed
  me="$(id -u)"
  for rel in keycloak-realm-export.json keycloak-theme; do
    target="${PANEL_DIR}/${rel}"
    if [ -L "$target" ]; then
      log "WARNING: left ${rel} as it is: it is a symbolic link. Keycloak (uid 10001) needs to read it; see the upgrade notes"
      continue
    fi
    [ -e "$target" ] || continue
    if [ -n "$(find "$target" -type d -perm /022 -print -quit 2>/dev/null)" ]; then
      log "WARNING: left ${rel} as it is: other users can write a folder in it. Keycloak (uid 10001) needs to read it; see the upgrade notes"
      continue
    fi
    if [ -n "$(find "$target" -type d ! -user "$me" -print -quit 2>/dev/null)" ]; then
      if ! chown -R -h "${me}:0" "$target" 2>/dev/null; then
        log "WARNING: left ${rel} as it is: could not take it over from its owner. Keycloak (uid 10001) needs to read it; see the upgrade notes"
        continue
      fi
      log "${rel} was owned by another user; it now belongs to uid ${me}, group 0"
      # Checked again: until the chown, the old owner could still change modes.
      if [ -n "$(find "$target" -type d -perm /022 -print -quit 2>/dev/null)" ]; then
        log "WARNING: left ${rel}'s modes as they are: other users can write a folder in it. Keycloak (uid 10001) needs to read it; see the upgrade notes"
        continue
      fi
    fi
    if [ -n "$(find "$target" -type f ! -links 1 ! -perm -044 -print -quit 2>/dev/null)" ]; then
      log "WARNING: some files in ${rel} have more than one link and stay as they are. Keycloak (uid 10001) needs to read them; see the upgrade notes"
    fi
    changed="$(find "$target" \( -type d ! -perm -055 -o -type f -links 1 ! -perm -044 \) \
      -print -exec chmod go+rX {} + 2>/dev/null | wc -l)"
    [ "$changed" -gt 0 ] && log "made ${rel} readable to Keycloak's uid 10001 (${changed} entries)"
  done
  target="${PANEL_DIR}/keycloak-realm-export.json"
  if [ -e "$target" ] && ! keycloak_can_read "$target"; then
    log "Keycloak (uid 10001, group 0) could not read ${target} and would not start; make it readable to others (chmod 644) and update again"
    return 1
  fi
  return 0
}

# keycloak_can_read <file> — whether uid 10001, group 0 may read the file a
# bind mount shows it (Docker resolves a symlinked host path itself).
keycloak_can_read() {
  local uid gid mode
  read -r uid gid mode < <(stat -L -c '%u %g %a' "$1" 2>/dev/null) || return 1
  mode=$((8#${mode}))
  [ $((mode & 4)) -ne 0 ] && return 0
  [ "$gid" = "0" ] && [ $((mode & 32)) -ne 0 ] && return 0
  [ "$uid" = "10001" ] && [ $((mode & 256)) -ne 0 ] && return 0
  return 1
}

bring_up() {
  # Before the panel: the new panel then finds the platform containers already
  # pinned, and its first pass attaches them.
  ensure_forwarding_pin
  if [ "$COMPOSE_CHANGED" = "1" ]; then
    run_logged docker compose "${COMPOSE_ARGS[@]}" up -d
  else
    run_logged docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps --force-recreate panel
  fi || return 1
  # The gateway reads its database URL and its config file only at start, and
  # compose does not notice a changed bind-mounted file. The panel re-attaches
  # the recreated gateway to the tenant networks by itself.
  if [ "$PLATFORM_HOSTS_CHANGED" = "1" ] \
      && docker compose "${COMPOSE_ARGS[@]}" config --services 2>/dev/null | grep -qx litellm; then
    run_logged docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps --force-recreate litellm || return 1
  fi
  # AI-2492: a limit added to .env under a Compose file that did not change.
  # Plain `up` recreates the engine only when its definition differs.
  if [ "$OLLAMA_LIMIT_CHANGED" = "1" ] && [ "$COMPOSE_CHANGED" != "1" ] \
      && docker compose "${COMPOSE_ARGS[@]}" config --services 2>/dev/null | grep -qx ollama; then
    run_logged docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps ollama || return 1
  fi
  # AI-2491: Keycloak caches its themes, and its bind mount still shows the
  # folder the refreshed theme replaced, so it starts again to read the new one.
  if [ "$THEME_CHANGED" = "1" ] \
      && docker compose "${COMPOSE_ARGS[@]}" config --services 2>/dev/null | grep -qx keycloak; then
    run_logged docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps --force-recreate keycloak || return 1
  fi
  return 0
}

apply_target() {
  # --reapply changes the host around the panel that is running: no new image,
  # and PANEL_VERSION stays what the operator set (pulling a floating "latest"
  # could bring a newer panel than the Compose file being installed).
  if [ "$REAPPLY" != "1" ]; then
    set_env_version "$TARGET_TAG"
    # Pull the digest that was verified, not the tag: the registry cannot hand
    # out anything else under a digest. The Compose file starts the panel as
    # <repository>:${PANEL_VERSION} and sets no pull policy, so giving the
    # verified image that name locally is what makes `up` start it.
    run_logged docker pull "${REGISTRY}@${IMAGE_DIGEST}" || return 1
    run_logged docker tag "${REGISTRY}@${IMAGE_DIGEST}" "${REGISTRY}:${TARGET_TAG}" || return 1
  fi
  bring_up || return 1
  return 0
}

# Health is read from Docker's own healthcheck status. The panel image defines
# `wget localhost:8080/healthz` as its healthcheck, so this is authoritative and
# avoids guessing the container's IP — which is ambiguous, since the panel is
# attached to several docker networks. Falls back to an in-container probe only
# if the image somehow declares no healthcheck.
wait_health() {
  local elapsed=0 status
  while [ "$elapsed" -lt "$HEALTH_CHECK_TIMEOUT" ]; do
    status="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$PANEL_CONTAINER" 2>/dev/null)"
    case "$status" in
      healthy)
        return 0
        ;;
      none)
        if docker exec "$PANEL_CONTAINER" wget -qO- http://localhost:8080/healthz >/dev/null 2>&1; then
          return 0
        fi
        ;;
    esac
    sleep "$HEALTH_CHECK_INTERVAL"
    elapsed=$((elapsed + HEALTH_CHECK_INTERVAL))
  done
  return 1
}

# close_ready_purposes — AI-1345. After a healthy update, ask the panel which
# kinds of stored secret have every value in the new format, and close each one
# that is not closed yet by appending it to the marker file. The panel reads
# the file only at start, so it is recreated once when anything was appended.
#
# Only ever ADDS lines, as root, from a count the panel makes at call time;
# nothing in the database or any API can remove one. Only a panel whose compose
# names the marker is asked: older images have no `secrets` command, and an
# unknown word would start a second server in their container.
close_ready_purposes() {
  local marker="${PANEL_DIR}/${LEGACY_CLOSED_REL}" ready purpose appended=""
  grep -qF -- "$LEGACY_CLOSED_REL" "$COMPOSE_FILE" 2>/dev/null || return 0
  [ -f "$marker" ] || return 0
  if ! ready="$(timeout 120 docker exec "$PANEL_CONTAINER" panel secrets reencrypt --status --ready 2>/dev/null)"; then
    log "WARNING: the panel did not report which kinds of secret are ready to close; none closed this time"
    return 0
  fi
  while IFS= read -r purpose; do
    # Purpose names only: anything else on stdout (a log line) is not one.
    [[ "$purpose" =~ ^[a-z0-9][a-z0-9-]*$ ]] || continue
    grep -qxF -- "$purpose" "$marker" && continue
    # End an open last line first, so the name lands on its own line.
    { [ ! -s "$marker" ] || [ -z "$(tail -c1 "$marker")" ] || echo >> "$marker"; } || return 1
    printf '%s\n' "$purpose" >> "$marker" || return 1
    appended="${appended:+$appended }${purpose}"
  done <<< "$ready"
  [ -n "$appended" ] || return 0
  log "closed the old secret format for: ${appended} (${LEGACY_CLOSED_REL}); recreating the panel to apply it"
  run_logged docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps --force-recreate panel || return 1
  wait_health
}

# ── Valkey major move (AI-2657) ───────────────────────────────────────────────
# The panel's Valkey holds refresh tokens, the blocklist of revoked tokens, TOTP
# replay guards and rate-limit counters, saved to /data/dump.rdb. A newer major
# reads an older major's file, but not the other way round: Valkey 8.1 stops at
# start on the file 9.x writes ("Can't handle RDB format version 81"). So the
# first release on a new Valkey major could not be rolled back: the restored
# Compose file starts the old Valkey on the new file, it exits, restarts, exits.
#
#   before the update changes anything (snapshot_valkey_before_major): when the
#     release's Compose file names a newer Valkey major than the one running,
#     the running Valkey saves, and its file is copied to
#     backups/valkey-<old>-pre-update-<time>.rdb (mode 600: it holds sessions).
#     No copy, no update: the run is refused with nothing changed.
#   on a rollback, before the previous release starts (undo_valkey_major):
#     1. stop the new Valkey (it saves on the way down);
#     2. load that file in a one-off container of the OLD image with
#        `--rdb-version-check relaxed` and SAVE, which writes it in the old
#        format with everything in it. Valkey documents this as best effort: it
#        aborts on anything the old major does not know (a type only the new
#        major has), and then nothing was written;
#     3. if that fails, move the new major's file aside (dump.rdb.valkey<new>-
#        <time>, kept) and put the copy from step one in its place. The old
#        major wrote that copy, so it loads; what was written since the update
#        (new sign-ins, tokens revoked since) is lost.
#
# Only dump.rdb is handled: the panel's Compose file runs Valkey with RDB
# snapshots and no append-only file. Later updates within one major read the
# same format and take no copy.

# staged_valkey_image <compose> — the image of the valkey service.
staged_valkey_image() {
  sed -nE '/^  valkey:[[:space:]]*$/,/^  [A-Za-z0-9_-]+:[[:space:]]*$/ s/^    image:[[:space:]]*["'"'"']?([^"'"'"'[:space:]#]+).*/\1/p' "$1" | head -n 1
}

# valkey_image_major <image> — the major version a valkey image tag names
# (valkey/valkey:9.2.0-alpine@sha256:… → 9), or nothing.
valkey_image_major() {
  local ref="${1%@*}" tag major
  case "$ref" in *:*) ;; *) return 0 ;; esac
  tag="${ref##*:}"
  major="${tag%%[.-]*}"
  [[ "$major" =~ ^[0-9]+$ ]] && echo "$major"
  return 0
}

# snapshot_valkey_before_major — see above. Sets VALKEY_* when this update
# moves Valkey to a newer major; FAIL_REASON when the copy cannot be taken.
snapshot_valkey_before_major() {
  local image old_image new old vol ts snap reply
  [ -n "$STAGED_COMPOSE" ] || return 0
  image="$(staged_valkey_image "$STAGED_COMPOSE")"
  new="$(valkey_image_major "$image")"
  [ -n "$new" ] || return 0
  old_image="$(docker inspect -f '{{.Config.Image}}' "$VALKEY_CONTAINER" 2>/dev/null)"
  old="$(valkey_image_major "$old_image")"
  { [ -n "$old" ] && [ "$old" -lt "$new" ]; } || return 0
  # The same reason as the database dumps: to the operator this is the same
  # refusal ("the data could not be saved first"), and it needs no new key in
  # seven locales. The log says which.
  FAIL_REASON="database backup failed — refusing to update"
  vol="$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/data"}}{{if eq .Type "volume"}}{{.Name}}{{else}}{{.Source}}{{end}}{{end}}{{end}}' "$VALKEY_CONTAINER" 2>/dev/null)"
  if [ -z "$vol" ]; then
    log "Valkey moves from ${old} to ${new}, but ${VALKEY_CONTAINER} has no /data mount to keep a copy of"
    return 1
  fi
  reply="$(docker exec "$VALKEY_CONTAINER" valkey-cli SAVE 2>&1 | tr -d '\r')"
  if [ "$reply" != "OK" ]; then
    log "Valkey moves from ${old} to ${new}, but ${VALKEY_CONTAINER} did not save its data: ${reply:-no answer}"
    return 1
  fi
  ts="$(date -u '+%Y%m%d-%H%M%S')"
  snap="${BACKUP_DIR}/valkey-${old}-pre-update-${ts}.rdb"
  mkdir -p "$BACKUP_DIR" || return 1
  if ! ( umask 077; docker exec "$VALKEY_CONTAINER" cat /data/dump.rdb > "$snap" ) || [ ! -s "$snap" ]; then
    rm -f "$snap"
    log "Valkey moves from ${old} to ${new}, but its data file could not be copied to ${snap}"
    return 1
  fi
  FAIL_REASON=""
  VALKEY_SNAPSHOT="$snap"
  VALKEY_OLD_IMAGE="$old_image"
  VALKEY_VOLUME="$vol"
  VALKEY_FROM="$old"
  VALKEY_TO="$new"
  log "Valkey moves from ${old} to ${new}; its data is copied to ${snap} for a rollback"
  return 0
}

# valkey_relaxed_resave — step 2 above: the old image loads the file relaxed
# and saves it in its own format. Fails, having written nothing, when it cannot.
valkey_relaxed_resave() {
  local waited=0 running reply rc=1
  docker rm -f "$VALKEY_ROLLBACK_CONTAINER" >/dev/null 2>&1 || true
  if ! docker run -d --name "$VALKEY_ROLLBACK_CONTAINER" --network none \
      -v "${VALKEY_VOLUME}:/data" "$VALKEY_OLD_IMAGE" \
      valkey-server --save "" --appendonly no --rdb-version-check relaxed >/dev/null 2>&1; then
    log "could not start Valkey ${VALKEY_FROM} once to read the data relaxed"
    return 1
  fi
  while [ "$waited" -lt "$VALKEY_LOAD_TIMEOUT" ]; do
    running="$(docker inspect -f '{{.State.Running}}' "$VALKEY_ROLLBACK_CONTAINER" 2>/dev/null)"
    [ "$running" = "true" ] || break
    if [ "$(docker exec "$VALKEY_ROLLBACK_CONTAINER" valkey-cli ping 2>/dev/null | tr -d '\r')" = "PONG" ]; then
      reply="$(docker exec "$VALKEY_ROLLBACK_CONTAINER" valkey-cli SAVE 2>&1 | tr -d '\r')"
      [ "$reply" = "OK" ] && rc=0
      break
    fi
    sleep 1
    waited=$((waited + 1))
  done
  if [ "$rc" != "0" ]; then
    log "Valkey ${VALKEY_FROM} could not read the Valkey ${VALKEY_TO} data, even relaxed; its log:"
    docker logs --tail 5 "$VALKEY_ROLLBACK_CONTAINER" 2>&1 | while IFS= read -r line; do log "  ${line}"; done
  fi
  docker rm -f "$VALKEY_ROLLBACK_CONTAINER" >/dev/null 2>&1 || true
  return "$rc"
}

# undo_valkey_major — see above. Runs on a rollback, before the previous
# release starts. Nothing to do when this update did not move Valkey's major.
undo_valkey_major() {
  local current aside
  [ -n "$VALKEY_SNAPSHOT" ] || return 0
  current="$(docker inspect -f '{{.Config.Image}}' "$VALKEY_CONTAINER" 2>/dev/null)"
  if [ "$(valkey_image_major "$current")" = "$VALKEY_FROM" ]; then
    # The new Valkey never started (the update failed before it): the file is
    # still the old major's.
    return 0
  fi
  log "putting Valkey's data back in the Valkey ${VALKEY_FROM} format before the previous version starts"
  docker stop -t 30 "$VALKEY_CONTAINER" >/dev/null 2>&1 || true
  if valkey_relaxed_resave; then
    log "Valkey's data is in the Valkey ${VALKEY_FROM} format again; nothing was lost"
    return 0
  fi
  aside="dump.rdb.valkey${VALKEY_TO}-$(date -u '+%Y%m%d-%H%M%S')"
  log "WARNING: putting back the Valkey copy from before the update (${VALKEY_SNAPSHOT}); sign-ins and token revocations since the update are lost. The Valkey ${VALKEY_TO} file is kept in the volume as ${aside}"
  if docker run --rm --network none --user 0 --entrypoint sh \
      -v "${VALKEY_VOLUME}:/data" -v "${VALKEY_SNAPSHOT}:/snapshot.rdb:ro" "$VALKEY_OLD_IMAGE" \
      -c 'set -e; cp /snapshot.rdb /data/.dump.rdb.restore; chown valkey:valkey /data/.dump.rdb.restore 2>/dev/null || true; if [ -e /data/dump.rdb ]; then mv /data/dump.rdb "/data/$1"; fi; mv /data/.dump.rdb.restore /data/dump.rdb' \
      sh "$aside" >/dev/null 2>&1; then
    return 0
  fi
  log "WARNING: could not put the Valkey copy back; restore ${VALKEY_SNAPSHOT} into the volume ${VALKEY_VOLUME} as dump.rdb by hand (see the upgrade notes, Valkey 9.2)"
  return 1
}

rollback() {
  local reason="$1"
  log "rolling back to ${PREV_VERSION}: ${reason}"
  set_env_version "$PREV_VERSION"
  # AI-2653: the old Postgres must find its data where it left it before
  # anything starts again. If that fails, nothing is started: neither Compose
  # file finds a cluster it can safely use, and the operator recovers by hand.
  if ! undo_postgres_upgrade; then
    if [ "$COMPOSE_CHANGED" = "1" ] && [ -n "$COMPOSE_BACKUP" ] && [ -f "$COMPOSE_BACKUP" ]; then
      cp -p "$COMPOSE_BACKUP" "$COMPOSE_FILE" || true
    fi
    finish_failed "the PostgreSQL upgrade from ${PG_UPGRADE_FROM} to ${PG_UPGRADE_TO} failed and the ${PG_UPGRADE_FROM} data could not be put back automatically; nothing was started (data in volume ${PG_UPGRADE_VOLUME}, dump in ${PG_UPGRADE_DIR}; see the upgrade notes, PostgreSQL 18)"
    return 1
  fi
  [ -z "$PG_UPGRADE_TO" ] || rm -f "$PG_UPGRADE_STATE"
  # A rolled-back image must run against the compose it shipped with, so restore
  # the compose we replaced. Without this the box would keep the new topology
  # while running the old binary — a combination nothing has ever tested.
  if [ "$COMPOSE_CHANGED" = "1" ] && [ -n "$COMPOSE_BACKUP" ] && [ -f "$COMPOSE_BACKUP" ]; then
    log "restoring the previous compose from ${COMPOSE_BACKUP}"
    cp -p "$COMPOSE_BACKUP" "$COMPOSE_FILE" || true
  fi
  # AI-2657: the previous Valkey must be able to read its data before it starts.
  undo_valkey_major || true
  bring_up || true
  finish_rollback "$reason"
}

# ── DNS-01 bridge migration (AI-2392) ─────────────────────────────────────────
# Installs made before the DNS-01 bridge (AI-2295) run Traefik's DNS-01 resolver
# (CERT_RESOLVER=letsencrypt-dns, the installer's TLS_MODE=cloudflare) with its
# own Cloudflare provider and CF_DNS_API_TOKEN. Their .env has no
# DNS01_BRIDGE_SECRET and no DNS01_PROVIDER, and the installer never rewrites
# an existing .env. This moves them to the bridge in two steps:
#
#   1. before the panel is recreated: add a generated DNS01_BRIDGE_SECRET, so
#      the new panel starts its bridge. Traefik keeps the Cloudflare provider,
#      so nothing about certificates changes yet;
#   2. after the update is healthy: recreate Traefik so it holds the secret,
#      ask the bridge from inside Traefik (POST /check: Traefik's network, its
#      address and its secret, and a DNS token that reaches the panel domain's
#      zone, without writing a record). Only on a 200 is DNS01_PROVIDER=httpreq
#      written and Traefik recreated; the check then runs again against the new
#      Traefik, and the .env copied just before is put back, and Traefik with
#      it, when it does not pass.
#
# Certificate renewals never depend on an unproven bridge: until step 2 has
# passed, Traefik keeps its own token. When /check says the bridge's token is
# the one saved in Settings, Traefik's copy of CF_DNS_API_TOKEN is retired too
# (TRAEFIK_CF_DNS_API_TOKEN set empty; docker-compose.yml). CF_DNS_API_TOKEN
# itself stays in .env: the panel falls back to it, and a rollback to a release
# from before the bridge runs Traefik's Cloudflare provider with it again.
#
# Idempotent: a .env that names DNS01_PROVIDER (any value: the installer's, or
# the operator's own choice) is left alone, and a secret is generated once.
# Nothing here fails an update; a step that cannot run is logged and skipped.
# The secret is never logged, never on a command line (the check builds its
# request inside Traefik from Traefik's own environment) and never in a result.
DNS01_CHECK_TIMEOUT="${DNS01_CHECK_TIMEOUT:-60}"
DNS01_CHECK_INTERVAL="${DNS01_CHECK_INTERVAL:-5}"
# Where the last passed check said the bridge's token comes from.
DNS01_CHECK_SOURCE=""

# The request, run by Traefik's shell: printf is a builtin and base64 and nc
# read the credentials on stdin, so they never appear in a process list.
# shellcheck disable=SC2016 # expanded inside the Traefik container
DNS01_CHECK_SCRIPT='[ -n "${HTTPREQ_PASSWORD:-}" ] || exit 3
hp="${HTTPREQ_ENDPOINT#http://}"; hp="${hp%%/*}"
auth="$(printf "%s:%s" "${HTTPREQ_USERNAME:-}" "$HTTPREQ_PASSWORD" | base64 | tr -d "\n")"
printf "POST /check HTTP/1.0\r\nHost: %s\r\nAuthorization: Basic %s\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" "${hp%%:*}" "$auth" | nc -w 10 "${hp%%:*}" "${hp##*:}"'

# env_value KEY — the last value .env assigns KEY, without quotes.
env_value() {
  grep -E "^$1=" "$ENV_FILE" 2>/dev/null | tail -1 | cut -d= -f2- | tr -d "\"'"
}

dns01_mode() { [ "$(env_value CERT_RESOLVER)" = "letsencrypt-dns" ]; }

# The Compose file on the box can run Traefik through the bridge.
# shellcheck disable=SC2016 # literal Compose text
compose_has_bridge() {
  grep -qF -- 'dnschallenge.provider=${DNS01_PROVIDER' "$COMPOSE_FILE" 2>/dev/null \
    && grep -qF 'HTTPREQ_PASSWORD: ${DNS01_BRIDGE_SECRET' "$COMPOSE_FILE" 2>/dev/null
}

# env_append LINE... — end an open last line, then append; .env stays 600.
env_append() {
  { [ ! -s "$ENV_FILE" ] || [ -z "$(tail -c1 "$ENV_FILE")" ] || echo >> "$ENV_FILE"; } || return 1
  printf '%s\n' "$@" >> "$ENV_FILE" || return 1
  chmod 600 "$ENV_FILE"
}

# backup_env TAG — an owner-only copy of .env; prints its path.
backup_env() {
  local copy
  copy="${BACKUP_DIR}/env.pre-$1-$(date -u '+%Y%m%d-%H%M%S')"
  mkdir -p "$BACKUP_DIR" || return 1
  (umask 077 && cp "$ENV_FILE" "$copy") && chmod 600 "$copy" || return 1
  printf '%s\n' "$copy"
}

# ensure_dns01_bridge_secret — step 1. Runs after the target's Compose file is
# installed, before the panel is recreated.
ensure_dns01_bridge_secret() {
  local secret backup
  [ -f "$ENV_FILE" ] && dns01_mode && compose_has_bridge || return 0
  [ -n "$(env_value DNS01_BRIDGE_SECRET)" ] && return 0
  secret="$(od -An -tx1 -N 32 /dev/urandom | tr -d ' \n')"
  if ! [[ "$secret" =~ ^[0-9a-f]{64}$ ]]; then
    log "WARNING: could not generate a DNS-01 bridge secret; Traefik keeps its own Cloudflare token for DNS-01"
    return 0
  fi
  if ! backup="$(backup_env dns01-secret)"; then
    log "WARNING: could not back up .env before adding the DNS-01 bridge secret; Traefik keeps its own Cloudflare token for DNS-01"
    return 0
  fi
  # An empty assignment counts as missing, as it does for the panel.
  sed -i -E '/^DNS01_BRIDGE_SECRET=[[:space:]]*$/d' "$ENV_FILE" || return 0
  if ! env_append "# AI-2392: the panel's DNS-01 bridge secret (added by the updater)." "DNS01_BRIDGE_SECRET=${secret}"; then
    log "WARNING: could not add the DNS-01 bridge secret to .env; putting back ${backup}"
    cp -p "$backup" "$ENV_FILE" || true
    return 0
  fi
  log "added a generated DNS01_BRIDGE_SECRET to .env for the panel's DNS-01 bridge (previous kept at ${backup})"
}

# dns01_check_once — POST /check from inside Traefik. 0 on a 200 that says ok.
dns01_check_once() {
  local resp
  resp="$(timeout 30 docker exec "$TRAEFIK_CONTAINER" sh -c "$DNS01_CHECK_SCRIPT" 2>/dev/null)" || return 1
  [[ "$(head -1 <<<"$resp")" =~ ^HTTP/1\.[01]\ 200 ]] || return 1
  grep -q '"ok":true' <<<"$resp" || return 1
  DNS01_CHECK_SOURCE="$(grep -o '"source":"[a-z]*"' <<<"$resp" | head -1 | cut -d'"' -f4)"
  return 0
}

# dns01_check — the check, retried: a recreated Traefik can have a new address
# that the panel learns within 30 seconds (it caches Traefik's addresses).
dns01_check() {
  local elapsed=0
  while :; do
    dns01_check_once && return 0
    [ "$elapsed" -lt "$DNS01_CHECK_TIMEOUT" ] || return 1
    sleep "$DNS01_CHECK_INTERVAL"
    elapsed=$((elapsed + DNS01_CHECK_INTERVAL))
  done
}

# Read into a variable first: under pipefail, grep -q closing the pipe early
# could fail the pipeline.
traefik_uses_bridge() {
  local args
  args="$(docker inspect -f '{{json .Args}}' "$TRAEFIK_CONTAINER" 2>/dev/null)" || return 1
  grep -qF 'dnschallenge.provider=httpreq' <<<"$args"
}

# migrate_dns01_bridge — step 2. Runs after the update is healthy.
migrate_dns01_bridge() {
  local backup retire=0
  [ -f "$ENV_FILE" ] && dns01_mode && compose_has_bridge || return 0
  # Any value is a choice already made (the installer's, or the operator's).
  [ -n "$(env_value DNS01_PROVIDER)" ] && return 0
  if [ -z "$(env_value DNS01_BRIDGE_SECRET)" ]; then
    log "WARNING: .env has no DNS01_BRIDGE_SECRET; DNS-01 certificates stay on Traefik's own Cloudflare token"
    return 0
  fi
  # Traefik must hold the secret to ask the bridge. Its DNS-01 provider is
  # still Cloudflare here, so recreating it changes nothing for certificates.
  if ! run_logged docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps traefik; then
    log "WARNING: could not recreate Traefik with the DNS-01 bridge secret; DNS-01 certificates stay on Traefik's own Cloudflare token"
    return 0
  fi
  if ! dns01_check; then
    log "DNS-01 certificates stay on Traefik's own Cloudflare token: the panel's DNS-01 bridge did not answer its check (it needs a DNS token, in Settings → Connectivity → DNS & Domains or as CF_DNS_API_TOKEN, that reaches the panel domain's zone). The next update or \"Apply again\" tries again."
    return 0
  fi
  [ "$DNS01_CHECK_SOURCE" = "settings" ] && grep -qF 'TRAEFIK_CF_DNS_API_TOKEN' "$COMPOSE_FILE" && retire=1
  if ! backup="$(backup_env dns01-bridge)"; then
    log "WARNING: could not back up .env before switching DNS-01 to the bridge; Traefik keeps its own Cloudflare token"
    return 0
  fi
  local lines=("# AI-2392: Traefik answers DNS-01 challenges through the panel's bridge (switched by the updater; previous .env at ${backup})." "DNS01_PROVIDER=httpreq")
  sed -i -E '/^DNS01_PROVIDER=[[:space:]]*$/d' "$ENV_FILE"
  if [ "$retire" = "1" ]; then
    sed -i -E '/^TRAEFIK_CF_DNS_API_TOKEN=/d' "$ENV_FILE"
    lines+=("# The bridge uses the token saved in Settings, so Traefik no longer gets CF_DNS_API_TOKEN." "TRAEFIK_CF_DNS_API_TOKEN=")
  fi
  if env_append "${lines[@]}" \
      && run_logged docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps traefik panel \
      && wait_health && traefik_uses_bridge && dns01_check; then
    if [ "$retire" = "1" ]; then
      log "DNS-01 certificates now go through the panel's bridge with the token saved in Settings; Traefik no longer holds a Cloudflare token (previous .env kept at ${backup})"
    else
      log "DNS-01 certificates now go through the panel's bridge (previous .env kept at ${backup}); Traefik keeps CF_DNS_API_TOKEN until a token is saved in Settings → DNS"
    fi
    return 0
  fi
  log "WARNING: the DNS-01 bridge did not pass its check after the switch; putting back ${backup} so Traefik uses its own Cloudflare token again"
  if cp -p "$backup" "$ENV_FILE" && chmod 600 "$ENV_FILE" \
      && run_logged docker compose "${COMPOSE_ARGS[@]}" up -d --no-deps traefik panel \
      && wait_health && ! traefik_uses_bridge; then
    log "DNS-01 is back on Traefik's own Cloudflare token"
  else
    log "WARNING: could not confirm that Traefik is back on its own Cloudflare token for DNS-01; check ${ENV_FILE} against ${backup} and run: docker compose up -d traefik panel"
  fi
  return 0
}

# ── Orchestration ─────────────────────────────────────────────────────────────
main() {
  local arg rc
  for arg in "$@"; do
    case "$arg" in
      --reapply) REAPPLY=1 ;;
      # Run by stage 1 only, as its child, under its lock (AI-1471).
      --stage2)  STAGE2=1 ;;
      # Stage 1's start probe: answers, touches nothing.
      --capabilities) [ "$#" = "1" ] && { echo "aap-update stage2 1"; exit 0; } ;&
      *)         echo "usage: aap-update.sh [--reapply]" >&2; exit 2 ;;
    esac
  done
  acquire_lock
  STARTED_AT="$(now)"
  write_updater_marker
  recover_interrupted_run || return 1

  # AI-2746: the panel asked for the on-demand engine and no update waits. An
  # update request goes first; the path unit fires again for the engine.
  if [ "$REAPPLY" != "1" ] && [ "$STAGE2" != "1" ] && [ ! -e "$REQUEST_FILE" ] \
      && { [ -e "$OLLAMA_REQUEST_FILE" ] || [ -L "$OLLAMA_REQUEST_FILE" ]; }; then
    ENGINE_RUN=1
    compose_args_init
    start_ollama_engine
    return
  fi

  if [ "$REAPPLY" = "1" ]; then
    # The installed version is the target. It was accepted on its channel when
    # it was installed, so the channel rule is not applied a second time; the
    # tag must still exist on the registry and carry our signature.
    # A PANEL_VERSION that names a release is the target. A floating one
    # (the installer's default is "latest") names no release, so the target is
    # the release the running panel image was built as.
    #
    # A PANEL_VERSION that names a release must be the release that runs
    # (merge review M6). An image swapped by hand under a pinned .env would
    # otherwise get the other release's Compose file and be recreated from
    # it. When the running image carries no release version there is nothing
    # to compare with, and PANEL_VERSION stands.
    local running_now
    TARGET_TAG="$(read_env_version)"
    running_now="$(running_release)"
    if is_release_version "$TARGET_TAG"; then
      if [ -n "$running_now" ] && [ "${TARGET_TAG#v}" != "$running_now" ]; then
        PREV_VERSION="$TARGET_TAG"
        finish_failed "PANEL_VERSION is ${TARGET_TAG} but the running panel is ${running_now}; set PANEL_VERSION in ${ENV_FILE} to the release that is running, or update the panel, then run --reapply again; nothing was changed"
        return 1
      fi
    else
      TARGET_TAG="$running_now"
    fi
    CURRENT="$TARGET_TAG"
    CHANNEL="reapply"
    ASSET_TAG="v${TARGET_TAG#v}"
    if [ -z "$TARGET_TAG" ]; then
      PREV_VERSION="$(read_env_version)"
      finish_failed "could not work out which release is running: PANEL_VERSION is '${PREV_VERSION:-unset}' and the ${PANEL_CONTAINER} image carries no release version; nothing was changed"
      return 1
    fi
    # AI-2172: Compose uses PANEL_VERSION as the image tag, and GHCR has no
    # v-prefixed tag. An .env that names the release as v2.7.0 gets 2.7.0.
    if [ "$(read_env_version_raw)" != "$(read_env_version)" ]; then
      set_env_version "$(read_env_version)"
      log "PANEL_VERSION in ${ENV_FILE} is now the image tag $(read_env_version)"
    fi
  elif ! read_request; then finish_failed "$FAIL_REASON"; return 1; fi
  PREV_VERSION="$(read_env_version)"
  [ -n "$PREV_VERSION" ] || PREV_VERSION="$CURRENT"
  log "request: ${PREV_VERSION:-unknown} → ${TARGET_TAG} (channel ${CHANNEL})"

  compose_args_init

  if ! validate_target; then finish_failed "$FAIL_REASON"; return 1; fi

  # AI-1185. A release newer than LAST_RELEASE_WITHOUT_MANIFEST is applied only
  # from its signed manifest: the manifest and every file this run will install
  # are downloaded and checked first, into the work area, before the backup and
  # before anything on the box changes. An older release has no manifest and
  # never gets one, so nothing but its signed image is applied.
  if needs_manifest "$TARGET_TAG"; then MANIFEST_RELEASE=1; fi
  if [ "$MANIFEST_RELEASE" != "1" ] && target_is_installed; then
    # Applying the host configuration again IS the request, and for this
    # release none of it is signed. Pulling the image that already runs and
    # calling that a success would mislead.
    finish_failed "release ${TARGET_TAG} has no release manifest, so its host configuration cannot be applied again; update to a newer release"
    return 1
  fi
  if [ "$MANIFEST_RELEASE" = "1" ]; then
    if ! prepare_stage; then finish_failed "could not create the updater's work area ${WORK_DIR}"; return 1; fi
    if ! fetch_manifest; then finish_failed "$FAIL_REASON"; return 1; fi
    # AI-1471: a release that brings its own updater is applied by it.
    refresh_updater; rc=$?
    case "$rc" in
      0) ;;
      3) return "$HANDOFF_RC" ;;
      *) finish_failed "$FAIL_REASON"; return 1 ;;
    esac
    if ! stage_release;  then finish_failed "$FAIL_REASON"; return 1; fi
    if ! stage_theme_refresh; then finish_failed "$FAIL_REASON"; return 1; fi
    # AI-2653: a release that moves Postgres to a new major is checked now,
    # while nothing on the box has changed yet.
    if ! plan_postgres_upgrade; then finish_failed "$FAIL_REASON"; return 1; fi
  else
    log "release ${TARGET_TAG} was published before release manifests (up to ${LAST_RELEASE_WITHOUT_MANIFEST}); applying the image only"
  fi

  if ! backup_db;       then finish_failed "database backup failed — refusing to update"; return 1; fi
  if ! verify_image;    then finish_failed "image signature verification failed for ${TARGET_TAG}"; return 1; fi
  # AI-2657: a release that moves Valkey to a newer major keeps the old data
  # first, so a rollback can start the old Valkey again. Nothing changed yet.
  if ! snapshot_valkey_before_major; then finish_failed "$FAIL_REASON"; return 1; fi

  # Fail-closed, like the cosign and pg_dump gates above: if the box cannot be
  # brought to the target's compose, refuse and leave it on the one that works
  # rather than recreating it into a broken sidecar. Runs after verification so
  # an unsigned image never causes a single change to the box's configuration.
  if ! install_release; then finish_failed "$FAIL_REASON"; return 1; fi
  if ! install_theme_refresh; then finish_failed "$FAIL_REASON"; return 1; fi
  if ! migrate_platform_hostnames; then finish_failed "$FAIL_REASON"; return 1; fi
  ensure_dns01_bridge_secret
  if ! reconcile_ollama_mem_limit; then finish_failed "$FAIL_REASON"; return 1; fi
  if ! reconcile_ollama_profile; then finish_failed "$FAIL_REASON"; return 1; fi

  # After the compose swap, before anything starts from it: the new Compose
  # file's Postgres must find its data upgraded (AI-2653).
  if ! upgrade_postgres_major; then
    rollback "the PostgreSQL upgrade from ${PG_UPGRADE_FROM} to ${PG_UPGRADE_TO} failed; the previous version runs again on its own data"
    return 1
  fi

  if ! apply_target; then
    rollback "pulling or recreating the new image failed"
    return 1
  fi
  if ! wait_health; then
    rollback "the new version did not become healthy in time"
    return 1
  fi
  # The appended lines stay on a rollback: an older image ignores the file, and
  # this image accepts what it reported ready.
  if ! close_ready_purposes; then
    rollback "the panel did not become healthy after closing the old secret format"
    return 1
  fi

  # AI-2392: after the update is healthy, and never a reason to roll it back.
  migrate_dns01_bridge

  # Verify the pin instead of assuming it (AI-832 final re-review N2). The panel
  # refuses to attach a platform container that forwards packets, so a run that
  # leaves one behind has not done what --reapply is for, and an update that
  # leaves one behind must say so where the operator reads the result.
  local unpinned note=""
  unpinned="$(unpinned_platforms)"
  if [ -n "$unpinned" ]; then
    note="still running with packet forwarding on: ${unpinned}; the Compose file on this host does not switch it off, so the panel will not attach them to customer networks (see the upgrade notes, Proxy and gateway containers)"
    if [ "$REAPPLY" = "1" ]; then
      finish_failed "$note"
      return 1
    fi
    log "WARNING: ${note}"
  fi
  # The forwarding note names something the operator has to act on, so it wins
  # over the plain statement that an old release brought its image only.
  if [ -z "$note" ] && [ "$MANIFEST_RELEASE" != "1" ]; then
    note="release ${TARGET_TAG} has no release manifest: only the panel image was updated"
  fi
  if [ -n "$PG_UPGRADE_TO" ]; then
    local pg_note="PostgreSQL was upgraded from ${PG_UPGRADE_FROM} to ${PG_UPGRADE_TO}; the ${PG_UPGRADE_FROM} data is kept in volume ${PG_UPGRADE_VOLUME} until you remove it (see the upgrade notes, PostgreSQL 18)"
    log "$pg_note"
    [ -n "$note" ] || note="$pg_note"
    rm -f "$PG_UPGRADE_STATE"
  fi

  if [ "$REAPPLY" = "1" ]; then
    log "host configuration of ${TARGET_TAG} applied again"
  else
    log "update to ${TARGET_TAG} succeeded"
  fi
  finish_ok "$note"
  return 0
}

# Run when executed; a test may source the file for its functions (AI-2653).
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
  main "$@"
fi
AAP_UPDATE_SCRIPT_EOF
}
_aap_updater_path_unit() {
  cat <<'AAP_UPDATER_PATH_EOF'
[Unit]
Description=AI Admin Panel — watch for one-click update requests
Documentation=https://docs.aiadminpanel.com/operations/updates

[Path]
# The panel container writes this file (target tag it chose itself) when an
# operator clicks "Update now". Its appearance fires aap-updater.service. The
# service removes the file when done, which re-arms this watcher for next time.
PathExists=/opt/aiadminpanel/update/request.json
# The run first moves the request into its root-only work area (AI-2443) and
# removes that copy when done. A copy still there means a run died before its
# cleanup (power loss, reboot); this fires the service at boot so it reports
# that run as interrupted instead of leaving the panel at "in-progress".
PathExists=/opt/aiadminpanel/.update-work/request.json
# AI-2746: the panel asks for the on-demand local AI engine (Ollama) with this
# file. The run removes it and writes update/ollama-result.json.
PathExists=/opt/aiadminpanel/update/ollama-request.json
Unit=aap-updater.service

[Install]
WantedBy=multi-user.target
AAP_UPDATER_PATH_EOF
}
_aap_updater_service_unit() {
  cat <<'AAP_UPDATER_SERVICE_EOF'
[Unit]
Description=AI Admin Panel — apply a one-click update (oneshot)
Documentation=https://docs.aiadminpanel.com/operations/updates
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
Environment=PANEL_DIR=/opt/aiadminpanel
# Runs as root: the only actor that swaps the panel. No container needs
# docker.sock for an update (the panel and Traefik mount it for deploying
# services and for routing, which is separate). The script is self-locking,
# takes a DB backup, verifies the release's signed manifest, its files and its
# image fail-closed, swaps the panel, and auto-rolls-back on failure.
ExecStart=/opt/aiadminpanel/aap-update.sh
# A failed/rolled-back apply still wrote result.json for the UI; surfacing the
# non-zero exit in `systemctl status` is intentional and harmless (the .path
# unit re-arms on the next request, not on this unit's state).
AAP_UPDATER_SERVICE_EOF
}
_aap_egress_guard_script() {
  cat <<'AAP_EGRESS_GUARD_SCRIPT_EOF'
#!/usr/bin/env bash
# aap-egress-guard.sh — keep containers off the cloud metadata addresses and
# tenant containers off the host's own ports (AI-1104). Runs as root on the
# host, from the installer and from aap-egress-guard.timer.
#
# WHY. On most clouds a server asks a fixed link-local address (169.254.169.254)
# for start-up data and sometimes for cloud credentials. A customer's app, or a
# RUN line in a customer's Dockerfile, could ask it too. Which Docker network a
# container sits on cannot stop that: "never send to this address" is a job for
# the host's packet filter, so this script owns a small rule set there.
#
# RULE 1, forwarded traffic. Chain AAP-EGRESS-GUARD, jumped from DOCKER-USER
# (the chain Docker leaves to the administrator and consults before its own).
# For each blocked destination: DNS (port 53) returns, everything else drops.
# No interface is named, so it covers every bridge, every default build step
# and the platform's own containers. Port 53 stays open because Google, AWS and
# Azure put their DNS resolver on such an address.
#
# RULE 1 ALSO COVERS 100.64.0.0/10 (AI-2287), the shared address space of RFC
# 6598 that Tailscale, Headscale and NetBird give their nodes. Once an operator
# puts this host on such a private network, the host has a route there, and a
# container's packet to a node is forwarded and leaves as the host: plugging
# the server into the office VPN would plug in every customer container too.
# Nothing public lives in this range. Unlike the metadata addresses, port 53
# is not opened for the whole range (a node's DNS server is one of the
# operator's devices). Two things return before the drop:
#   - replies to connections opened FROM the range (an admin on the tailnet
#     using a published port, a provider's load balancer that sends from it):
#     conntrack RELATED,ESTABLISHED. A container cannot open one itself: its
#     first packet is new and dropped;
#   - DNS (port 53) to the host's own resolvers inside the range, read from
#     /etc/resolv.conf and /run/systemd/resolve/resolv.conf on every run
#     (Tailscale's 100.100.100.100 when the host accepts its DNS, Alibaba
#     Cloud's 100.100.2.136). Docker's resolver asks them from inside the
#     container, so without this every container would lose DNS. A resolver
#     added later is picked up by the next timer run.
# Its IPv6 range (Tailscale and Headscale: fd7a:115c:a1e0::/48) needs no rule:
# containers have no IPv6 (see IPV6 below). A NetBird network moved to a
# custom range, or a ZeroTier network (operator-chosen, often private ranges),
# is not covered. When one of the panel's own Docker networks (the networks
# the IPv6 check watches) has addresses in the range, because the operator set
# Docker's address pools there, the range rule would cut traffic inside that
# network: it is left out, and the status says failed and names the network.
#
# RULE 1 ALSO HOLDS THE ANTI-SPOOF RULE OF PRIVATE ACCESS (AI-2194), at its
# top, but only when aap-private-access.sh has put this host on a tailnet and
# saved the tailnet interface (INTERFACE= in /etc/aiadminpanel/private-access.conf,
# root-owned and outside the panel's shared update/ directory, so the panel
# container cannot change which interface is trusted). The panel's private
# hostname trusts a 100.64.0.0/10 source address. Docker-published ports go
# through FORWARD, not INPUT, so the host's own input rules (Tailscale's
# included) never see those packets, and a forged or provider-internal
# 100.64.x source arriving on the public interface would pass. So, for
# Traefik's published ports 80 and 443 (--ctorigdstport is the port before
# Docker's DNAT, so a tenant app's own ports are untouched), a new connection
# from the range that did not arrive on that interface is dropped. A saved
# file whose INTERFACE is not a plain interface name fails closed: the range
# is dropped to 80/443 from every interface and the status says failed.
# A provider whose load balancer sends from the range on the public interface
# is cut off from the panel while private access is on (runbook: private-access).
#
# RULE 2, traffic to the host itself. Chain AAP-HOST-GUARD, jumped from INPUT.
# For packets arriving from Docker's default bridge (docker0, where default
# build steps run), from tenant bridges (interfaces named aapbr…, which the
# panel gives every new tenant network) and from older tenant bridges (br-<id>
# of networks named aap_… that carry the label aiadminpanel.managed=true): let
# replies, TCP 80 and 443 and port 53 return to INPUT, drop the rest. Nothing
# is accepted here, so the host's own firewall still decides what returns. SSH
# from the internet arrives on the network card and is never matched.
#
# NOT COVERED by rule 2: the two shared platform networks, aiadminpanel_ai_bus
# and aiadminpanel_traefik_public. The platform's gateway, proxy and model
# server live there, and a model server on the host is a supported setup;
# cutting their path to host ports unattended could break the operator's AI.
#
# A MODEL SERVER ON THE HOST that customer apps call directly (a Provider AI
# address on the host, for example) is on a port rule 2 drops. The operator
# lists such TCP ports in the install's .env, AAP_EGRESS_GUARD_TENANT_HOST_PORTS
# (space or comma separated, at most 16); they return before the drop on every
# guarded interface. An invalid list is ignored and the status says failed.
#
# THE PLATFORM'S OWN TRAFFIC TO THE HOST. The gateway and the proxy are also
# attached to tenant bridges. The panel attaches them with gateway priority -1,
# so their default route, and with it what they send to the host (a model
# server on the host), stays on their own network, which rule 2 leaves out. An
# endpoint attached before that has priority 0 and may route through a tenant
# bridge; `apply` re-attaches each such endpoint of a container with the
# platform's exact name (<prefix>traefik, litellm, ollama) with priority -1,
# keeping its aliases, and says so. No source address is ever exempted: tenant
# containers keep NET_RAW and could forge one. Gateway priority needs Docker 28;
# on an older daemon rule 2 is not applied and the status says unsupported
# (rule 1 still is), because applying it would cut the platform's host traffic
# and any exemption would be forgeable.
#
# THE JUMPS GO FIRST. An appended jump can be present and dead: Docker before
# release 28 ends DOCKER-USER with "-j RETURN", and ufw or firewalld accept
# port 22 in INPUT first. So both jumps are inserted at position 1, and every
# apply (each timer run) checks that each is still rule 1 and puts it back if
# not. `status` says active only when that holds.
#
# Commands:
#   plan    print the rules it would apply; changes nothing
#   apply   create or repair the rules, then write the status file
#   status  print "active", or the reason it is not; changes nothing
#   remove  delete the jumps and the chains (rollback)
#
# IPV6 (AI-2141). Both rules are IPv4 rules. Containers stay off IPv6 because
# the networks they use have IPv6 off: the panel creates every tenant network
# with EnableIPv6=false and refuses to reuse one that has it on. Each run checks
# the networks a container of the panel can sit on (the panel's aap_ networks,
# the shared platform networks and docker0's "bridge") and, when one has IPv6
# on, still applies both rules but reports failed and names the network: there
# is no ip6tables copy of the rules, so such a network is unguarded.
#
# The status file (update/egress-guard.json, read by the panel) holds
# {"status": "active" | "unsupported" | "failed", "checked_at": …, "reason": …,
#  "docker_version": …, "host_rule": "active" | "inactive" | "unknown",
#  "ipv6_networks": [names],
#  "private_access_rule": "active" | "closed" | "off"}.
# "unsupported" means no iptables variant shows a DOCKER-USER chain, or Docker
# is older than 28 (then host_rule is "inactive").
#
# Exit codes: 0 active / done, 1 failed or not active, 2 usage or a refused
# override, 3 unsupported.
#
# Overrides, for tests and the isolation oracle only. Each is checked before any
# firewall call; a value that does not match is refused with exit 2.
#   AAP_EGRESS_GUARD_BLOCKED      blocked destinations, space separated: IPv4
#                                 addresses or ranges inside 169.254.0.0/16 or
#                                 100.64.0.0/10, or 168.63.129.16, or
#                                 100.100.100.200 (a metadata address)
#   AAP_EGRESS_GUARD_RESOLV_FILES resolver files, space separated absolute
#                                 paths (a missing file is skipped)
#   AAP_EGRESS_GUARD_CHAIN        rule 1 chain name (AAP-…, at most 28 chars)
#   AAP_EGRESS_GUARD_HOST_CHAIN   rule 2 chain name (AAP-…, at most 28 chars)
#   AAP_EGRESS_GUARD_HOST_IFACES  rule 2 interfaces, space separated (a name
#                                 or a name ending in +); Docker is then not
#                                 asked and no platform endpoint is exempted
#   AAP_EGRESS_GUARD_STATUS_FILE  absolute path of the status file
#   AAP_EGRESS_GUARD_WORK_DIR     absolute path of the root-only folder the
#                                 status file is built in (default: the
#                                 status folder's parent/.egress-guard-work)
#   AAP_EGRESS_GUARD_LOCK         absolute path of the lock file
#   AAP_EGRESS_GUARD_ENV_FILE     absolute path of the install's .env, read only
#                                 for AAP_PLATFORM_CONTAINER_PREFIX and
#                                 AAP_EGRESS_GUARD_TENANT_HOST_PORTS
#   AAP_EGRESS_GUARD_PRIVATE_ACCESS_CONF
#                                 absolute path of aap-private-access.sh's saved
#                                 settings, read only for INTERFACE

set -u

DEFAULT_BLOCKED="169.254.0.0/16 168.63.129.16 100.100.100.200 100.64.0.0/10"
# The private-network range (AI-2287): no general DNS exception, see RULE 1.
PRIVATE_RANGE="100.64.0.0/10"
RESOLV_FILES="${AAP_EGRESS_GUARD_RESOLV_FILES-/etc/resolv.conf /run/systemd/resolve/resolv.conf}"
# The host's resolvers inside PRIVATE_RANGE, as a.b.c.d/32.
PRIVATE_RESOLVERS=()
STATUS_FILE="${AAP_EGRESS_GUARD_STATUS_FILE:-/opt/aiadminpanel/update/egress-guard.json}"
# Root-only, beside update/ (default /opt/aiadminpanel/.egress-guard-work), so
# on the same filesystem: the status file is built here, never in update/.
WORK_DIR="${AAP_EGRESS_GUARD_WORK_DIR:-$(dirname "$(dirname "$STATUS_FILE")")/.egress-guard-work}"
LOCK_FILE="${AAP_EGRESS_GUARD_LOCK:-/run/aap-egress-guard.lock}"
EGRESS_CHAIN="${AAP_EGRESS_GUARD_CHAIN:-AAP-EGRESS-GUARD}"
HOST_CHAIN="${AAP_EGRESS_GUARD_HOST_CHAIN:-AAP-HOST-GUARD}"
ENV_FILE="${AAP_EGRESS_GUARD_ENV_FILE:-/opt/aiadminpanel/.env}"
PRIVATE_ACCESS_CONF="${AAP_EGRESS_GUARD_PRIVATE_ACCESS_CONF:-/etc/aiadminpanel/private-access.conf}"
# Traefik's published ports (docker-compose.yml), guarded by the anti-spoof rule.
TRAEFIK_PORTS="80 443"
# Set by read_private_access: the anti-spoof rule is wanted, and the tailnet
# interface it trusts (empty: trust none, fail closed).
SPOOF_RULE=false
TAILNET_IFACE=""
# The shared platform networks rule 2 leaves out (internal/docker/labels.go).
SHARED_NETWORKS="aiadminpanel_ai_bus aiadminpanel_traefik_public"
IPT=""
REASON=""
BLOCKED=()
HOST_IFACES=()
HOST_NARROWED=false
PLATFORM_PREFIX="aiadminpanel_"
EXTRA_PORTS=()
CONFIG_PROBLEM=""
# Filled by discover_docker.
declare -A NET_IFACE=()
LEGACY_IFACES=()
# Platform endpoints to re-attach: "container|network|alias alias".
REATTACH=()
REATTACH_PROBLEM=""
DOCKER_TOO_OLD=""
DOCKER_VERSION=""
# Watched networks with IPv6 on (AI-2141).
IPV6_NETWORKS=()
# Watched networks with addresses in PRIVATE_RANGE (AI-2287).
PRIVATE_NETWORKS=()
# Set once rule 2 is checked in place.
HOST_RULE_OK=false

usage() {
  echo "usage: $0 plan|apply|status|remove" >&2
  exit 2
}

refuse() {
  echo "aap-egress-guard: refused: $1" >&2
  exit 2
}

# ── configuration ────────────────────────────────────────────────────────────

# An IPv4 address or range, printed with its prefix length ("/32" added).
normalize_ipv4() {
  local value="$1" addr prefix octet
  [[ "$value" =~ ^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})(/([0-9]{1,2}))?$ ]] || return 1
  addr="${BASH_REMATCH[1]}"
  prefix="${BASH_REMATCH[3]:-32}"
  [ "$prefix" -le 32 ] || return 1
  for octet in ${addr//./ }; do
    [ "$((10#$octet))" -le 255 ] || return 1
  done
  echo "${addr}/${prefix}"
}

# a.b.c.d → a 32-bit number.
ipv4_int() {
  local a b c d
  IFS=. read -r a b c d <<<"$1"
  echo $(((10#$a << 24) | (10#$b << 16) | (10#$c << 8) | 10#$d))
}

# 0 when address/prefix $1 lies inside range/prefix $2 (both normalized).
ipv4_within() {
  local inner="${1%/*}" inner_len="${1#*/}" outer="${2%/*}" outer_len="${2#*/}" mask
  [ "$inner_len" -ge "$outer_len" ] || return 1
  mask=$(((0xFFFFFFFF << (32 - outer_len)) & 0xFFFFFFFF))
  [ $(($(ipv4_int "$inner") & mask)) -eq $(($(ipv4_int "$outer") & mask)) ]
}

# 0 when one of the subnets in $1 (space separated; IPv6 ones are skipped)
# overlaps PRIVATE_RANGE.
overlaps_private_range() {
  local subnet normalized
  for subnet in $1; do
    normalized="$(normalize_ipv4 "$subnet")" || continue
    if ipv4_within "$normalized" "$PRIVATE_RANGE" || ipv4_within "$PRIVATE_RANGE" "$normalized"; then
      return 0
    fi
  done
  return 1
}

# A blocked entry that gets the private-range rules instead of the metadata
# ones: inside 100.64.0.0/10 and not Alibaba's metadata address.
is_private_target() {
  [ "$1" != "100.100.100.200/32" ] && ipv4_within "$1" "$PRIVATE_RANGE"
}

# Only the addresses rule 1 exists for may be blocked: an override narrows the
# rule set, it cannot turn it into a general firewall.
blockable() {
  case "$1" in
    168.63.129.16/32 | 100.100.100.200/32) return 0 ;;
    169.254.*) [ "${1#*/}" -ge 16 ] ;;
    *) ipv4_within "$1" "$PRIVATE_RANGE" ;;
  esac
}

# The host's resolvers inside PRIVATE_RANGE ("nameserver a.b.c.d" lines; a
# range, an IPv6 address or anything else is not one), each listed once.
read_private_resolvers() {
  local file key value rest normalized seen=" "
  for file in $RESOLV_FILES; do
    [ -r "$file" ] || continue
    while read -r key value rest; do
      [ "$key" = nameserver ] || continue
      [[ "$value" =~ ^[0-9.]+$ ]] || continue
      normalized="$(normalize_ipv4 "$value")" || continue
      ipv4_within "$normalized" "$PRIVATE_RANGE" || continue
      case "$seen" in *" ${normalized} "*) continue ;; esac
      seen="${seen}${normalized} "
      PRIVATE_RESOLVERS+=("$normalized")
    done <"$file"
  done
}

# An interface name, or a name ending in "+" (iptables' prefix match).
valid_iface() { [[ "$1" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,14}\+?$ ]]; }

read_config() {
  local list entry normalized
  if [ -n "${AAP_EGRESS_GUARD_BLOCKED+set}" ]; then
    list="$AAP_EGRESS_GUARD_BLOCKED"
    [ -n "$list" ] || refuse "AAP_EGRESS_GUARD_BLOCKED is empty"
  else
    list="$DEFAULT_BLOCKED"
  fi
  for entry in $list; do
    normalized="$(normalize_ipv4 "$entry")" || refuse "not an IPv4 address or range: ${entry}"
    blockable "$normalized" || refuse "not a link-local, metadata or private-network (100.64.0.0/10) address: ${entry}"
    BLOCKED+=("$normalized")
  done
  [[ "$EGRESS_CHAIN" =~ ^AAP-[A-Z0-9-]{1,24}$ ]] || refuse "chain name must be AAP- and up to 24 of A-Z 0-9 -"
  [[ "$HOST_CHAIN" =~ ^AAP-[A-Z0-9-]{1,24}$ ]] || refuse "host chain name must be AAP- and up to 24 of A-Z 0-9 -"
  [ "$HOST_CHAIN" != "$EGRESS_CHAIN" ] || refuse "the two chains need different names"
  if [ -n "${AAP_EGRESS_GUARD_HOST_IFACES+set}" ]; then
    [ -n "$AAP_EGRESS_GUARD_HOST_IFACES" ] || refuse "AAP_EGRESS_GUARD_HOST_IFACES is empty"
    for entry in $AAP_EGRESS_GUARD_HOST_IFACES; do
      valid_iface "$entry" || refuse "not an interface name: ${entry}"
      HOST_IFACES+=("$entry")
    done
    HOST_NARROWED=true
  fi
  case "$STATUS_FILE" in /*) ;; *) refuse "status file must be an absolute path" ;; esac
  case "$WORK_DIR" in /*) ;; *) refuse "work folder must be an absolute path" ;; esac
  case "$LOCK_FILE" in /*) ;; *) refuse "lock file must be an absolute path" ;; esac
  case "$ENV_FILE" in /*) ;; *) refuse "env file must be an absolute path" ;; esac
  case "$PRIVATE_ACCESS_CONF" in /*) ;; *) refuse "private-access settings must be an absolute path" ;; esac
  for entry in $RESOLV_FILES; do
    case "$entry" in /*) ;; *) refuse "resolver files must be absolute paths" ;; esac
  done
  read_private_resolvers
  read_platform_prefix
  read_extra_ports
  read_private_access
}

# A configuration problem is reported; several are joined.
add_config_problem() {
  CONFIG_PROBLEM="${CONFIG_PROBLEM:+${CONFIG_PROBLEM}; }$1"
}

# aap-private-access.sh's saved settings: when present, the anti-spoof rule is
# wanted. Only INTERFACE is read, never sourced; the last line wins.
read_private_access() {
  local value
  [ -e "$PRIVATE_ACCESS_CONF" ] || return 0
  SPOOF_RULE=true
  if [ ! -r "$PRIVATE_ACCESS_CONF" ]; then
    add_config_problem "${PRIVATE_ACCESS_CONF} cannot be read; the anti-spoof rule trusts no interface"
    return 0
  fi
  value="$(grep '^INTERFACE=' "$PRIVATE_ACCESS_CONF" | tail -1 | cut -d= -f2-)"
  value="${value%\"}"
  value="${value#\"}"
  # A plain name: a prefix pattern (name+) would trust a whole family.
  if valid_iface "$value" && [[ "$value" != *+ ]]; then
    TAILNET_IFACE="$value"
  else
    add_config_problem "INTERFACE in ${PRIVATE_ACCESS_CONF} is not an interface name; 100.64.0.0/10 is dropped to ports 80 and 443 from every interface"
  fi
}

# One setting from the install's .env, quotes stripped; empty when absent.
env_value() {
  local value
  [ -r "$ENV_FILE" ] || return 0
  # The last line wins, as in Docker Compose's own reading of .env.
  value="$(grep "^$1=" "$ENV_FILE" | tail -1 | cut -d= -f2-)"
  value="${value%\"}"
  value="${value#\"}"
  printf '%s' "$value"
}

# The operator's extra host ports for tenant bridges. Only plain port numbers;
# anything else voids the whole list (fail closed) and is reported.
read_extra_ports() {
  local value port ports=()
  value="$(env_value AAP_EGRESS_GUARD_TENANT_HOST_PORTS)"
  [ -n "$value" ] || return 0
  for port in ${value//,/ }; do
    if [[ "$port" =~ ^[0-9]{1,5}$ ]] && [ "$((10#$port))" -ge 1 ] && [ "$((10#$port))" -le 65535 ]; then
      ports+=("$((10#$port))")
    else
      add_config_problem "AAP_EGRESS_GUARD_TENANT_HOST_PORTS in ${ENV_FILE} is not a list of port numbers; ignored"
      return 0
    fi
  done
  if [ "${#ports[@]}" -gt 16 ]; then
    add_config_problem "AAP_EGRESS_GUARD_TENANT_HOST_PORTS in ${ENV_FILE} lists more than 16 ports; ignored"
    return 0
  fi
  EXTRA_PORTS=("${ports[@]}")
}

# The panel's platform container prefix (AAP_PLATFORM_CONTAINER_PREFIX in the
# install's .env; internal/docker/platform.go). The file is read, never sourced.
read_platform_prefix() {
  local value
  value="$(env_value AAP_PLATFORM_CONTAINER_PREFIX)"
  [ -n "$value" ] || return 0
  if [[ "$value" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,62}$ ]]; then
    PLATFORM_PREFIX="$value"
  else
    echo "aap-egress-guard: ignoring an invalid AAP_PLATFORM_CONTAINER_PREFIX in ${ENV_FILE}" >&2
  fi
}

# ── what Docker has ──────────────────────────────────────────────────────────

# Fills NET_IFACE (tenant network → bridge interface), LEGACY_IFACES (tenant
# interfaces that aapbr+ does not match) and REATTACH, or DOCKER_TOO_OLD.
# Fails when Docker cannot be asked; a network that vanishes between the two
# calls is skipped.
discover_docker() {
  local names name line id bridge managed iface version
  version="$(docker version --format '{{.Server.Version}}' 2>/dev/null)" || return 1
  DOCKER_VERSION="$version"
  if [[ ! "$version" =~ ^([0-9]+)\. ]] || [ "${BASH_REMATCH[1]}" -lt 28 ]; then
    DOCKER_TOO_OLD="$version"
  fi
  names="$(docker network ls --format '{{.Name}}' 2>/dev/null)" || return 1
  local ipv6 shared subnets
  while IFS= read -r name; do
    [[ "$name" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ ]] || continue
    shared=false
    case " bridge ${SHARED_NETWORKS} " in *" ${name} "*) shared=true ;; esac
    case "$name" in aap_*) ;; *) [ "$shared" = true ] || continue ;; esac
    line="$(docker network inspect --format '{{.Name}}|{{.Id}}|{{index .Options "com.docker.network.bridge.name"}}|{{index .Labels "aiadminpanel.managed"}}|{{.EnableIPv6}}|{{range .IPAM.Config}}{{.Subnet}} {{end}}' "$name" 2>/dev/null)" || continue
    IFS='|' read -r _ id bridge managed ipv6 subnets <<<"$line"
    if [ "$shared" = true ]; then
      [ "$ipv6" != "true" ] || IPV6_NETWORKS+=("$name")
      ! overlaps_private_range "$subnets" || PRIVATE_NETWORKS+=("$name")
      continue
    fi
    # Only the panel's own networks: the prefix alone could be an operator's.
    [ "$managed" = "true" ] || continue
    [ "$ipv6" != "true" ] || IPV6_NETWORKS+=("$name")
    ! overlaps_private_range "$subnets" || PRIVATE_NETWORKS+=("$name")
    [ "$bridge" != "<no value>" ] || bridge=""
    if [ -n "$bridge" ]; then
      iface="$bridge"
    else
      [[ "$id" =~ ^[0-9a-f]{12} ]] || continue
      iface="br-${id:0:12}"
    fi
    valid_iface "$iface" || continue
    NET_IFACE["$name"]="$iface"
    case "$iface" in aapbr*) ;; *) LEGACY_IFACES+=("$iface") ;; esac
  done <<<"$names"
  [ -n "$DOCKER_TOO_OLD" ] || discover_legacy_platform_endpoints
}

# For each platform container (the exact names <prefix>traefik, litellm and
# ollama), each endpoint on a tenant bridge whose gateway priority is not
# negative goes into REATTACH. An alias that is not a plain name voids that
# endpoint and is reported: it is never passed to Docker.
discover_legacy_platform_endpoints() {
  local suffix container line entry net prio aliases alias
  local endpoints=()
  # A Docker template, not a shell expansion.
  # shellcheck disable=SC2016
  local template='{{.Name}}|{{range $n, $e := .NetworkSettings.Networks}}{{$n}},{{$e.GwPriority}},{{range $e.Aliases}}{{.}} {{end}};{{end}}'
  for suffix in traefik litellm ollama; do
    container="${PLATFORM_PREFIX}${suffix}"
    line="$(docker inspect --format "$template" "$container" 2>/dev/null)" || continue
    [ "${line%%|*}" = "/${container}" ] || continue
    IFS=';' read -r -a endpoints <<<"${line#*|}"
    for entry in "${endpoints[@]}"; do
      IFS=',' read -r net prio aliases <<<"$entry"
      [ -n "${NET_IFACE[$net]+set}" ] || continue
      [[ "$prio" =~ ^-?[0-9]+$ ]] || continue
      [ "$prio" -ge 0 ] || continue
      for alias in $aliases; do
        if [[ ! "$alias" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$ ]]; then
          REATTACH_PROBLEM="${container} on ${net} has an alias that is not a plain name; not re-attached"
          continue 2
        fi
      done
      REATTACH+=("${container}|${net}|${aliases% }")
    done
  done
}

# Re-attach each REATTACH endpoint with gateway priority -1 and its aliases.
# The container is off that network for the moment between the two calls.
reattach_platform_endpoints() {
  local item container net aliases alias args
  for item in "${REATTACH[@]}"; do
    IFS='|' read -r container net aliases <<<"$item"
    args=(--gw-priority -1)
    for alias in $aliases; do
      args+=(--alias "$alias")
    done
    if docker network disconnect "$net" "$container" >/dev/null 2>&1 \
      && docker network connect "${args[@]}" "$net" "$container" >/dev/null 2>&1; then
      echo "re-attached ${container} to ${net} with gateway priority -1 (it was attached by an older panel)"
    else
      REATTACH_PROBLEM="could not re-attach ${container} to ${net} with gateway priority -1; the panel's reconcile attaches it again"
      echo "aap-egress-guard: ${REATTACH_PROBLEM}" >&2
    fi
  done
}

# ── the rule set ─────────────────────────────────────────────────────────────

# Rules in the form `iptables -S` prints them, so a healthy chain compares equal.
egress_rules() {
  local target resolver port
  # The anti-spoof rule (AI-2194). Left out, like the range rule, when a panel
  # network lives in the range: its containers' own traffic to the published
  # ports would be cut.
  if [ "$SPOOF_RULE" = true ] && [ "${#PRIVATE_NETWORKS[@]}" -eq 0 ]; then
    for port in $TRAEFIK_PORTS; do
      if [ -n "$TAILNET_IFACE" ]; then
        echo "-s ${PRIVATE_RANGE} ! -i ${TAILNET_IFACE} -p tcp -m conntrack --ctstate NEW --ctorigdstport ${port} -j DROP"
      else
        echo "-s ${PRIVATE_RANGE} -p tcp -m conntrack --ctstate NEW --ctorigdstport ${port} -j DROP"
      fi
    done
  fi
  for target in "${BLOCKED[@]}"; do
    if is_private_target "$target"; then
      # A panel network lives in the range: cutting it would break the panel.
      [ "${#PRIVATE_NETWORKS[@]}" -eq 0 ] || continue
      echo "-d ${target} -m conntrack --ctstate RELATED,ESTABLISHED -j RETURN"
      for resolver in "${PRIVATE_RESOLVERS[@]}"; do
        ipv4_within "$resolver" "$target" || continue
        echo "-d ${resolver} -p udp -m udp --dport 53 -j RETURN"
        echo "-d ${resolver} -p tcp -m tcp --dport 53 -j RETURN"
      done
      echo "-d ${target} -j DROP"
      continue
    fi
    echo "-d ${target} -p udp -m udp --dport 53 -j RETURN"
    echo "-d ${target} -p tcp -m tcp --dport 53 -j RETURN"
    echo "-d ${target} -j DROP"
  done
}

# The rules rule 2 holds for one interface.
host_rules_for() {
  local port
  echo "-i $1 -m conntrack --ctstate RELATED,ESTABLISHED -j RETURN"
  echo "-i $1 -p tcp -m tcp --dport 80 -j RETURN"
  echo "-i $1 -p tcp -m tcp --dport 443 -j RETURN"
  for port in "${EXTRA_PORTS[@]}"; do
    echo "-i $1 -p tcp -m tcp --dport ${port} -j RETURN"
  done
  echo "-i $1 -p udp -m udp --dport 53 -j RETURN"
  echo "-i $1 -p tcp -m tcp --dport 53 -j RETURN"
  echo "-i $1 -j DROP"
}

# One line naming the tenant host-port allow-list, so an operator sees what
# customer apps may reach on this host and how to change it.
allow_list_line() {
  local head="tenant host-port allow-list (AAP_EGRESS_GUARD_TENANT_HOST_PORTS in ${ENV_FILE})"
  if [ "${#EXTRA_PORTS[@]}" -gt 0 ]; then
    echo "${head}: TCP ${EXTRA_PORTS[*]}"
  else
    echo "${head}: empty: customer apps cannot reach a model server on this host; to allow one (Ollama on 11434, for example) add AAP_EGRESS_GUARD_TENANT_HOST_PORTS=\"11434\" there and run this script with apply"
  fi
}

# Rule 2 from HOST_IFACES, or from what discover_docker found.
host_rules() {
  local iface
  local ifaces=("${HOST_IFACES[@]}")
  if [ "$HOST_NARROWED" = false ]; then
    ifaces=(docker0 'aapbr+')
    while IFS= read -r iface; do
      [ -n "$iface" ] && ifaces+=("$iface")
    done < <(printf '%s\n' "${LEGACY_IFACES[@]}" | sort -u)
  fi
  for iface in "${ifaces[@]}"; do
    host_rules_for "$iface"
  done
}

# ── iptables ─────────────────────────────────────────────────────────────────

# The variant under which Docker's DOCKER-USER chain is visible: Docker may
# write through the nft or the legacy backend, whatever `iptables` points at.
pick_iptables() {
  local candidate
  for candidate in iptables iptables-nft iptables-legacy; do
    command -v "$candidate" >/dev/null 2>&1 || continue
    if "$candidate" -w -S DOCKER-USER >/dev/null 2>&1; then
      IPT="$candidate"
      return 0
    fi
  done
  return 1
}

ipt() { "$IPT" -w "$@"; }

# The rules of CHAIN without the "-A CHAIN " prefix; fails if CHAIN is missing.
chain_rules() {
  local listing
  listing="$(ipt -S "$1" 2>/dev/null)" || return 1
  printf '%s\n' "$listing" | sed -n "s/^-A $1 //p"
}

# Make CHAIN hold exactly the rules in $2 (one per line). Rewritten only when it
# differs, so a timer run on a healthy host changes nothing.
sync_chain() {
  local chain="$1" desired="$2" current rule words
  if ! ipt -S "$chain" >/dev/null 2>&1; then
    ipt -N "$chain" || return 1
  fi
  current="$(chain_rules "$chain")" || return 1
  [ "$current" = "$desired" ] && return 0
  ipt -F "$chain" || return 1
  while IFS= read -r rule; do
    [ -n "$rule" ] || continue
    read -r -a words <<<"$rule"
    ipt -A "$chain" "${words[@]}" || return 1
  done <<<"$desired"
}

# Rule numbers of the jumps from PARENT to CHAIN, highest first.
jump_positions() {
  ipt -S "$1" 2>/dev/null | grep '^-A ' | grep -nx -- "-A $1 -j $2" | cut -d: -f1 | sort -rn
}

jump_is_first() {
  [ "$(ipt -S "$1" 2>/dev/null | grep -m1 '^-A ')" = "-A $1 -j $2" ]
}

# Exactly one jump from PARENT to CHAIN, and it is rule 1. Inserted, never
# appended; any later copy is removed after the new one is in place, so the
# chain is never without its jump.
ensure_jump_first() {
  local parent="$1" chain="$2" position
  if ! jump_is_first "$parent" "$chain"; then
    ipt -I "$parent" 1 -j "$chain" || return 1
  fi
  for position in $(jump_positions "$parent" "$chain"); do
    [ "$position" -gt 1 ] || continue
    ipt -D "$parent" "$position" || return 1
  done
}

remove_jumps() {
  local parent="$1" chain="$2" position
  for position in $(jump_positions "$parent" "$chain"); do
    ipt -D "$parent" "$position" || return 1
  done
}

# 0 when the rule set is in place; otherwise REASON says what is not. Rule 2
# is compared with what Docker has now (discover_docker ran before).
check_active() {
  local current
  if ! current="$(chain_rules "$EGRESS_CHAIN")"; then
    REASON="chain ${EGRESS_CHAIN} is missing"
    return 1
  fi
  if [ "$current" != "$(egress_rules)" ]; then
    REASON="chain ${EGRESS_CHAIN} does not hold the planned rules"
    return 1
  fi
  if ! jump_is_first DOCKER-USER "$EGRESS_CHAIN"; then
    REASON="the jump to ${EGRESS_CHAIN} is not first in DOCKER-USER"
    return 1
  fi
  if ! current="$(chain_rules "$HOST_CHAIN")"; then
    REASON="chain ${HOST_CHAIN} is missing"
    return 1
  fi
  if [ "$current" != "$(host_rules)" ]; then
    REASON="chain ${HOST_CHAIN} does not hold the planned rules"
    return 1
  fi
  if ! jump_is_first INPUT "$HOST_CHAIN"; then
    REASON="the jump to ${HOST_CHAIN} is not first in INPUT"
    return 1
  fi
  return 0
}

# Docker is asked unless rule 2 is narrowed; DOCKER_OK says whether it answered.
DOCKER_OK=true
ask_docker() {
  [ "$HOST_NARROWED" = false ] || return 0
  discover_docker || DOCKER_OK=false
}

# ── status file and lock ─────────────────────────────────────────────────────

# publish_status <tmp> — rename the finished file over STATUS_FILE. GNU mv -T
# replaces a planted link, also one to a folder, by rename(2). BusyBox mv (the
# Alpine image the installer tests run in) refuses a link to a folder instead;
# then the link itself is unlinked (rm never follows it) and the rename is
# tried once more. Nothing is ever written through the link.
publish_status() {
  mv -fT -- "$1" "$STATUS_FILE" 2>/dev/null && return 0
  [ -L "$STATUS_FILE" ] && rm -f -- "$STATUS_FILE" && mv -fT -- "$1" "$STATUS_FILE"
}

# prepare_work_dir — the root-only work area beside update/. Refused when it is
# a link, not ours, or on another filesystem than update/ (mv would then copy
# into update/ by path instead of renaming).
prepare_work_dir() {
  (umask 077 && mkdir -p -- "$WORK_DIR") || return 1
  [ -d "$WORK_DIR" ] && [ ! -L "$WORK_DIR" ] || return 1
  [ "$(stat -c %u -- "$WORK_DIR")" = "$(id -u)" ] || return 1
  chmod 700 -- "$WORK_DIR" || return 1
  [ "$(stat -c %d -- "$WORK_DIR")" = "$(stat -c %d -- "$(dirname "$STATUS_FILE")")" ]
}

# The update directory is shared with the panel container (AI-2443), so nothing
# is created or written there by path: the file is built in the root-only work
# area and renamed over the target with mv -T, which replaces a planted link
# (to a file or a folder) instead of following it.
write_status() {
  local status="$1" reason="$2" dir tmp host_rule=unknown version names="" n spoof=off
  if [ "$SPOOF_RULE" = true ]; then
    spoof=closed
    [ -z "$TAILNET_IFACE" ] || spoof=active
  fi
  if [ -n "$DOCKER_TOO_OLD" ]; then
    host_rule=inactive
  elif [ "$HOST_RULE_OK" = true ]; then
    host_rule=active
  fi
  version="$(printf '%s' "$DOCKER_VERSION" | tr -cd 'A-Za-z0-9.+-')"
  # Names were checked against ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ in discover_docker.
  for n in "${IPV6_NETWORKS[@]}"; do
    names="${names:+${names},}\"${n}\""
  done
  dir="$(dirname "$STATUS_FILE")"
  if [ ! -d "$dir" ]; then
    echo "aap-egress-guard: ${dir} does not exist; status file not written" >&2
    return 0
  fi
  reason="$(printf '%s' "$reason" | tr -cd 'A-Za-z0-9 ._:/,()-')"
  if ! prepare_work_dir; then
    # An old "active" must not stay visible: rm unlinks a planted link, it
    # never follows it, and the panel then shows the guard as unknown.
    rm -f -- "$STATUS_FILE" 2>/dev/null || true
    echo "aap-egress-guard: no safe work folder at ${WORK_DIR}; status file removed, not written" >&2
    return 1
  fi
  tmp="$(umask 077 && mktemp "${WORK_DIR}/status.XXXXXX")" || return 1
  if printf '{"status":"%s","checked_at":"%s","reason":"%s","docker_version":"%s","host_rule":"%s","ipv6_networks":[%s],"private_access_rule":"%s"}\n' \
      "$status" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$reason" "$version" "$host_rule" "$names" "$spoof" >"$tmp" \
      && chmod 644 "$tmp" && publish_status "$tmp"; then
    return 0
  fi
  rm -f -- "$tmp"
  return 1
}

# One run edits the firewall at a time: rule numbers read by one run must not
# shift under it. Waits up to 30 seconds (flock -n in a loop: BusyBox flock has
# no -w). A host without flock runs unlocked.
take_lock() {
  local tries=30
  command -v flock >/dev/null 2>&1 || return 0
  exec 9>"$LOCK_FILE" || return 1
  until flock -n 9; do
    tries=$((tries - 1))
    [ "$tries" -gt 0 ] || return 1
    sleep 1
  done
}

fail() {
  echo "aap-egress-guard: failed: $1" >&2
  write_status failed "$1"
  exit 1
}

# ── commands ─────────────────────────────────────────────────────────────────

too_old_reason() {
  echo "rule 2 is not applied: Docker ${DOCKER_TOO_OLD} is older than Docker 28, which the platform's gateway priority needs; rule 1 is applied. Tenant containers still reach the host's ports until Docker is upgraded"
}

private_networks_reason() {
  local word="network ${PRIVATE_NETWORKS[*]} uses"
  [ "${#PRIVATE_NETWORKS[@]}" -eq 1 ] || word="networks ${PRIVATE_NETWORKS[*]} use"
  echo "Docker ${word} addresses in ${PRIVATE_RANGE}, so the rule that keeps containers off Tailscale, Headscale and NetBird networks is left out (it would cut that traffic). Move Docker's address pools out of ${PRIVATE_RANGE} (default-address-pools in /etc/docker/daemon.json) and recreate the network"
}

ipv6_reason() {
  local s="" word=network
  [ "${#IPV6_NETWORKS[@]}" -eq 1 ] || { s=s; word=networks; }
  echo "IPv6 is enabled on Docker ${word} ${IPV6_NETWORKS[*]}. The guard covers IPv4 only, so containers there reach IPv6 addresses unfiltered. Turn IPv6 off: remove ipv6 and enable_ipv6 from /etc/docker/daemon.json, then recreate the network${s} without IPv6 (an app network: redeploy the app after docker network rm)"
}

# Before Docker 28: take rule 2 away if an earlier run left it, so the
# firewall matches the status.
drop_host_rule() {
  remove_jumps INPUT "$HOST_CHAIN" || return 1
  if ipt -S "$HOST_CHAIN" >/dev/null 2>&1; then
    ipt -F "$HOST_CHAIN" && ipt -X "$HOST_CHAIN"
  fi
}

cmd_plan() {
  local rule
  ask_docker
  if [ "${#PRIVATE_NETWORKS[@]}" -gt 0 ]; then
    echo "# $(private_networks_reason)"
  fi
  echo "# rule 1: no container may send to these addresses; DNS (port 53) stays open to the metadata addresses"
  echo "# and, inside ${PRIVATE_RANGE} (Tailscale, Headscale, NetBird), only to this host's own resolvers; replies to connections from there return"
  if [ "$SPOOF_RULE" = true ]; then
    echo "# private access (${PRIVATE_ACCESS_CONF}): new connections from ${PRIVATE_RANGE} to ports ${TRAEFIK_PORTS// /, } must arrive on ${TAILNET_IFACE:-no interface (invalid INTERFACE: fail closed)}"
  fi
  echo "-N ${EGRESS_CHAIN}"
  while IFS= read -r rule; do
    echo "-A ${EGRESS_CHAIN} ${rule}"
  done <<<"$(egress_rules)"
  echo "-I DOCKER-USER 1 -j ${EGRESS_CHAIN}"
  echo "# rule 2: from docker0 and tenant bridges only replies, TCP 80/443 and port 53 reach the host"
  echo "# $(allow_list_line)"
  if [ -n "$CONFIG_PROBLEM" ]; then
    echo "# ${CONFIG_PROBLEM}"
  fi
  if [ "$DOCKER_OK" = false ]; then
    echo "# Docker could not be asked: older tenant bridges and platform endpoints are missing below"
  fi
  if [ -n "$DOCKER_TOO_OLD" ]; then
    echo "# $(too_old_reason)"
    echo "# not covered: ${SHARED_NETWORKS}: containers on these shared networks still reach the host's ports"
    return 0
  fi
  local item container net
  for item in "${REATTACH[@]}"; do
    IFS='|' read -r container net _ <<<"$item"
    echo "# re-attach ${container} to ${net} with gateway priority -1 (attached by an older panel; its default route could leave through that bridge)"
  done
  if [ -n "$REATTACH_PROBLEM" ]; then
    echo "# ${REATTACH_PROBLEM}"
  fi
  echo "-N ${HOST_CHAIN}"
  while IFS= read -r rule; do
    echo "-A ${HOST_CHAIN} ${rule}"
  done <<<"$(host_rules)"
  echo "-I INPUT 1 -j ${HOST_CHAIN}"
  echo "# not covered: ${SHARED_NETWORKS}: containers on these shared networks still reach the host's ports"
}

cmd_apply() {
  take_lock || {
    echo "aap-egress-guard: another run holds ${LOCK_FILE}; the firewall was not touched" >&2
    exit 1
  }
  if ! pick_iptables; then
    write_status unsupported "no DOCKER-USER chain under iptables, iptables-nft or iptables-legacy"
    echo "unsupported: no DOCKER-USER chain under iptables, iptables-nft or iptables-legacy" >&2
    exit 3
  fi
  # Docker is asked first: rule 1 depends on the panel networks' addresses.
  ask_docker
  sync_chain "$EGRESS_CHAIN" "$(egress_rules)" || fail "could not write chain ${EGRESS_CHAIN}"
  ensure_jump_first DOCKER-USER "$EGRESS_CHAIN" || fail "could not put the jump to ${EGRESS_CHAIN} first in DOCKER-USER"
  if [ "$DOCKER_OK" = true ] && [ -n "$DOCKER_TOO_OLD" ]; then
    drop_host_rule || fail "could not remove chain ${HOST_CHAIN}"
    [ "${#IPV6_NETWORKS[@]}" -eq 0 ] || fail "$(ipv6_reason)"
    [ "${#PRIVATE_NETWORKS[@]}" -eq 0 ] || fail "$(private_networks_reason)"
    write_status unsupported "$(too_old_reason)"
    echo "unsupported: $(too_old_reason)" >&2
    exit 3
  fi
  if [ "$DOCKER_OK" = true ]; then
    reattach_platform_endpoints
    sync_chain "$HOST_CHAIN" "$(host_rules)" || fail "could not write chain ${HOST_CHAIN}"
  elif ! ipt -S "$HOST_CHAIN" >/dev/null 2>&1; then
    fail "could not list Docker networks; rule 2 was not created"
  fi
  # Without Docker's answer rule 2 stays as the last run left it, still first.
  ensure_jump_first INPUT "$HOST_CHAIN" || fail "could not put the jump to ${HOST_CHAIN} first in INPUT"
  [ "$DOCKER_OK" = true ] || fail "could not list Docker networks; rule 2 was left as it was"
  check_active || fail "$REASON"
  HOST_RULE_OK=true
  [ -z "$CONFIG_PROBLEM" ] || fail "$CONFIG_PROBLEM"
  [ -z "$REATTACH_PROBLEM" ] || fail "$REATTACH_PROBLEM"
  [ "${#IPV6_NETWORKS[@]}" -eq 0 ] || fail "$(ipv6_reason)"
  [ "${#PRIVATE_NETWORKS[@]}" -eq 0 ] || fail "$(private_networks_reason)"
  write_status active ""
  echo "active"
}

cmd_status() {
  if ! pick_iptables; then
    echo "unsupported: no DOCKER-USER chain under iptables, iptables-nft or iptables-legacy"
    exit 3
  fi
  ask_docker
  if [ "$DOCKER_OK" = false ]; then
    echo "not active: could not list Docker networks"
    exit 1
  fi
  if [ "${#IPV6_NETWORKS[@]}" -gt 0 ]; then
    echo "not active: $(ipv6_reason)"
    exit 1
  fi
  if [ "${#PRIVATE_NETWORKS[@]}" -gt 0 ]; then
    echo "not active: $(private_networks_reason)"
    exit 1
  fi
  if [ -n "$DOCKER_TOO_OLD" ]; then
    echo "unsupported: $(too_old_reason)"
    exit 3
  fi
  if check_active && [ -z "$CONFIG_PROBLEM" ] && [ "${#REATTACH[@]}" -eq 0 ]; then
    echo "active"
    return 0
  fi
  [ -n "$REASON" ] || REASON="${CONFIG_PROBLEM:-platform endpoints attached by an older panel still need re-attaching (run apply)}"
  echo "not active: ${REASON}"
  exit 1
}

cmd_remove() {
  take_lock || {
    echo "aap-egress-guard: another run holds ${LOCK_FILE}; the firewall was not touched" >&2
    exit 1
  }
  if ! pick_iptables; then
    echo "nothing to remove: no DOCKER-USER chain"
    return 0
  fi
  remove_jumps DOCKER-USER "$EGRESS_CHAIN" || fail "could not delete the jump to ${EGRESS_CHAIN}"
  remove_jumps INPUT "$HOST_CHAIN" || fail "could not delete the jump to ${HOST_CHAIN}"
  local chain
  for chain in "$EGRESS_CHAIN" "$HOST_CHAIN"; do
    ipt -S "$chain" >/dev/null 2>&1 || continue
    if ! ipt -F "$chain" || ! ipt -X "$chain"; then
      fail "could not delete chain ${chain}"
    fi
  done
  write_status failed "removed by aap-egress-guard.sh remove"
  echo "removed"
}

[ $# -eq 1 ] || usage
case "$1" in
  plan | apply | status | remove) ;;
  *) usage ;;
esac
read_config
"cmd_$1"
AAP_EGRESS_GUARD_SCRIPT_EOF
}
_aap_egress_guard_service_unit() {
  cat <<'AAP_EGRESS_GUARD_SERVICE_EOF'
[Unit]
Description=AI Admin Panel — container egress guard: apply the host firewall rules (oneshot)
Documentation=https://docs.aiadminpanel.com/getting-started/upgrade
# The rules hang off Docker's DOCKER-USER chain, which exists once Docker runs.
After=docker.service
Wants=docker.service

[Service]
Type=oneshot
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Runs as root: it edits the host firewall (AI-1104). It keeps containers off
# the cloud metadata addresses and tenant containers off the host's own ports,
# re-inserts its jumps first when something moved them, and writes
# update/egress-guard.json for the panel. A non-zero exit (failed, or no
# DOCKER-USER chain) shows in `systemctl status`; the timer still re-runs it.
ExecStart=/opt/aiadminpanel/aap-egress-guard.sh apply

[Install]
# Also when Docker (re)starts, so the guard follows Docker up at boot instead
# of waiting for the timer.
WantedBy=docker.service
AAP_EGRESS_GUARD_SERVICE_EOF
}
_aap_egress_guard_timer_unit() {
  cat <<'AAP_EGRESS_GUARD_TIMER_EOF'
[Unit]
Description=AI Admin Panel — re-apply the container egress guard every 5 minutes
Documentation=https://docs.aiadminpanel.com/getting-started/upgrade

[Timer]
# A reboot empties the packet filter and a firewall reload may; this puts the
# rules back. OnCalendar rather than OnUnitActiveSec: a wall-clock schedule
# does not depend on how the last run ended (a failed oneshot never becomes
# active), the lesson of ci-runner-prune.timer.
OnBootSec=30s
OnCalendar=*:0/5
Persistent=true
AccuracySec=30s

[Install]
WantedBy=timers.target
AAP_EGRESS_GUARD_TIMER_EOF
}

# AI-2747: the Vultr first-boot hook, written by --bake on the vultr-marketplace channel.
_aap_embed_vultr_first_boot() {
  cat <<'AAP_EMBED_VULTR_FIRST_BOOT_EOF'
#!/bin/bash
# AI Admin Panel: Vultr first-boot hook for snapshot builds (AI-2747).
#
# A Vultr Marketplace server made from our snapshot already holds the machine
# setup and every container image (install.sh --bake). cloud-init runs this
# hook once on each new server (/var/lib/cloud/scripts/per-instance/, Vultr's
# snapshot-build model). It reads the deploy form from Vultr's metadata service
# exactly as the Vendor Data script does (docs/vultr-marketplace/build/
# vendor-data.sh), shows the same bare-IP status page, and runs the per-server
# half of the install: install.sh --first-boot.
#
# Unlike the Vendor Data script it never stops SSH (image pipeline spec PD5):
# the first boot is short, closing SSH is what broke Marketplace servers
# (AI-2735), and the image holds no password or key. A login banner shows the
# progress instead (the installer updates it at every step).
#
# Written by install.sh --bake (AAP_INSTALL_SOURCE=vultr-marketplace), embedded from
# scripts/marketplace/vultr-first-boot.sh. Tested by
# tests/installer/vultr_first_boot.bats; the blocks shared with vendor-data.sh
# (status page, metadata read, value checks) must stay identical to it, and that
# test fails when they drift.
#
# Exit codes (also in /var/log/aap-marketplace.log and the login message):
#   0  ready
#   12 the Vultr metadata service gave no admin_pass (or could not be reached)
#   13 a deploy-form value is invalid (admin password under 32 characters or
#      not plain printable ASCII, malformed domain, admin e-mail that is not
#      one address the owner can receive mail at)
#   other: install.sh --first-boot's code (1 a step failed, 2 not a baked
#      server, 3 another server's secrets; see /var/log/aiadminpanel/install.log)
#
# TEST ONLY: --test-app-vars <file> reads the deploy-form values from <file>
# (lines name=value, root-owned, mode 600) instead of the metadata service,
# which answers 404 for app variables on a server not deployed from the
# Marketplace. cloud-init runs this hook with no arguments, so a Marketplace
# server never takes this path; it exists for the real-server test run only.
set -euo pipefail

# The AAP_FB_* overrides exist for the test only; on Vultr none is set.
LOG="${AAP_FB_LOG:-/var/log/aap-marketplace.log}"
MOTD="${AAP_FB_MOTD:-/etc/motd.d/50-aiadminpanel}"
PANEL_DIR="${AAP_FB_PANEL_DIR:-/opt/aiadminpanel}"
INSTALLER="${AAP_FB_INSTALLER:-/usr/local/lib/aap-marketplace/install.sh}"
BAKE_MARKER="${AAP_FB_MARKER:-/etc/aiadminpanel/baked.json}"
METADATA_URL="http://169.254.169.254/v1/internal"
# One value (AI-2728): the admin password is also the setup code, so it needs
# the setup code's minimum (_setup_token_valid in scripts/lib/secrets.sh, 32),
# above the sign-in policy's 12 (admin_password_ok). Vultr's variable: 40.
MIN_PASSWORD_LENGTH=32

TEST_APP_VARS=""
case "${1:-}" in
  "") ;;
  --test-app-vars)
    TEST_APP_VARS="${2:?--test-app-vars needs a file}" ;;
  *) echo "usage: $0 [--test-app-vars <file>]   (the option is for tests only)" >&2; exit 2 ;;
esac

# The image's version, from the bake marker (the image *is* the version).
AAP_VERSION="v$(sed -n 's/.*"version":"\([^"]*\)".*/\1/p' "$BAKE_MARKER" 2>/dev/null | head -n 1)"
[ "$AAP_VERSION" != v ] || AAP_VERSION="(no bake marker)"

umask 077
mkdir -p "$(dirname "$LOG")"
touch "$LOG"
chmod 600 "$LOG"
exec >>"$LOG" 2>&1
log() { echo "$(date -u +%FT%TZ) $*"; }
log "AI Admin Panel ${AAP_VERSION}: first boot from the snapshot started (SSH stays open)"
[ -z "$TEST_APP_VARS" ] || log "TEST MODE: deploy-form values come from ${TEST_APP_VARS}, not the metadata service"

# The login message (MOTD) is how the customer sees the result over SSH.
# World-readable, so it never holds the admin password (also the setup code).
status() {
  mkdir -p "$(dirname "$MOTD")"
  {
    printf 'AI Admin Panel %s: %s\n' "$AAP_VERSION" "$1"
    [ -z "${2:-}" ] || printf '%s\n' "$2"
    printf 'Install log: %s\n' "$LOG"
  } >"$MOTD"
  chmod 644 "$MOTD"
}

# ── Bare-IP status page (AI-2700, AI-2701) ────────────────────────────────────
# Vultr's App Instructions only know {{ip}}, so a customer without SSH opens
# http://<ip>. This page answers there: "still installing", "ready, your panel
# is at https://<domain>, sign in with <e-mail> and the admin password" or
# "failed, see the log". Since AI-2738 signing in comes first and opens the
# setup wizard. AI-2792: the e-mail is the one the installer gave the admin
# account (the deploy form's admin_email), read back from the panel's .env.
# The e-mail is not a secret; the page never shows the admin password: it
# reads only the status file below (state, domain, exit code, sign-in
# e-mail), which this script writes and which holds nothing else.
#
# How it gets port 80 without taking it: the page listens on 8099, and one nat
# rule sends outside traffic for port 80 there. Nothing listens on port 80, so
# the installer's port check passes and Traefik binds port 80 as usual. Local
# traffic (the installer's own checks) never passes PREROUTING. Requests for
# any other host name (Let's Encrypt's HTTP-01 check for the panel domain) are
# passed on to Traefik unchanged. After a good install the page stays 24 hours,
# then the rule goes and port 80 is Traefik's alone; a reboot ends it too (the
# rule and the unit are not saved). After a failed install it stays up.
# From the first release with Traefik's bare-IP router (AI-2723, the
# panel-bare-ip labels in docker-compose.yml), Traefik then sends http://<ip>
# to https://<panel domain>/ for good; the page says so when the installed
# Compose file has that router, and otherwise that it goes away.
#
# Best effort: if the page cannot start (no systemd-run, no iptables, no
# python3), the install goes on and the log says so.
STATUS_DIR="${AAP_VD_STATUS_DIR:-/run/aap-marketplace}"
STATUS_LIB="${AAP_VD_LIB_DIR:-/usr/local/lib/aap-marketplace}"
STATUS_PORT=8099
STATUS_RULE=(-p tcp --dport 80 -m addrtype --dst-type LOCAL -m comment --comment aap-install-status -j REDIRECT --to-ports "$STATUS_PORT")
STATUS_ACCEPT=(-p tcp --dport "$STATUS_PORT" -m conntrack --ctstate DNAT --ctorigdstport 80 -m comment --comment aap-install-status -j ACCEPT)

# page_state <installing|ready|failed> [domain] [exit code] [redirect] [email]
# [email fallback]: atomic, world-readable. redirect=1: Traefik takes
# http://<ip> over (AI-2723). email: the admin's sign-in e-mail; email
# fallback=1: it is admin@<temporary domain> and the setup wizard asks for the
# owner's own e-mail (AI-2792).
page_state() {
  mkdir -p "$STATUS_DIR"
  chmod 755 "$STATUS_DIR"
  {
    printf 'state=%s\n' "$1"
    [ -z "${2:-}" ] || printf 'domain=%s\n' "$2"
    [ -z "${3:-}" ] || printf 'exit=%s\n' "$3"
    [ -z "${4:-}" ] || printf 'redirect=%s\n' "$4"
    [ -z "${5:-}" ] || printf 'email=%s\n' "$5"
    [ -z "${6:-}" ] || printf 'email_fallback=%s\n' "$6"
  } >"$STATUS_DIR/status.tmp"
  chmod 644 "$STATUS_DIR/status.tmp"
  mv -f "$STATUS_DIR/status.tmp" "$STATUS_DIR/status"
}

write_status_page_files() {
  mkdir -p "$STATUS_LIB"
  chmod 755 "$STATUS_LIB"
  cat >"$STATUS_LIB/status-page.py" <<'PY'
# AI Admin Panel: first-boot status page for Vultr Marketplace servers
# (AI-2700, AI-2701). Written by the Vendor Data script. Shows the state from
# one status file; never reads anything else on disk.
import html, http.client, ipaddress, os, re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

STATUS_FILE = os.environ.get("AAP_STATUS_FILE", "/run/aap-marketplace/status")
BIND = os.environ.get("AAP_STATUS_BIND", "0.0.0.0")
PORT = int(os.environ.get("AAP_STATUS_PORT", "8099"))
UPSTREAM = os.environ.get("AAP_STATUS_UPSTREAM", "")  # tests only; default: Traefik on port 80
LABEL = r"[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?"
DOMAIN_RE = re.compile(r"%s(\.%s)+" % (LABEL, LABEL))
EMAIL_RE = re.compile(r"[a-z0-9._%%+-]{1,64}@%s(\.%s)+" % (LABEL, LABEL))
HOP = {"connection", "keep-alive", "proxy-connection", "proxy-authenticate", "proxy-authorization",
       "te", "trailer", "transfer-encoding", "upgrade"}
HEADERS = {
    "Content-Type": "text/html; charset=utf-8",
    "Cache-Control": "no-store",
    "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
    "X-Content-Type-Options": "nosniff",
    "X-Frame-Options": "DENY",
    "Referrer-Policy": "no-referrer",
}


def read_status():
    st = {}
    try:
        with open(STATUS_FILE, encoding="utf-8") as f:
            for line in f.read(4096).splitlines():
                k, _, v = line.partition("=")
                st[k.strip()] = v.strip()
    except OSError:
        pass
    state = st.get("state")
    if state not in ("installing", "ready", "failed"):
        state = "installing"
    domain = st.get("domain", "")
    if not DOMAIN_RE.fullmatch(domain):
        domain = ""
    code = st.get("exit", "")
    if not code.isdigit():
        code = ""
    redirect = st.get("redirect") == "1"
    email = st.get("email", "")
    fallback = st.get("email_fallback") == "1"
    if not EMAIL_RE.fullmatch(email):
        email, fallback = "", domain.endswith(".aiadminpanel.host")
    return state, domain, code, redirect, email, fallback


def page(state, domain, code, redirect=False, email="", fallback=False):
    if state == "ready" and domain:
        url = html.escape("https://%s/" % domain, quote=True)
        # AI-2792: the address the installer gave the admin account. This page
        # is public (anyone who scans the IP sees it), so the owner's own
        # address is masked to its first letter and domain (GDPR data
        # minimisation; it is also the sign-in name). The owner typed it into
        # the deploy form; the root-only login message shows it whole.
        # admin@<domain> (no address in the deploy form, the setup wizard then
        # asks for the owner's own) is predictable and not personal: shown.
        fallback_email = "admin@%s" % domain
        if email and email != fallback_email:
            local, _, mail_domain = email.partition("@")
            shown = '%s&bull;&bull;&bull;@%s' % (html.escape(local[0], quote=True), html.escape(mail_domain, quote=True))
            which = 'the e-mail you entered in the deploy form; already filled in on the sign-in page'
        else:
            shown = html.escape(fallback_email, quote=True)
            which = 'already filled in on the sign-in page'
        email = shown
        title = "Your AI Admin Panel is ready"
        if redirect:
            # AI-2723: Traefik's bare-IP router takes over when this page ends.
            later = ('Bookmark it. After a day this page ends, but this address keeps taking '
                     'you to your panel.')
        else:
            later = 'Bookmark it: this page goes away within a day.'
        # AI-2738, AI-2792: one way in. Sign in with this e-mail and the
        # admin password; the setup wizard opens next, then the dashboard.
        body = ('<p>Your panel is at <a href="%s">%s</a>. %s</p><p>Open the panel and '
                'sign in; the setup wizard opens next:</p>'
                '<ul><li>E-mail: <code>%s</code> (%s)</li>'
                '<li>Password: the admin password from the Vultr App Instructions</li></ul>'
                % (url, url, later, email, which))
        if fallback:
            body += ('<p>The setup wizard asks for your own e-mail address and makes it '
                     'your sign-in e-mail. After that, sign in with your own address.</p>')
        refresh = ""
    elif state == "ready":
        title = "Your AI Admin Panel is ready"
        body = "<p>The install is done. The panel address is in /var/log/aap-marketplace.log.</p>"
        refresh = ""
    elif state == "failed":
        title = "The AI Admin Panel install failed"
        body = ("<p>The first-boot install stopped (exit %s). Sign in over SSH as root and read "
                "/var/log/aap-marketplace.log.</p>" % (code or "unknown"))
        refresh = ""
    else:
        title = "AI Admin Panel is still installing"
        body = ("<p>The server installs AI Admin Panel on its first start. This takes several "
                "minutes. This page reloads itself and shows the panel address when it is done.</p>")
        refresh = '<meta http-equiv="refresh" content="15">'
    return ("<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">%s"
            "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
            "<title>%s</title><style>body{font-family:system-ui,sans-serif;max-width:36rem;"
            "margin:4rem auto;padding:0 1rem;line-height:1.5}</style></head><body><h1>%s</h1>%s"
            "</body></html>" % (refresh, title, title, body)).encode("utf-8")


def is_ip_host(host):
    host = (host or "").strip()
    if host.startswith("["):
        host = host[1:].split("]", 1)[0]
    elif host.count(":") == 1:
        host = host.split(":", 1)[0]
    if host == "":
        return True
    try:
        ipaddress.ip_address(host)
        return True
    except ValueError:
        return False


class Handler(BaseHTTPRequestHandler):
    server_version = "aap-install-status"
    sys_version = ""
    timeout = 15

    def log_message(self, *args):
        pass

    def do_GET(self):
        self.route(True)

    def do_HEAD(self):
        self.route(False)

    def do_POST(self):
        self.refuse()

    do_PUT = do_DELETE = do_PATCH = do_OPTIONS = do_POST

    def refuse(self):
        self.send_response(405)
        self.send_header("Allow", "GET, HEAD")
        self.send_header("Content-Length", "0")
        self.end_headers()

    def route(self, with_body):
        if is_ip_host(self.headers.get("Host")):
            body = page(*read_status())
            self.send_response(200)
            for k, v in HEADERS.items():
                self.send_header(k, v)
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            if with_body:
                self.wfile.write(body)
            return
        self.forward(with_body)

    def forward(self, with_body):
        # Another host name: pass the request to Traefik on port 80, at the
        # address the client reached (Docker publishes port 80 there).
        if UPSTREAM:
            target, port = UPSTREAM.rsplit(":", 1)
        else:
            target, port = self.connection.getsockname()[0], "80"
        try:
            conn = http.client.HTTPConnection(target, int(port), timeout=10)
            headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP}
            conn.request(self.command, self.path, headers=headers)
            resp = conn.getresponse()
            data = resp.read(1 << 20)
            conn.close()
        except (OSError, http.client.HTTPException):
            self.send_response(502)
            self.send_header("Content-Length", "0")
            self.end_headers()
            return
        self.send_response(resp.status)
        for k, v in resp.getheaders():
            if k.lower() not in HOP and k.lower() != "content-length":
                self.send_header(k, v)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        if with_body:
            self.wfile.write(data)


ThreadingHTTPServer.daemon_threads = True
ThreadingHTTPServer((BIND, PORT), Handler).serve_forever()
PY
  cat >"$STATUS_LIB/status-page-off.sh" <<EOF
#!/bin/bash
# Takes the first-boot status page down (AI-2700). Run 24 hours after a good install.
iptables -t nat -D PREROUTING ${STATUS_RULE[*]} 2>/dev/null
iptables -D INPUT ${STATUS_ACCEPT[*]} 2>/dev/null
systemctl stop aap-install-status.service 2>/dev/null
exit 0
EOF
  chmod 644 "$STATUS_LIB/status-page.py"
  chmod 755 "$STATUS_LIB/status-page-off.sh"
}

# ready_state <domain>: the ready login message and page (AI-2792). The
# sign-in e-mail is the installer's (ADMIN_EMAIL in .env); an installer
# before AI-2792 writes none, and its admin is admin@<domain>.
ready_state() {
  local domain="$1" email fallback="" redirect="" note=""
  email="$(sed -n 's/^ADMIN_EMAIL=//p' "${PANEL_DIR}/.env" 2>/dev/null | tail -n 1)"
  [ -n "$email" ] || email="admin@${domain:-<panel domain>}"
  # Only a temporary domain makes the wizard ask (AI-2702): admin@<domain> has
  # no mailbox there. On the owner's own domain that address stays.
  if [ "$email" = "admin@${domain}" ] && [[ "$domain" == *.aiadminpanel.host ]]; then
    fallback=1
    note="
The setup wizard asks for your own e-mail and makes it your sign-in e-mail."
  fi
  status "ready." "Panel:      https://${domain:-<see install log>}
Sign in with the e-mail and password below; the setup wizard opens next.
E-mail:     ${email}
Password:   the admin password from the Vultr App Instructions${note}"
  if grep -qF 'traefik.http.routers.panel-bare-ip.' "${PANEL_DIR}/docker-compose.yml" 2>/dev/null; then
    redirect=1
  fi
  page_state ready "$domain" "" "$redirect" "$email" "$fallback"
}

start_status_page() {
  page_state installing
  write_status_page_files
  if ! systemd-run --unit=aap-install-status --description="AI Admin Panel first-boot status page" \
    -p DynamicUser=yes -p NoNewPrivileges=yes -p ProtectSystem=strict -p ProtectHome=yes \
    -p PrivateTmp=yes -p Restart=on-failure \
    -E AAP_STATUS_FILE="$STATUS_DIR/status" -E AAP_STATUS_PORT="$STATUS_PORT" \
    /usr/bin/python3 "$STATUS_LIB/status-page.py"; then
    log "status page could not start (systemd-run failed); the install goes on without it"
    return 0
  fi
  if iptables -t nat -I PREROUTING "${STATUS_RULE[@]}" && iptables -I INPUT "${STATUS_ACCEPT[@]}"; then
    log "status page on http://<server IP>/ (port 80 redirected to ${STATUS_PORT} while it runs)"
  else
    log "status page could not start (iptables failed); the install goes on without it"
  fi
}

finish() {
  local rc=$?
  set +e
  if [ "$rc" -eq 0 ]; then
    local domain
    domain="$(sed -n 's/^PANEL_DOMAIN=//p' "${PANEL_DIR}/.env" 2>/dev/null | tail -n 1)"
    ready_state "$domain"
    systemd-run --unit=aap-install-status-off --on-active=24h \
      /bin/bash "$STATUS_LIB/status-page-off.sh" >/dev/null 2>&1 ||
      log "could not schedule the status page's take-down; it ends at the next reboot"
  else
    status "first boot FAILED (exit ${rc})." "See the install log, and /var/log/aiadminpanel/install.log if the installer started.
Run it again: sudo ${INSTALLER} --first-boot (this server's secrets are kept)."
    page_state failed "" "$rc"
  fi
  log "finished with exit ${rc}"
  exit "$rc"
}
trap finish EXIT
trap 'exit 130' INT TERM
status "first boot: preparing (about two minutes; SSH stays open)..."
start_status_page

# ── Deploy-form values from Vultr's metadata service ─────────────────────────
# meta <name>: prints the value of app variable <name>. Returns 0 with the value,
# 3 when the variable is not set (HTTP 404: an optional field left blank), 1 when
# the service fails, so a transient error is never mistaken for "left blank".
meta() {
  local body code
  body="$(mktemp)"
  code="$(curl -sS --max-time 10 --retry 5 --retry-delay 2 --retry-connrefused \
    -H "METADATA-TOKEN: vultr" -o "$body" -w '%{http_code}' \
    "${METADATA_URL}/app-$1")" || code="000"
  case "$code" in
    200) cat "$body"; rm -f "$body"; return 0 ;;
    404) rm -f "$body"; return 3 ;;
    *) rm -f "$body"; log "metadata app-$1: HTTP ${code}"; return 1 ;;
  esac
}

# app_var <name>: meta, or in a test run the value from --test-app-vars (same
# return codes: 3 when the file has no such line).
app_var() {
  [ -n "$TEST_APP_VARS" ] || { meta "$1"; return; }
  local line
  line="$(grep -m1 "^$1=" "$TEST_APP_VARS")" || return 3
  printf '%s' "${line#*=}"
}

if [ -n "$TEST_APP_VARS" ]; then
  if [ ! -f "$TEST_APP_VARS" ] || [ "$(stat -c '%u %a' "$TEST_APP_VARS")" != "$(id -u) 600" ]; then
    log "TEST MODE refused: ${TEST_APP_VARS} must be a file owned by this user with mode 600."
    exit 12
  fi
fi

rc=0
ADMIN_PASSWORD="$(app_var admin_pass)" || rc=$?
if [ "$rc" -ne 0 ] || [ -z "$ADMIN_PASSWORD" ]; then
  log "admin_pass is missing from the Vultr metadata service (rc ${rc}). Is the password variable named admin_pass?"
  exit 12
fi
if [ "${#ADMIN_PASSWORD}" -lt "$MIN_PASSWORD_LENGTH" ]; then
  log "admin_pass has ${#ADMIN_PASSWORD} characters; it is also the setup code, which needs at least ${MIN_PASSWORD_LENGTH}. Set the password variable's length to 40 in the Vultr console."
  exit 13
fi
# Printable ASCII only, no spaces: the setup-code box trims spaces and an HTTP
# header cannot carry other characters. Vultr's generator makes none of them.
# In a subshell, not `bash -c`: an argument would show the password in ps.
if ! (LC_ALL=C; [[ "$ADMIN_PASSWORD" =~ ^[[:graph:]]+$ ]]); then
  log "admin_pass holds a space or a character outside printable ASCII; it cannot be pasted as the setup code."
  exit 13
fi

rc=0
PANEL_DOMAIN="$(app_var panel_domain)" || rc=$?
case "$rc" in
  0 | 3) ;;
  *) log "panel_domain could not be read from the metadata service; not guessing a blank field."; exit 12 ;;
esac
# Forgive what people paste: spaces, a scheme, a trailing slash, capitals.
PANEL_DOMAIN="$(printf '%s' "$PANEL_DOMAIN" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')"
PANEL_DOMAIN="${PANEL_DOMAIN#http://}"
PANEL_DOMAIN="${PANEL_DOMAIN#https://}"
PANEL_DOMAIN="${PANEL_DOMAIN%/}"
label='[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?'
if [ -n "$PANEL_DOMAIN" ] && ! [[ "$PANEL_DOMAIN" =~ ^${label}(\.${label})+$ ]]; then
  log "panel_domain '${PANEL_DOMAIN}' is not a domain name (expected e.g. panel.example.com)."
  exit 13
fi
if [ -n "$PANEL_DOMAIN" ]; then
  log "Domain from the deploy form: ${PANEL_DOMAIN} (its DNS A record must point at this server)"
else
  log "No domain given: the installer claims a free temporary domain (AI-544)"
fi

rc=0
ADMIN_EMAIL="$(app_var admin_email)" || rc=$?
case "$rc" in
  0 | 3) ;;
  *) log "admin_email could not be read from the metadata service; not guessing a blank field."; exit 12 ;;
esac
# AI-2792: the owner e-mail becomes the admin account e-mail and sign-in name.
# Same rule as the installer's admin_email_normalize (scripts/lib/preflight.sh):
# trimmed, lower case, letters, digits and . _ % + - before the @, a domain
# name after it, nothing under aiadminpanel.host (no mailbox there).
ADMIN_EMAIL="$(printf '%s' "$ADMIN_EMAIL" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]')"
if [ -n "$ADMIN_EMAIL" ]; then
  if ! (LC_ALL=C; [[ "${#ADMIN_EMAIL}" -le 254 && "$ADMIN_EMAIL" =~ ^[a-z0-9._%+-]{1,64}@${label}(\.${label})+$ ]]) ||
    [[ "$ADMIN_EMAIL" =~ ^\.|\.@|\.\. ]] || [[ "$ADMIN_EMAIL" =~ [@.]aiadminpanel\.host$ ]]; then
    log "admin_email '${ADMIN_EMAIL}' is not one e-mail address you can receive mail at (expected e.g. you@example.com)."
    exit 13
  fi
  log "Admin sign-in e-mail from the deploy form: ${ADMIN_EMAIL}"
else
  log "No admin_email given: the admin signs in as admin@<panel domain> until the setup wizard asks for the owner's e-mail"
fi

# Setup code = admin password (AI-2728, "one value"), as in vendor-data.sh.
SETUP_TOKEN="$ADMIN_PASSWORD"
log "Setup code: the admin password (one value for the customer)"

# ── The per-server half of the install ───────────────────────────────────────
# The values reach the installer in its environment only: never an argument
# (ps shows those), never a file, never this log. PANEL_VERSION is left unset:
# the installer takes the baked version, the one whose images are on disk.
if [ ! -f "$INSTALLER" ]; then
  log "${INSTALLER} is missing: this server was not made from a baked snapshot."
  exit 2
fi
export ADMIN_PASSWORD PANEL_DOMAIN SETUP_TOKEN ADMIN_EMAIL
# The Marketplace's attribution name: licence events report it as
# install_source (ADR-0008 section 2), so it matches the listing's counts.
export AAP_INSTALL_SOURCE=vultr-marketplace
unset PANEL_VERSION
log "Running install.sh --first-boot (its own log: /var/log/aiadminpanel/install.log)"
rc=0
bash "$INSTALLER" --first-boot </dev/null || rc=$?
exit "$rc"
AAP_EMBED_VULTR_FIRST_BOOT_EOF
}

# The nightly backup payloads, injected by build-installer.sh from the files the
# @AAP_EMBED:<path>@ lines name.
_aap_embed_backup_databases() {
  cat <<'AAP_EMBED_BACKUP_DATABASES_EOF'
#!/usr/bin/env bash
# AI Admin Panel - Nightly backup set: OpenBao vault + the platform databases (AI-925)
#
# One run writes one set, BACKUP_DIR/set-<UTC timestamp>/:
#   openbao-data.tar.gz   cold copy of the vault volume (backup-openbao.sh)
#   aiadminpanel.sql.gz   plain-SQL dump of the panel database
#   keycloak.sql.gz       plain-SQL dump of the Keycloak database
#   litellm.sql.gz        plain-SQL dump of the AI gateway's database (AI-2221):
#                         virtual keys, budgets, spend. Left out, with a log
#                         line, only on a box that has no litellm database.
#   manifest.json         key fingerprint, OpenBao image, every file's SHA-256
#
# The set is written as set-<ts>.partial and renamed only when every step
# worked, so a half-written set is never mistaken for a good one. The unseal
# key is never in the set (see backup-openbao.sh). The dumps are NOT encrypted:
# they hold Keycloak password hashes and secrets, so everything is root-only
# (folders 0700, files 0600). Sets older than 7 days are deleted whole; the
# newest complete set is always kept.
#
# The run holds the updater's lock (aap-update.sh), so an update never runs
# while the vault is stopped for the copy.
#
# Usage:
#   /opt/aiadminpanel/backup-databases.sh
#
# The installer (and `install.sh --refresh-updater`) schedules it with the
# aap-backup.timer systemd unit, daily at 03:00 host time. Do not also run it
# from cron: each run stops the vault for a few seconds.

set -euo pipefail
umask 077

# ── Configuration ──────────────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKUP_DIR="${BACKUP_DIR:-/opt/aiadminpanel/backups}"
LOG_FILE="${LOG_FILE:-/var/log/aiadminpanel/backup.log}"
PG_CONTAINER="${PG_CONTAINER:-aiadminpanel_postgresql}"
PG_USER="${PG_USER:-aiadminpanel}"
AAP_LOCK_FILE="${AAP_LOCK_FILE:-/opt/aiadminpanel/.update-work/lock}"
BACKUP_LOCK_WAIT="${BACKUP_LOCK_WAIT:-1800}"
# A run the timer catches up at boot can start before Postgres and OpenBao are
# up. Wait this long for them before giving up (the vault step waits too).
export BACKUP_READY_WAIT="${BACKUP_READY_WAIT:-300}"
export BACKUP_READY_INTERVAL="${BACKUP_READY_INTERVAL:-5}"
DATABASES=("aiadminpanel" "keycloak")
# Databases dumped when they exist (AI-2221). The installer creates litellm for
# the bundled AI gateway; a box without it is not an error. preflight() decides,
# before the vault is stopped, and adds each one found to DATABASES.
OPTIONAL_DATABASES=("litellm")
RETENTION_DAYS=7
PARTIAL_MAX_MINUTES=1440
MANIFEST_FORMAT=1
TIMESTAMP="$(date -u +%Y%m%dT%H%M%SZ)"
STARTED_AT="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"

# ── Logging ────────────────────────────────────────────────────────────────────
log() {
  local level="$1"
  shift
  local msg="[$(date -u '+%Y-%m-%dT%H:%M:%SZ')] [$level] $*"
  echo "$msg"
  if [ -d "$(dirname "$LOG_FILE")" ]; then
    echo "$msg" >> "$LOG_FILE" 2>/dev/null || true
  fi
}

info()  { log "INFO " "$@"; }
warn()  { log "WARN " "$@"; }
error() { log "ERROR" "$@"; }

# ── Lock shared with the updater ───────────────────────────────────────────────
# Same file and the same checks as aap-update.sh acquire_lock: the folder is
# root's, and a folder that is a link is not ours.
acquire_lock() {
  local lock_dir
  lock_dir="$(dirname "$AAP_LOCK_FILE")"
  if [ -L "$lock_dir" ] || ! mkdir -p "$lock_dir" || ! chmod 700 "$lock_dir"; then
    error "cannot use the lock folder ${lock_dir}"
    return 1
  fi
  exec 9>"$AAP_LOCK_FILE"
  # A retry loop, not `flock -w`: BusyBox flock has no -w.
  local waited=0
  until flock -n 9; do
    if [ "$waited" -ge "$BACKUP_LOCK_WAIT" ]; then
      error "update in progress, backup skipped (lock ${AAP_LOCK_FILE} still taken after ${BACKUP_LOCK_WAIT}s)"
      return 1
    fi
    sleep 1
    waited=$((waited + 1))
  done
}

# ── Pre-flight Checks ─────────────────────────────────────────────────────────
preflight() {
  if [ -L "$BACKUP_DIR" ]; then
    error "backup folder ${BACKUP_DIR} is a link; refusing to write through it"
    return 1
  fi
  mkdir -p "$BACKUP_DIR"
  chmod 700 "$BACKUP_DIR"
  mkdir -p "$(dirname "$LOG_FILE")"

  if ! command -v jq >/dev/null 2>&1; then
    error "jq is not installed; it writes the set's manifest"
    return 1
  fi

  # Check the database before the vault is stopped, so a database problem
  # never costs vault downtime. Wait for it first: at boot it may be starting.
  local start="$SECONDS"
  until docker inspect --format='{{.State.Status}}' "$PG_CONTAINER" 2>/dev/null | grep -q "running" \
      && docker exec "$PG_CONTAINER" psql -U "$PG_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; do
    if [ $((SECONDS - start)) -ge "$BACKUP_READY_WAIT" ]; then
      error "PostgreSQL in container '$PG_CONTAINER' is not running or not accepting connections after ${BACKUP_READY_WAIT}s"
      return 1
    fi
    sleep "$BACKUP_READY_INTERVAL"
  done

  # An optional database is skipped only when Postgres says it does not exist;
  # a question that fails stops the run, so a broken check never drops a dump.
  local db found
  for db in "${OPTIONAL_DATABASES[@]}"; do
    if ! found="$(docker exec "$PG_CONTAINER" psql -U "$PG_USER" -d postgres -At \
        -c "SELECT 1 FROM pg_database WHERE datname = '${db}'" 2>/dev/null)"; then
      error "cannot check whether database '${db}' exists"
      return 1
    fi
    if [ "$found" = "1" ]; then
      DATABASES+=("$db")
    else
      warn "no '${db}' database on this host; it is not in this set"
    fi
  done
}

# ── Dump Database ──────────────────────────────────────────────────────────────
dump_database() {
  local set_dir="$1" db_name="$2"
  local dump_file="${set_dir}/${db_name}.sql"
  local gz_file="${dump_file}.gz"

  info "Dumping database '${db_name}'..."

  if ! docker exec "$PG_CONTAINER" pg_dump -U "$PG_USER" -d "$db_name" > "$dump_file" 2>/dev/null; then
    error "Failed to dump database '${db_name}'"
    rm -f "$dump_file"
    return 1
  fi

  if [ ! -s "$dump_file" ]; then
    error "Dump file for '${db_name}' is empty"
    rm -f "$dump_file"
    return 1
  fi

  if ! head -1 "$dump_file" | grep -q "^--"; then
    warn "Dump file for '${db_name}' may not be valid SQL (missing comment header)"
  fi

  if ! gzip "$dump_file"; then
    error "Failed to compress dump file for '${db_name}'"
    rm -f "$dump_file"
    return 1
  fi

  local size
  size=$(du -h "$gz_file" | cut -f1)
  info "Database '${db_name}' backed up: ${gz_file} (${size})"
}

# ── Manifest ───────────────────────────────────────────────────────────────────
write_manifest() {
  local set_dir="$1" files="[]" f
  local names=(openbao-data.tar.gz) db
  for db in "${DATABASES[@]}"; do names+=("${db}.sql.gz"); done
  for f in "${names[@]}"; do
    files="$(jq -c --arg name "$f" --arg sha "$(sha256sum "${set_dir}/${f}" | cut -d' ' -f1)" \
      --argjson size "$(stat -c '%s' "${set_dir}/${f}")" \
      '. + [{name: $name, sha256: $sha, size: $size}]' <<<"$files")"
  done
  jq -n --argjson format "$MANIFEST_FORMAT" --arg started "$STARTED_AT" \
    --arg finished "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" \
    --slurpfile openbao "${set_dir}/openbao.json" --argjson files "$files" \
    '{format: $format, status: "complete", started_at: $started, finished_at: $finished,
      openbao: $openbao[0], files: $files}' > "${set_dir}/manifest.json.tmp"
  mv "${set_dir}/manifest.json.tmp" "${set_dir}/manifest.json"
  rm -f "${set_dir}/openbao.json"
}

# ── Retention ──────────────────────────────────────────────────────────────────
# Runs only after a complete set was written, so there is always one to keep.
# Old flat *.sql.gz dumps from before AI-925 are left alone; the runbook tells
# the operator what to do with them.
rotate_sets() {
  local newest d fp key_dir current_fp
  newest="$(find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d -name 'set-*' ! -name '*.partial' | sort | tail -1)"

  while IFS= read -r d; do
    [ -n "$d" ] && [ "$d" != "$newest" ] || continue
    rm -rf -- "$d"
    info "Removed old backup set $(basename "$d")"
  done < <(find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d -name 'set-*' ! -name '*.partial' -mtime +"$RETENTION_DAYS")

  while IFS= read -r d; do
    [ -n "$d" ] || continue
    rm -rf -- "$d"
    info "Removed unfinished backup set $(basename "$d")"
  done < <(find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d -name 'set-*.partial' -mmin +"$PARTIAL_MAX_MINUTES")

  # Pre-restore copies (restore-openbao.sh) follow the same rule: older than
  # RETENTION_DAYS go, the newest always stays; an unfinished one goes after a day.
  local newest_pre
  newest_pre="$(find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type f -name 'pre-restore-*.tar.gz' | sort | tail -1)"
  while IFS= read -r d; do
    [ -n "$d" ] && [ "$d" != "$newest_pre" ] || continue
    rm -f -- "$d"
    info "Removed old pre-restore copy $(basename "$d")"
  done < <(find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type f -name 'pre-restore-*.tar.gz' -mtime +"$RETENTION_DAYS")
  while IFS= read -r d; do
    [ -n "$d" ] || continue
    rm -f -- "$d"
    info "Removed unfinished pre-restore copy $(basename "$d")"
  done < <(find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type f -name 'pre-restore-*.partial' -mmin +"$PARTIAL_MAX_MINUTES")

  prune_key_history
}

# prune_key_history — a key copy goes only when no remaining set needs it and
# it is not the current key: without it, a set taken under that key cannot be
# restored. An entry is <fingerprint> (clear) or <fingerprint>.cred (encrypted
# on a protected host, AI-2146); both are judged by the fingerprint.
prune_key_history() {
  local key_dir current_fp d fp key_file cred
  key_dir="${OPENBAO_KEY_HISTORY_DIR:-/opt/aiadminpanel/secrets/openbao_unseal_key.d}"
  [ -d "$key_dir" ] || return 0
  # A kept set whose manifest cannot be read might need any key: keep them all.
  while IFS= read -r d; do
    if ! jq -e '.openbao.key_fingerprint | strings' "$d" >/dev/null 2>&1; then
      warn "cannot read ${d}; keeping every key copy this run"
      return 0
    fi
  done < <(find "$BACKUP_DIR" -mindepth 2 -maxdepth 2 -path "${BACKUP_DIR}/set-*/manifest.json" ! -path '*.partial/*')
  for d in "$BACKUP_DIR"/set-*; do
    case "$d" in *.partial) continue ;; esac
    if [ -d "$d" ] && [ ! -f "$d/manifest.json" ]; then
      warn "kept set $(basename "$d") has no manifest; keeping every key copy this run"
      return 0
    fi
  done
  cred="${OPENBAO_KEY_CRED:-/opt/aiadminpanel/secrets/openbao_unseal_key.cred}"
  key_file="${OPENBAO_KEY_FILE:-}"
  if [ -z "$key_file" ]; then
    if [ -s "$cred" ]; then key_file="${OPENBAO_RUN_KEY_FILE:-/run/aiadminpanel/openbao/openbao_unseal_key}"
    else key_file=/opt/aiadminpanel/secrets/openbao_unseal_key; fi
  fi
  # Without the current key's fingerprint nothing can be judged safely.
  if [ ! -s "$key_file" ]; then
    warn "cannot read the current unseal key at ${key_file}; keeping every key copy this run"
    return 0
  fi
  current_fp="$(sha256sum < "$key_file" | cut -d' ' -f1)"
  for d in "$key_dir"/*; do
    [ -f "$d" ] || continue
    fp="$(basename "$d")"
    fp="${fp%.cred}"
    [ "$fp" = "$current_fp" ] && continue
    if find "$BACKUP_DIR" -mindepth 2 -maxdepth 2 -path "${BACKUP_DIR}/set-*/manifest.json" \
        ! -path '*.partial/*' -exec jq -e --arg fp "$fp" '.openbao.key_fingerprint == $fp' {} \; 2>/dev/null \
        | grep -q true; then
      continue
    fi
    rm -f -- "$d"
    info "Removed key history entry ${fp}: no backup set needs it"
  done
}

# ── Main ───────────────────────────────────────────────────────────────────────
main() {
  info "=== Starting backup set ${TIMESTAMP} ==="

  acquire_lock || exit 1
  preflight || exit 1

  local set_dir="${BACKUP_DIR}/set-${TIMESTAMP}.partial"
  mkdir -m 700 "$set_dir"

  # The vault step's own lines go to the same log as everything else.
  if ! "${SCRIPT_DIR}/backup-openbao.sh" "$set_dir" 2>&1 | tee -a "$LOG_FILE"; then
    error "OpenBao copy failed; set left unfinished at ${set_dir}"
    exit 1
  fi

  local failed=0 db
  for db in "${DATABASES[@]}"; do
    if ! dump_database "$set_dir" "$db"; then
      failed=$((failed + 1))
    fi
  done
  if [ "$failed" -gt 0 ]; then
    error "Backup failed with ${failed} database failure(s); set left unfinished at ${set_dir}"
    exit 1
  fi

  write_manifest "$set_dir"
  mv "$set_dir" "${BACKUP_DIR}/set-${TIMESTAMP}"
  info "Backup set complete: ${BACKUP_DIR}/set-${TIMESTAMP}"

  rotate_sets
  info "=== Backup set ${TIMESTAMP} done ==="
}

# AAP_BACKUP_DEFINE_ONLY=1 lets the bats suite source the functions.
[ "${AAP_BACKUP_DEFINE_ONLY:-0}" = "1" ] || main "$@"
AAP_EMBED_BACKUP_DATABASES_EOF
}
_aap_embed_backup_openbao() {
  cat <<'AAP_EMBED_BACKUP_OPENBAO_EOF'
#!/usr/bin/env bash
# AI Admin Panel - OpenBao vault copy for the nightly backup set (AI-925)
#
# Copies the OpenBao data volume into a backup set, cold: the container is
# stopped for the few seconds the copy takes, then started again. The native
# snapshot API would need a privileged token the panel deliberately does not
# keep (docs/runbooks/openbao.md §2b).
#
# The copy is only readable with the unseal key it was encrypted under, and the
# key never goes into the set. The set records the key's SHA-256 fingerprint;
# the key itself is kept in OPENBAO_KEY_HISTORY_DIR/<fingerprint> (root, 0600)
# so that rotating the key later does not orphan older sets. On a host whose
# key is protected (AI-2146: secrets/openbao_unseal_key.cred exists) the key is
# read from its memory copy in /run, and the history entry is kept encrypted
# the same way, as <fingerprint>.cred: no clear copy is written to disk.
#
# Usage (normally called by backup-databases.sh):
#   backup-openbao.sh <set-dir>
#
# It holds the updater's lock while the vault is stopped, so an update never
# runs then. Called by backup-databases.sh it reuses the lock that script
# already holds (inherited on file descriptor 9); run on its own it takes it.
#
# Writes <set-dir>/openbao-data.tar.gz and <set-dir>/openbao.json (image,
# fingerprint, timestamps) for the caller's manifest. Exits non-zero on any
# failure, and always leaves OpenBao running if it was running before.

set -euo pipefail
umask 077

OPENBAO_CONTAINER="${OPENBAO_CONTAINER:-aiadminpanel_openbao}"
OPENBAO_DATA_VOLUME="${OPENBAO_DATA_VOLUME:-aiadminpanel_openbao_data}"
OPENBAO_KEY_CRED="${OPENBAO_KEY_CRED:-/opt/aiadminpanel/secrets/openbao_unseal_key.cred}"
OPENBAO_KEY_MODE_FILE="${OPENBAO_KEY_MODE_FILE:-${OPENBAO_KEY_CRED%.cred}.mode}"
OPENBAO_RUN_KEY_FILE="${OPENBAO_RUN_KEY_FILE:-/run/aiadminpanel/openbao/openbao_unseal_key}"
if [ -z "${OPENBAO_KEY_FILE:-}" ]; then
  if [ -s "$OPENBAO_KEY_CRED" ]; then OPENBAO_KEY_FILE="$OPENBAO_RUN_KEY_FILE"
  else OPENBAO_KEY_FILE=/opt/aiadminpanel/secrets/openbao_unseal_key; fi
fi
OPENBAO_KEY_HISTORY_DIR="${OPENBAO_KEY_HISTORY_DIR:-/opt/aiadminpanel/secrets/openbao_unseal_key.d}"
OPENBAO_START_TIMEOUT="${OPENBAO_START_TIMEOUT:-60}"
OPENBAO_POLL_INTERVAL="${OPENBAO_POLL_INTERVAL:-1}"
AAP_LOCK_FILE="${AAP_LOCK_FILE:-/opt/aiadminpanel/.update-work/lock}"
BACKUP_LOCK_WAIT="${BACKUP_LOCK_WAIT:-1800}"

log() { echo "[$(date -u '+%Y-%m-%dT%H:%M:%SZ')] [backup-openbao] $*"; }
fail() { log "ERROR: $*"; exit 1; }
now() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }

# health_json — the vault's own health report, read from inside its container
# (it publishes no port). The query makes every state answer 200 so wget prints
# the body instead of failing on a sealed or uninitialised vault.
health_json() {
  docker exec "$OPENBAO_CONTAINER" wget -q -O - \
    'http://127.0.0.1:8200/v1/sys/health?uninitcode=200&sealedcode=200&standbyok=true' 2>/dev/null
}

is_unsealed() {
  local body
  body="$(health_json)" || return 1
  [[ "$body" == *'"initialized":true'* && "$body" == *'"sealed":false'* ]]
}

wait_unsealed() {
  local waited=0
  while [ "$waited" -le "$OPENBAO_START_TIMEOUT" ]; do
    is_unsealed && return 0
    sleep "$OPENBAO_POLL_INTERVAL"
    waited=$((waited + 1))
  done
  return 1
}

# remember_key — keep a copy of the current key under its fingerprint. The
# value is only ever read by sha256sum and cp; it is never echoed, logged or
# passed as an argument.
remember_key() {
  local fp="$1" dest tmp
  if [ -L "$OPENBAO_KEY_HISTORY_DIR" ]; then
    fail "key history ${OPENBAO_KEY_HISTORY_DIR} is a link; refusing to write through it"
  fi
  mkdir -p "$OPENBAO_KEY_HISTORY_DIR"
  chmod 700 "$OPENBAO_KEY_HISTORY_DIR"
  dest="${OPENBAO_KEY_HISTORY_DIR}/${fp}"
  if [ -s "$OPENBAO_KEY_CRED" ]; then
    # Protected host: an encrypted entry, checked by decrypting it to a pipe.
    dest="${dest}.cred"
    [ -f "$dest" ] && return 0
    tmp="$(mktemp "${dest}.XXXXXX")"
    local mode=host
    [ -s "$OPENBAO_KEY_MODE_FILE" ] && mode="$(cat "$OPENBAO_KEY_MODE_FILE")"
    if ! systemd-creds encrypt --name=openbao_unseal_key --with-key="$mode" "$OPENBAO_KEY_FILE" "$tmp" >/dev/null 2>&1 \
        || [ "$(systemd-creds decrypt --name=openbao_unseal_key "$tmp" - 2>/dev/null | sha256sum | cut -d' ' -f1)" != "$fp" ]; then
      rm -f "$tmp"
      fail "could not keep an encrypted copy of the current key in ${OPENBAO_KEY_HISTORY_DIR}"
    fi
    chmod 600 "$tmp"
    mv "$tmp" "$dest"
    log "kept an encrypted copy of the current unseal key as key history entry ${fp}"
    return 0
  fi
  [ -f "$dest" ] && return 0
  tmp="$(mktemp "${dest}.XXXXXX")"
  cp "$OPENBAO_KEY_FILE" "$tmp"
  chmod 600 "$tmp"
  if [ "$(sha256sum < "$tmp" | cut -d' ' -f1)" != "$fp" ]; then
    rm -f "$tmp"
    fail "the key copy in ${OPENBAO_KEY_HISTORY_DIR} does not match the key file"
  fi
  mv "$tmp" "$dest"
  log "kept a copy of the current unseal key as key history entry ${fp}"
}

# hold_lock — the updater's lock, the same file and checks as aap-update.sh.
# A descriptor 9 inherited from backup-databases.sh that already points at the
# lock file is that script's held lock: flock on it succeeds at once. Opening
# the file again would be a second lock and wait on the first.
hold_lock() {
  local lock_dir waited=0
  if [ -e "$AAP_LOCK_FILE" ] && [ "$(readlink /proc/$$/fd/9 2>/dev/null)" = "$(readlink -f "$AAP_LOCK_FILE")" ] \
      && flock -n 9; then
    return 0
  fi
  lock_dir="$(dirname "$AAP_LOCK_FILE")"
  if [ -L "$lock_dir" ] || ! mkdir -p "$lock_dir" || ! chmod 700 "$lock_dir"; then
    fail "cannot use the lock folder ${lock_dir}"
  fi
  exec 9>"$AAP_LOCK_FILE"
  # A retry loop, not `flock -w`: BusyBox flock has no -w.
  until flock -n 9; do
    if [ "$waited" -ge "$BACKUP_LOCK_WAIT" ]; then
      fail "update in progress, vault copy skipped (lock ${AAP_LOCK_FILE} still taken after ${BACKUP_LOCK_WAIT}s)"
    fi
    sleep 1
    waited=$((waited + 1))
  done
}

STOPPED=0
restart_on_exit() {
  if [ "$STOPPED" = "1" ]; then
    log "starting ${OPENBAO_CONTAINER} again after a failed copy"
    docker start "$OPENBAO_CONTAINER" >/dev/null 2>&1 || log "ERROR: could not start ${OPENBAO_CONTAINER}; start it by hand"
  fi
}
trap restart_on_exit EXIT

main() {
  local set_dir="${1:-}"
  [ -n "$set_dir" ] && [ -d "$set_dir" ] || fail "usage: backup-openbao.sh <set-dir> (an existing folder)"
  [ -s "$OPENBAO_KEY_FILE" ] || fail "no unseal key file at ${OPENBAO_KEY_FILE}"
  hold_lock

  local fp image stopped_at started_at
  fp="$(sha256sum < "$OPENBAO_KEY_FILE" | cut -d' ' -f1)"

  image="$(docker inspect --format '{{.Config.Image}}' "$OPENBAO_CONTAINER" 2>/dev/null)" \
    || fail "OpenBao container ${OPENBAO_CONTAINER} not found"
  # Copy only a vault that is up and unsealed: a sealed or empty one has
  # nothing safe to back up, and stopping it would hide the real problem. At
  # boot (a timer catch-up run) it may still be starting, so wait for it.
  local start="$SECONDS"
  until is_unsealed; do
    if [ $((SECONDS - start)) -ge "${BACKUP_READY_WAIT:-300}" ]; then
      fail "OpenBao is not running, initialised and unsealed after ${BACKUP_READY_WAIT:-300}s; nothing stopped"
    fi
    sleep "${BACKUP_READY_INTERVAL:-5}"
  done

  remember_key "$fp"

  log "stopping ${OPENBAO_CONTAINER} for the copy"
  stopped_at="$(now)"
  STOPPED=1
  docker stop "$OPENBAO_CONTAINER" >/dev/null || fail "could not stop ${OPENBAO_CONTAINER}"
  # tar from the vault's own image: no extra image is pulled on the host, and
  # the volume is mounted read-only. The archive streams to stdout so it is
  # written here under umask 077, owned by root.
  if ! docker run --rm --entrypoint tar -v "${OPENBAO_DATA_VOLUME}:/openbao/file:ro" "$image" \
      -czf - -C /openbao/file . > "${set_dir}/openbao-data.tar.gz"; then
    fail "copying volume ${OPENBAO_DATA_VOLUME} failed"
  fi
  docker start "$OPENBAO_CONTAINER" >/dev/null || fail "could not start ${OPENBAO_CONTAINER}"
  STOPPED=0
  started_at="$(now)"
  wait_unsealed || fail "OpenBao did not report unsealed within ${OPENBAO_START_TIMEOUT}s after the copy"

  jq -n --arg image "$image" --arg fp "$fp" --arg stopped "$stopped_at" --arg started "$started_at" \
    '{image: $image, key_fingerprint: $fp, stopped_at: $stopped, started_at: $started}' \
    > "${set_dir}/openbao.json"
  log "vault copied (down from ${stopped_at} to ${started_at})"
}

main "$@"
AAP_EMBED_BACKUP_OPENBAO_EOF
}
_aap_embed_restore_openbao() {
  cat <<'AAP_EMBED_RESTORE_OPENBAO_EOF'
#!/usr/bin/env bash
# AI Admin Panel - restore the OpenBao vault from a backup set (AI-925)
#
# Puts the vault part of a set written by backup-databases.sh back into the
# OpenBao data volume. It is ONE step of the full-set restore order in
# docs/runbooks/openbao.md §3: stop the panel, restore both databases from the
# same set, run this, check the database against the vault, start the panel.
#
# It refuses rather than guesses:
#   - without --yes, or when the set's manifest is missing, not "complete", or
#     any file's checksum differs;
#   - while the panel container is running (the job worker runs inside it);
#   - while an update holds the updater's lock;
#   - when the set was taken under another unseal key than the current one;
#   - when the set was taken by a newer OpenBao than the one running.
# Before it overwrites anything it saves the current volume to
# BACKUP_DIR/pre-restore-<time>.tar.gz (backup-databases.sh keeps it 7 days).
# If the restored vault is not unsealed
# within OPENBAO_START_TIMEOUT seconds, it puts that copy back and exits 1.
#
# Usage:
#   restore-openbao.sh <set-dir> --yes

set -euo pipefail
umask 077

OPENBAO_CONTAINER="${OPENBAO_CONTAINER:-aiadminpanel_openbao}"
OPENBAO_DATA_VOLUME="${OPENBAO_DATA_VOLUME:-aiadminpanel_openbao_data}"
# AI-2146: on a protected host (the .cred exists) the current key is the clear
# copy in memory under /run, never a clear file on disk.
OPENBAO_KEY_CRED="${OPENBAO_KEY_CRED:-/opt/aiadminpanel/secrets/openbao_unseal_key.cred}"
OPENBAO_RUN_KEY_FILE="${OPENBAO_RUN_KEY_FILE:-/run/aiadminpanel/openbao/openbao_unseal_key}"
if [ -z "${OPENBAO_KEY_FILE:-}" ]; then
  if [ -s "$OPENBAO_KEY_CRED" ]; then OPENBAO_KEY_FILE="$OPENBAO_RUN_KEY_FILE"
  else OPENBAO_KEY_FILE=/opt/aiadminpanel/secrets/openbao_unseal_key; fi
fi
OPENBAO_KEY_HISTORY_DIR="${OPENBAO_KEY_HISTORY_DIR:-/opt/aiadminpanel/secrets/openbao_unseal_key.d}"
OPENBAO_START_TIMEOUT="${OPENBAO_START_TIMEOUT:-60}"
OPENBAO_POLL_INTERVAL="${OPENBAO_POLL_INTERVAL:-1}"
PANEL_CONTAINER="${PANEL_CONTAINER:-aiadminpanel_panel}"
BACKUP_DIR="${BACKUP_DIR:-/opt/aiadminpanel/backups}"
AAP_LOCK_FILE="${AAP_LOCK_FILE:-/opt/aiadminpanel/.update-work/lock}"

log() { echo "[$(date -u '+%Y-%m-%dT%H:%M:%SZ')] [restore-openbao] $*"; }
refuse() { log "REFUSED: $*"; exit 1; }
fail() { log "ERROR: $*"; exit 1; }

health_json() {
  docker exec "$OPENBAO_CONTAINER" wget -q -O - \
    'http://127.0.0.1:8200/v1/sys/health?uninitcode=200&sealedcode=200&standbyok=true' 2>/dev/null
}

wait_unsealed() {
  local waited=0 body
  while [ "$waited" -le "$OPENBAO_START_TIMEOUT" ]; do
    body="$(health_json)" || body=""
    if [[ "$body" == *'"initialized":true'* && "$body" == *'"sealed":false'* ]]; then
      return 0
    fi
    sleep "$OPENBAO_POLL_INTERVAL"
    waited=$((waited + 1))
  done
  return 1
}

# version_of <image> — the tag after the last colon, without a leading "v".
version_of() { local tag="${1##*:}"; [ "$tag" != "$1" ] || tag=""; printf '%s' "${tag#v}"; }

# put_archive <archive> — empty the data volume and unpack the archive into it,
# with the vault image's own tar (no extra image on the host).
put_archive() {
  docker run --rm -i --entrypoint sh -v "${OPENBAO_DATA_VOLUME}:/openbao/file" "$IMAGE" \
    -c 'find /openbao/file -mindepth 1 -delete && tar -xzf - -C /openbao/file' < "$1"
}

check_set() {
  local set_dir="$1" manifest="$1/manifest.json" name sha
  case "$set_dir" in *.partial|*.partial/) refuse "set ${set_dir} is unfinished (.partial)";; esac
  [ -f "$manifest" ] || refuse "no manifest.json in ${set_dir}"
  jq -e '.status == "complete"' "$manifest" >/dev/null 2>&1 || refuse "the manifest in ${set_dir} does not say complete"
  jq -e '.files[] | select(.name == "openbao-data.tar.gz")' "$manifest" >/dev/null \
    || refuse "the manifest in ${set_dir} lists no vault archive"
  while IFS=$'\t' read -r name sha; do
    case "$name" in */*|..|.|"") refuse "the manifest names an unexpected file: ${name}";; esac
    [ -f "${set_dir}/${name}" ] || refuse "${name} is missing from ${set_dir}"
    [ "$(sha256sum "${set_dir}/${name}" | cut -d' ' -f1)" = "$sha" ] \
      || refuse "${name} does not match its checksum in the manifest"
  done < <(jq -r '.files[] | [.name, .sha256] | @tsv' "$manifest")
}

STOPPED=0
PRE_RESTORE=""
TOUCHED=0
on_exit() {
  local rc=$?
  [ "$STOPPED" = "1" ] || return 0
  if [ "$TOUCHED" = "1" ] && [ -n "$PRE_RESTORE" ]; then
    log "putting the pre-restore copy back"
    docker stop "$OPENBAO_CONTAINER" >/dev/null 2>&1 || true
    put_archive "$PRE_RESTORE" || log "ERROR: could not put ${PRE_RESTORE} back; do it by hand (runbook §3)"
  fi
  docker start "$OPENBAO_CONTAINER" >/dev/null 2>&1 || log "ERROR: could not start ${OPENBAO_CONTAINER}"
  [ "$rc" -ne 0 ] || exit 1
}
trap on_exit EXIT

main() {
  local set_dir="" yes=0 arg
  for arg in "$@"; do
    case "$arg" in
      --yes) yes=1 ;;
      -*) fail "unknown option ${arg}" ;;
      *) set_dir="${arg%/}" ;;
    esac
  done
  [ -n "$set_dir" ] && [ -d "$set_dir" ] || fail "usage: restore-openbao.sh <set-dir> --yes"
  [ "$yes" = "1" ] || refuse "this replaces the vault's data; run again with --yes"
  command -v jq >/dev/null 2>&1 || fail "jq is not installed"

  check_set "$set_dir"
  local manifest="${set_dir}/manifest.json"

  # The panel container runs the API and the job worker. While it runs it can
  # write to the vault and the database that the restore is about to change.
  if [ "$(docker inspect --format '{{.State.Running}}' "$PANEL_CONTAINER" 2>/dev/null || true)" = "true" ]; then
    refuse "the panel (${PANEL_CONTAINER}) is running; stop it first (docker compose stop panel), see the runbook's full-set restore order"
  fi

  local lock_dir
  lock_dir="$(dirname "$AAP_LOCK_FILE")"
  if [ -L "$lock_dir" ] || ! mkdir -p "$lock_dir" || ! chmod 700 "$lock_dir"; then
    fail "cannot use the lock folder ${lock_dir}"
  fi
  exec 9>"$AAP_LOCK_FILE"
  flock -n 9 || refuse "an update or a backup is running; try again when it is done"

  [ -s "$OPENBAO_KEY_FILE" ] || fail "no unseal key file at ${OPENBAO_KEY_FILE}"
  local want_fp have_fp
  want_fp="$(jq -r '.openbao.key_fingerprint' "$manifest")"
  have_fp="$(sha256sum < "$OPENBAO_KEY_FILE" | cut -d' ' -f1)"
  if [ "$want_fp" != "$have_fp" ] && [ -s "$OPENBAO_KEY_CRED" ]; then
    refuse "the set was taken under another unseal key (${want_fp}). To restore under that key, copy ${OPENBAO_KEY_HISTORY_DIR}/${want_fp}.cred over ${OPENBAO_KEY_CRED}, run aap-openbao-key unlock, restart OpenBao (docker compose up -d --force-recreate openbao), then run this again. Runbook: docs/runbooks/openbao.md §3"
  fi
  if [ "$want_fp" != "$have_fp" ]; then
    refuse "the set was taken under another unseal key (${want_fp}). To restore under that key, copy ${OPENBAO_KEY_HISTORY_DIR}/${want_fp} over ${OPENBAO_KEY_FILE} with mode 0644 (the non-root OpenBao server must read it; a 0600 copy leaves the vault sealed), restart OpenBao, then run this again. Runbook: docs/runbooks/openbao.md §3"
  fi

  IMAGE="$(docker inspect --format '{{.Config.Image}}' "$OPENBAO_CONTAINER" 2>/dev/null)" \
    || fail "OpenBao container ${OPENBAO_CONTAINER} not found"
  local backup_v running_v
  backup_v="$(version_of "$(jq -r '.openbao.image' "$manifest")")"
  running_v="$(version_of "$IMAGE")"
  [ -n "$backup_v" ] && [ -n "$running_v" ] || refuse "cannot compare OpenBao versions (set: '${backup_v}', running: '${running_v}')"
  if [ "$backup_v" != "$running_v" ] && \
     [ "$(printf '%s\n%s\n' "$backup_v" "$running_v" | sort -V | tail -1)" = "$backup_v" ]; then
    refuse "the set was taken by OpenBao ${backup_v}, newer than the running ${running_v}"
  fi

  mkdir -p "$BACKUP_DIR"
  chmod 700 "$BACKUP_DIR"
  PRE_RESTORE="${BACKUP_DIR}/pre-restore-$(date -u +%Y%m%dT%H%M%SZ).tar.gz"

  log "stopping ${OPENBAO_CONTAINER}"
  STOPPED=1
  docker stop "$OPENBAO_CONTAINER" >/dev/null || fail "could not stop ${OPENBAO_CONTAINER}"
  # Written as .partial and renamed only once tar succeeded: a cut-off copy
  # must never sit there under a name that looks like a good one (AI-1249).
  if ! docker run --rm --entrypoint tar -v "${OPENBAO_DATA_VOLUME}:/openbao/file:ro" "$IMAGE" \
      -czf - -C /openbao/file . > "${PRE_RESTORE}.partial"; then
    rm -f "${PRE_RESTORE}.partial"
    fail "could not save the current volume; nothing was changed"
  fi
  mv "${PRE_RESTORE}.partial" "$PRE_RESTORE"
  log "current vault saved to ${PRE_RESTORE}"

  TOUCHED=1
  put_archive "${set_dir}/openbao-data.tar.gz" || fail "unpacking the set failed"
  docker start "$OPENBAO_CONTAINER" >/dev/null || fail "could not start ${OPENBAO_CONTAINER}"
  if ! wait_unsealed; then
    log "the restored vault did not unseal within ${OPENBAO_START_TIMEOUT}s"
    fail "restore rolled back"
  fi
  STOPPED=0
  log "vault restored from $(basename "$set_dir"). The panel is still stopped: check the database against the vault (runbook §3), then start it."
}

main "$@"
AAP_EMBED_RESTORE_OPENBAO_EOF
}
_aap_embed_backup_service() {
  cat <<'AAP_EMBED_BACKUP_SERVICE_EOF'
[Unit]
Description=AI Admin Panel — nightly backup set: OpenBao vault + both databases (oneshot)
Documentation=https://docs.aiadminpanel.com/docs/admin/backup-restore
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
# Runs as root: it stops the OpenBao container for the few seconds of the vault
# copy, reads the unseal key to fingerprint it, and writes root-only (0700/0600)
# sets under /opt/aiadminpanel/backups. It shares the updater's lock, so an
# update never runs while the vault is stopped. Its log: journalctl -u
# aap-backup.service, and /var/log/aiadminpanel/backup.log.
ExecStart=/opt/aiadminpanel/backup-databases.sh
AAP_EMBED_BACKUP_SERVICE_EOF
}
_aap_embed_backup_timer() {
  cat <<'AAP_EMBED_BACKUP_TIMER_EOF'
[Unit]
Description=AI Admin Panel — run the nightly backup set at 03:00 host time
Documentation=https://docs.aiadminpanel.com/docs/admin/backup-restore

[Timer]
OnCalendar=*-*-* 03:00:00
# A host that was off at 03:00 runs the missed backup at the next boot.
Persistent=true
Unit=aap-backup.service

[Install]
WantedBy=timers.target
AAP_EMBED_BACKUP_TIMER_EOF
}
_aap_embed_openbao_key() {
  cat <<'AAP_EMBED_OPENBAO_KEY_EOF'
#!/usr/bin/env bash
# AI Admin Panel - OpenBao unseal key protection at rest (AI-2146)
#
# Keeps the OpenBao unseal key encrypted on disk with systemd-creds and puts a
# clear copy only in memory (/run, tmpfs) for OpenBao to read. Design and threat
# table: docs/specs/2026-11-06-ai-2146-unseal-key-at-rest.md.
#
#   secrets/openbao_unseal_key.cred   the key, encrypted (TPM2 + host key when
#                                     the host has a TPM2, the host key only
#                                     otherwise)
#   secrets/openbao_unseal_key.mode   "host+tpm2" or "host": what protects it
#   /run/aiadminpanel/openbao/openbao_unseal_key
#                                     the clear copy compose mounts into OpenBao
#                                     (OPENBAO_UNSEAL_KEY_FILE in .env)
#
# What it protects against, honestly: with "host" the key that opens the .cred
# (/var/lib/systemd/credential.secret) is on the same disk, so a copy of
# /opt/aiadminpanel alone is safe, but a full-disk copy or a provider snapshot
# still opens the vault ("partial protection"). With "host+tpm2" a disk copy
# cannot open it. Root on the running host can always read the key.
#
# Commands (root, on the box):
#   status [--json]      mode, fingerprint, whether /run holds the key; also
#                        refreshes update/openbao-key.json for the panel
#   protect [--yes]      encrypt the clear key, move OpenBao to the /run copy,
#                        then delete the clear key. Without --yes it first shows
#                        the recovery key and waits for SAVED to be typed.
#   unlock               decrypt into /run (run by aap-openbao-key.service at
#                        boot, before Docker). Fails closed: no file on error.
#   export               print the clear key once, for an offline copy
#   import <file> [--yes]
#                        encrypt a saved key on this host (new host, TPM reset)
#
# The key value is never logged, never passed as an argument and never written
# to disk in clear by this script; it moves through pipes and the tmpfs file.

set -euo pipefail
umask 077

PANEL_DIR="${PANEL_DIR:-/opt/aiadminpanel}"
SECRETS_DIR="${SECRETS_DIR:-${PANEL_DIR}/secrets}"
CLEAR_KEY="${SECRETS_DIR}/openbao_unseal_key"
CRED_FILE="${SECRETS_DIR}/openbao_unseal_key.cred"
MODE_FILE="${SECRETS_DIR}/openbao_unseal_key.mode"
HISTORY_DIR="${OPENBAO_KEY_HISTORY_DIR:-${SECRETS_DIR}/openbao_unseal_key.d}"
RUN_DIR="${AAP_OPENBAO_RUN_DIR:-/run/aiadminpanel/openbao}"
RUN_KEY="${RUN_DIR}/openbao_unseal_key"
ENV_FILE="${PANEL_DIR}/.env"
COMPOSE_FILE="${PANEL_DIR}/docker-compose.yml"
STATUS_FILE="${PANEL_DIR}/update/openbao-key.json"
# Root-only, beside update/ (same filesystem, so a rename is a rename): the
# report is built here, never in update/, which the panel container can write.
WORK_DIR="${PANEL_DIR}/.openbao-key-work"
OPENBAO_CONTAINER="${OPENBAO_CONTAINER:-aiadminpanel_openbao}"
OPENBAO_START_TIMEOUT="${OPENBAO_START_TIMEOUT:-60}"
OPENBAO_POLL_INTERVAL="${OPENBAO_POLL_INTERVAL:-1}"
CRED_NAME="openbao_unseal_key"
UNIT="aap-openbao-key.service"

log() { echo "[aap-openbao-key] $*" >&2; }
fail() { log "ERROR: $*"; exit 1; }
refuse() { log "REFUSED: $*"; exit 1; }

fp_of() { sha256sum < "$1" | cut -d' ' -f1; }

# creds_supported — systemd-creds 250 or later (Ubuntu 22.04 has 249).
creds_supported() {
  command -v systemd-creds >/dev/null 2>&1 || return 1
  local v
  v="$(systemd-creds --version 2>/dev/null | awk 'NR==1 {print $2}')"
  case "$v" in ''|*[!0-9]*) return 1 ;; esac
  [ "$v" -ge 250 ]
}

pick_mode() {
  if systemd-creds has-tpm2 >/dev/null 2>&1; then echo "host+tpm2"; else echo "host"; fi
}

current_mode() {
  if [ -s "$CRED_FILE" ]; then
    if [ -s "$MODE_FILE" ]; then cat "$MODE_FILE"; else echo "host"; fi
  else
    echo "clear"
  fi
}

# decrypt_to <cred> <out|-> — the credential's clear value.
decrypt_to() { systemd-creds decrypt --name="$CRED_NAME" "$1" "$2"; }

# encrypt_verified <in> <dest> <mode> <fp> — encrypt, prove the round trip gives
# the same fingerprint, then rename into place. Nothing is left on failure.
encrypt_verified() {
  local in="$1" dest="$2" mode="$3" fp="$4" tmp
  tmp="$(mktemp "${dest}.XXXXXX")"
  if ! systemd-creds encrypt --name="$CRED_NAME" --with-key="$mode" "$in" "$tmp" >/dev/null 2>&1; then
    rm -f "$tmp"
    return 1
  fi
  if [ "$(decrypt_to "$tmp" - 2>/dev/null | sha256sum | cut -d' ' -f1)" != "$fp" ]; then
    rm -f "$tmp"
    return 2
  fi
  chmod 600 "$tmp"
  mv -f "$tmp" "$dest"
}

remove_clear() {
  if command -v shred >/dev/null 2>&1; then shred -u -- "$1" 2>/dev/null || rm -f -- "$1"; else rm -f -- "$1"; fi
}

# env_set KEY VALUE / env_unset KEY — edit .env in place, one line per key.
env_set() {
  local key="$1" value="$2" tmp
  [ -f "$ENV_FILE" ] || ( umask 077; : > "$ENV_FILE" )
  tmp="$(mktemp "${ENV_FILE}.XXXXXX")"
  grep -v "^${key}=" "$ENV_FILE" > "$tmp" || true
  printf '%s=%s\n' "$key" "$value" >> "$tmp"
  chmod --reference="$ENV_FILE" "$tmp" 2>/dev/null || chmod 600 "$tmp"
  mv -f "$tmp" "$ENV_FILE"
}
env_unset() {
  local key="$1" tmp
  [ -f "$ENV_FILE" ] || return 0
  tmp="$(mktemp "${ENV_FILE}.XXXXXX")"
  grep -v "^${key}=" "$ENV_FILE" > "$tmp" || true
  chmod --reference="$ENV_FILE" "$tmp" 2>/dev/null || chmod 600 "$tmp"
  mv -f "$tmp" "$ENV_FILE"
}

# publish_status <tmp> — rename the finished file over STATUS_FILE. GNU mv -T
# replaces a planted link, also one to a folder, by rename(2). BusyBox mv (the
# Alpine image the installer tests run in) refuses a link to a folder instead;
# then the link itself is unlinked (rm never follows it) and the rename is
# tried once more. Nothing is ever written through the link.
publish_status() {
  mv -fT -- "$1" "$STATUS_FILE" 2>/dev/null && return 0
  [ -L "$STATUS_FILE" ] && rm -f -- "$STATUS_FILE" && mv -fT -- "$1" "$STATUS_FILE"
}

# prepare_work_dir — the root-only work area beside update/. Refused when it is
# a link, not ours, or on another filesystem than update/ (mv would then copy
# into update/ by path instead of renaming).
prepare_work_dir() {
  mkdir -p -- "$WORK_DIR" || return 1
  [ -d "$WORK_DIR" ] && [ ! -L "$WORK_DIR" ] || return 1
  [ "$(stat -c %u -- "$WORK_DIR")" = "$(id -u)" ] || return 1
  chmod 700 -- "$WORK_DIR" || return 1
  [ "$(stat -c %d -- "$WORK_DIR")" = "$(stat -c %d -- "$(dirname "$STATUS_FILE")")" ]
}

# write_status — the panel's view (read-only for it), in the host-shared update
# folder: the mode only, never the key or its fingerprint. update/ is writable
# from the panel container (AI-2443), so nothing is written there by path: the
# file is built in the work area and renamed over the report with mv -T, which
# replaces a planted link (to a file or a folder) instead of following it. The
# report is only a view, so a failure is a warning, never a failed unlock.
write_status() {
  local dir mode protected=false tmp
  dir="$(dirname "$STATUS_FILE")"
  [ -d "$dir" ] || return 0
  mode="$(current_mode)"
  [ "$mode" = "clear" ] || protected=true
  if ! creds_supported && [ "$mode" = "clear" ]; then mode="clear-unsupported"; fi
  if ! prepare_work_dir || ! tmp="$(mktemp "${WORK_DIR}/status.XXXXXX")"; then
    # A stale report must not stay visible: rm unlinks, it never follows.
    rm -f -- "$STATUS_FILE" 2>/dev/null || true
    log "WARNING: no safe work area at ${WORK_DIR}; ${STATUS_FILE} removed, not written"
    return 0
  fi
  if printf '{"mode":"%s","protected":%s,"updated_at":"%s"}\n' \
      "$mode" "$protected" "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" > "$tmp" \
      && chmod 644 "$tmp" && publish_status "$tmp"; then
    return 0
  fi
  rm -f -- "$tmp"
  log "WARNING: could not write ${STATUS_FILE}"
}

# unlock — decrypt into /run. A failed decrypt leaves NO key file, so compose
# cannot bind-mount it and OpenBao does not start (fails closed, never with an
# empty or stale key).
cmd_unlock() {
  if [ ! -s "$CRED_FILE" ]; then
    log "no encrypted key at ${CRED_FILE}; nothing to unlock"
    return 0
  fi
  mkdir -p "$RUN_DIR"
  chmod 700 "$RUN_DIR"
  rm -f "$RUN_KEY"
  local tmp
  tmp="$(mktemp "${RUN_KEY}.XXXXXX")"
  if ! decrypt_to "$CRED_FILE" "$tmp" >/dev/null 2>&1 || [ ! -s "$tmp" ]; then
    rm -f "$tmp"
    fail "cannot decrypt ${CRED_FILE} on this host; OpenBao stays sealed. If the TPM or the host changed, import your recovery key: aap-openbao-key import <file>"
  fi
  # 0644: the non-root OpenBao server reads it through the bind mount; the
  # folder is root-only.
  chmod 644 "$tmp"
  mv -f "$tmp" "$RUN_KEY"
  write_status
  log "unseal key decrypted into ${RUN_KEY} (memory only)"
}

health_unsealed() {
  local body
  body="$(docker exec "$OPENBAO_CONTAINER" wget -q -O - \
    'http://127.0.0.1:8200/v1/sys/health?uninitcode=200&sealedcode=200&standbyok=true' 2>/dev/null)" || return 1
  [[ "$body" == *'"initialized":true'* && "$body" == *'"sealed":false'* ]]
}

wait_unsealed() {
  local waited=0
  while [ "$waited" -le "$OPENBAO_START_TIMEOUT" ]; do
    health_unsealed && return 0
    sleep "$OPENBAO_POLL_INTERVAL"
    waited=$((waited + 1))
  done
  return 1
}

recreate_openbao() {
  docker compose -f "$COMPOSE_FILE" --env-file "$ENV_FILE" up -d --no-deps --force-recreate openbao >/dev/null
}

confirm_recovery_key() {
  local src="$1" answer=""
  cat <<EOF
===========================================================
  OpenBao recovery key (shown once)
===========================================================
  $(cat "$src")

  After this step the key on disk is encrypted for THIS host
  only. If the host is lost, only this recovery key opens
  your vault backups. Store it offline now (password manager
  or paper). Do not store it on this server.

  Type SAVED and press Enter to continue:
EOF
  IFS= read -r answer || true
  [ "$answer" = "SAVED" ] || refuse "the recovery key was not confirmed; nothing was changed"
}

mode_label() {
  case "$1" in
    host+tpm2) echo "protected by this host's TPM2 and host key: a disk copy or provider snapshot cannot open the vault" ;;
    host) echo "partial protection (host key, no TPM2): a copy of ${PANEL_DIR} cannot open the vault, but a full-disk copy or provider snapshot still can. See ADR 0018 (external unseal)" ;;
    *) echo "not protected: the clear key is on disk" ;;
  esac
}

# protect_history <mode> — every clear key history entry becomes <fp>.cred.
protect_history() {
  local mode="$1" f fp rc
  [ -d "$HISTORY_DIR" ] || return 0
  [ ! -L "$HISTORY_DIR" ] || fail "key history ${HISTORY_DIR} is a link; refusing to write through it"
  for f in "$HISTORY_DIR"/*; do
    [ -f "$f" ] || continue
    case "$f" in *.cred) continue ;; esac
    fp="$(basename "$f")"
    [ "$(fp_of "$f")" = "$fp" ] || fail "key history entry ${fp} does not match its name; left as it is"
    rc=0
    encrypt_verified "$f" "${f}.cred" "$mode" "$fp" || rc=$?
    [ "$rc" -eq 0 ] || fail "could not encrypt key history entry ${fp}; left as it is"
    remove_clear "$f"
  done
}

cmd_protect() {
  local yes=0 arg
  for arg in "$@"; do
    case "$arg" in --yes) yes=1 ;; *) fail "unknown option ${arg}" ;; esac
  done
  creds_supported || refuse "this host has no systemd-creds 250 or later (Ubuntu 22.04 has 249); the unseal key stays in clear at ${CLEAR_KEY}"

  if [ -s "$CRED_FILE" ] && [ ! -e "$CLEAR_KEY" ]; then
    log "the unseal key is already protected ($(current_mode))"
    write_status
    return 0
  fi
  [ -s "$CLEAR_KEY" ] || fail "no unseal key at ${CLEAR_KEY}"
  [ "$yes" = "1" ] || confirm_recovery_key "$CLEAR_KEY"

  local mode fp rc=0
  mode="$(pick_mode)"
  fp="$(fp_of "$CLEAR_KEY")"
  encrypt_verified "$CLEAR_KEY" "$CRED_FILE" "$mode" "$fp" || rc=$?
  case "$rc" in
    0) ;;
    2) refuse "the decrypted key does not match the clear key; nothing was changed" ;;
    *) fail "systemd-creds could not encrypt the key (mode ${mode}); nothing was changed" ;;
  esac
  printf '%s\n' "$mode" > "$MODE_FILE"
  chmod 600 "$MODE_FILE"

  # From here a failure must put the box back on the clear key.
  rollback() {
    log "putting OpenBao back on the clear key at ${CLEAR_KEY}"
    env_unset OPENBAO_UNSEAL_KEY_FILE
    rm -f "$CRED_FILE" "$MODE_FILE" "$RUN_KEY"
    if docker inspect "$OPENBAO_CONTAINER" >/dev/null 2>&1; then
      recreate_openbao || log "ERROR: could not recreate OpenBao; run: docker compose -f ${COMPOSE_FILE} up -d openbao"
    fi
    write_status
  }

  if ! ( cmd_unlock ) || [ "$(fp_of "$RUN_KEY")" != "$fp" ]; then
    rollback
    fail "the key in ${RUN_KEY} is not the clear key; nothing kept"
  fi
  env_set OPENBAO_UNSEAL_KEY_FILE "$RUN_KEY"
  if command -v systemctl >/dev/null 2>&1; then
    systemctl enable "$UNIT" >/dev/null 2>&1 || log "WARNING: could not enable ${UNIT}; OpenBao will not unseal after a reboot until it is enabled"
  fi

  # Prove OpenBao unseals from the /run copy before the clear key goes.
  if docker inspect "$OPENBAO_CONTAINER" >/dev/null 2>&1; then
    if ! recreate_openbao || ! wait_unsealed; then
      rollback
      fail "OpenBao did not unseal from ${RUN_KEY} within ${OPENBAO_START_TIMEOUT}s; it is back on the clear key"
    fi
  fi

  protect_history "$mode"
  remove_clear "$CLEAR_KEY"
  write_status
  log "unseal key protected: $(mode_label "$mode")"
}

cmd_export() {
  if [ -s "$CRED_FILE" ]; then
    log "printing the clear unseal key once; store it offline, not on this server"
    decrypt_to "$CRED_FILE" - || fail "cannot decrypt ${CRED_FILE} on this host"
    echo
  elif [ -s "$CLEAR_KEY" ]; then
    log "the key is not protected; printing ${CLEAR_KEY}"
    cat "$CLEAR_KEY"
    echo
  else
    fail "no unseal key on this host"
  fi
}

cmd_import() {
  local src="" yes=0 arg
  for arg in "$@"; do
    case "$arg" in --yes) yes=1 ;; -*) fail "unknown option ${arg}" ;; *) src="$arg" ;; esac
  done
  [ -n "$src" ] && [ -f "$src" ] || fail "usage: aap-openbao-key import <file> [--yes]"
  creds_supported || refuse "this host has no systemd-creds 250 or later; copy the key to ${CLEAR_KEY} (mode 0644) instead"
  local tmp mode fp rc=0
  mkdir -p "$RUN_DIR"
  chmod 700 "$RUN_DIR"
  tmp="$(mktemp "${RUN_DIR}/import.XXXXXX")"
  # The installer writes the key without a newline; a saved copy usually has one.
  tr -d ' \t\r\n' < "$src" > "$tmp"
  if ! grep -qxE '[0-9a-f]{64}' "$tmp"; then
    rm -f "$tmp"
    refuse "${src} does not hold an unseal key (64 hex characters)"
  fi
  fp="$(fp_of "$tmp")"
  if [ -s "$CRED_FILE" ] && [ "$yes" != "1" ]; then
    if [ "$(decrypt_to "$CRED_FILE" - 2>/dev/null | sha256sum | cut -d' ' -f1)" != "$fp" ]; then
      rm -f "$tmp"
      refuse "${CRED_FILE} holds another key; run again with --yes to replace it"
    fi
  fi
  mode="$(pick_mode)"
  encrypt_verified "$tmp" "$CRED_FILE" "$mode" "$fp" || rc=$?
  rm -f "$tmp"
  [ "$rc" -eq 0 ] || fail "could not encrypt the imported key; nothing was changed"
  printf '%s\n' "$mode" > "$MODE_FILE"
  chmod 600 "$MODE_FILE"
  cmd_unlock
  env_set OPENBAO_UNSEAL_KEY_FILE "$RUN_KEY"
  if command -v systemctl >/dev/null 2>&1; then
    systemctl enable "$UNIT" >/dev/null 2>&1 || true
  fi
  log "key ${fp} imported ($(mode_label "$mode")). Start OpenBao: docker compose -f ${COMPOSE_FILE} up -d --force-recreate openbao"
}

cmd_status() {
  local json=0 mode fp="" memory=false
  [ "${1:-}" = "--json" ] && json=1
  # Refreshes the panel's view too (the installer runs it after an update).
  write_status
  mode="$(current_mode)"
  [ -s "$RUN_KEY" ] && memory=true
  if [ -s "$RUN_KEY" ]; then fp="$(fp_of "$RUN_KEY")"
  elif [ -s "$CLEAR_KEY" ]; then fp="$(fp_of "$CLEAR_KEY")"; fi
  if [ "$json" = "1" ]; then
    printf '{"mode":"%s","protected":%s,"fingerprint":"%s","memory_copy":%s,"supported":%s}\n' \
      "$mode" "$([ "$mode" = "clear" ] && echo false || echo true)" "$fp" "$memory" \
      "$(creds_supported && echo true || echo false)"
  else
    echo "mode:        ${mode} ($(mode_label "$mode"))"
    echo "fingerprint: ${fp:-unknown}"
    echo "memory copy: ${memory} (${RUN_KEY})"
  fi
}

main() {
  local cmd="${1:-}"
  [ $# -eq 0 ] || shift
  case "$cmd" in
    status) cmd_status "$@" ;;
    protect) cmd_protect "$@" ;;
    unlock) cmd_unlock ;;
    export) cmd_export ;;
    import) cmd_import "$@" ;;
    *) echo "usage: aap-openbao-key {status [--json]|protect [--yes]|unlock|export|import <file> [--yes]}" >&2; exit 2 ;;
  esac
}

main "$@"
AAP_EMBED_OPENBAO_KEY_EOF
}
_aap_embed_openbao_key_service() {
  cat <<'AAP_EMBED_OPENBAO_KEY_SERVICE_EOF'
[Unit]
Description=AI Admin Panel — decrypt the OpenBao unseal key into memory (oneshot, AI-2146)
Documentation=https://docs.aiadminpanel.com/docs/admin/backup-restore
# Only on a host whose key is encrypted (aap-openbao-key protect). Elsewhere
# OpenBao reads the clear key file and this unit does nothing.
ConditionPathExists=/opt/aiadminpanel/secrets/openbao_unseal_key.cred
# Before Docker: restart: unless-stopped starts OpenBao when the daemon starts,
# and a start that fails then (no key file to bind-mount) is not retried.
Before=docker.service
After=local-fs.target

[Service]
Type=oneshot
RemainAfterExit=yes
# Decrypts secrets/openbao_unseal_key.cred with systemd-creds into
# /run/aiadminpanel/openbao/openbao_unseal_key (tmpfs; folder 0700 root). On
# failure it leaves no file, so OpenBao does not start: it fails closed.
ExecStart=/opt/aiadminpanel/aap-openbao-key.sh unlock

[Install]
WantedBy=docker.service multi-user.target
AAP_EMBED_OPENBAO_KEY_SERVICE_EOF
}
# AI-2194: private access, written by the installer but never enabled by it.
_aap_embed_private_access() {
  cat <<'AAP_EMBED_PRIVATE_ACCESS_EOF'
#!/usr/bin/env bash
# aap-private-access.sh — put this panel host on the operator's own private
# network (Tailscale, or Headscale with the same client), so the panel can be
# opened there under a private hostname (AI-2194). Runs as root on the host,
# by hand for the first join and from aap-private-access.timer after that.
# Spec: docs/specs/2026-11-12-private-access.md
#
# WHY ON THE HOST. The network is a property of the server, not of one
# container: the client keeps working while the panel is down (when an admin
# most needs the host), survives panel updates, and gives the egress guard a
# real interface (tailscale0) to name. It follows the egress guard's contract:
# a root script, a timer, and a JSON status file the panel only reads.
#
# WHAT THE NODE MAY DO. One tagged node that admins reach; nothing more. The
# join always passes --accept-dns=false and --accept-routes=false (the host's
# resolver and routes, which Docker builds on, stay as they are), --ssh=false,
# no exit node, no advertised routes, shields down (it would block the panel),
# then turns the web client off and resets Serve and Funnel. Options that turn
# any of these on are refused, and every run sets them off again, so a change
# made by hand does not last longer than five minutes. Whatever still differs
# afterwards is reported as a problem and the status says failed.
#
# THE JOIN KEY. One-time, read from a file (deleted after the attempt) or from
# stdin, checked against the key character set, and handed to the client as
# "file:<path>" from a 0600 file in a 0700 directory under /run that is
# deleted on exit. Never on a command line (ps shows those to every user),
# never in the status file, the saved settings or any output: the client's
# messages are printed with the key replaced by [redacted].
#
# SAVED SETTINGS. /etc/aiadminpanel/private-access.conf, root-owned, not
# secret: NETWORK, LOGIN_SERVER, HOSTNAME, TAGS, INTERFACE. Read with grep,
# never sourced. It is outside the panel's shared update/ directory on purpose:
# the egress guard reads INTERFACE for its anti-spoof rule, and the panel
# container must not be able to change which interface that rule trusts.
#
# THE EGRESS GUARD. Its rule 1 always keeps containers off 100.64.0.0/10
# (AI-2287). With the saved settings present it also drops new connections from
# that range to Traefik's ports 80 and 443 unless they arrive on INTERFACE
# (AI-2194). apply and remove re-run it, and private access counts as
# connected only when the guard applied.
#
# NODE STATE. /var/lib/tailscale holds the node's identity. It stays on this
# host and is not part of panel backups; a restore on another host joins with
# a new key.
#
# Commands:
#   plan    print what apply would do; changes nothing
#   apply   install the client if missing, join with a key or re-assert the
#           safe settings, re-run the egress guard, write the status file
#   status  print "connected …" or the reason it is not; changes nothing
#   remove  log out, stop the client and the timer, drop the saved settings,
#           re-run the egress guard (rollback). The package stays installed.
#
# Options (plan and apply):
#   --network tailscale|headscale   default: the saved one, else tailscale
#   --login-server URL              Headscale only: https://host[:port][/path]
#   --auth-key-file PATH            the one-time key, file mode 0600; deleted
#   --auth-key-stdin                the one-time key on stdin
#   --hostname NAME                 node name, default aap-panel
#   --tags tag:a[,tag:b]            default tag:aap-panel
#   --no-install                    fail instead of installing the client
#
# The status file (update/private-access.json) holds
# {"status": "connected" | "disconnected" | "failed" | "off" | "unsupported",
#  "checked_at", "reason", "network", "login_server", "node_name",
#  "tailnet_ipv4", "interface", "tags": [], "client_version", "backend_state",
#  "egress_guard", "problems": []}.
#
# Exit codes: 0 connected / done / off, 1 failed or not connected, 2 usage or a
# refused option, 3 unsupported (no package path for this system).
#
# Overrides, for tests only; each must be an absolute path:
#   AAP_PRIVATE_ACCESS_STATUS_FILE, AAP_PRIVATE_ACCESS_CONF,
#   AAP_PRIVATE_ACCESS_LOCK, AAP_PRIVATE_ACCESS_KEY_DIR,
#   AAP_PRIVATE_ACCESS_EGRESS_GUARD, AAP_PRIVATE_ACCESS_OS_RELEASE,
#   AAP_PRIVATE_ACCESS_PKG_ROOT (prefix for the package manager's files)
#   AAP_PRIVATE_ACCESS_ALLOW_HTTP_LOGIN_SERVER=1 accepts an http:// login
#   server (the local Headscale proof only; a real one needs TLS)

set -u

STATUS_FILE="${AAP_PRIVATE_ACCESS_STATUS_FILE:-/opt/aiadminpanel/update/private-access.json}"
CONF_FILE="${AAP_PRIVATE_ACCESS_CONF:-/etc/aiadminpanel/private-access.conf}"
LOCK_FILE="${AAP_PRIVATE_ACCESS_LOCK:-/run/aap-private-access.lock}"
KEY_DIR="${AAP_PRIVATE_ACCESS_KEY_DIR:-/run/aap-private-access}"
EGRESS_GUARD="${AAP_PRIVATE_ACCESS_EGRESS_GUARD:-/opt/aiadminpanel/aap-egress-guard.sh}"
OS_RELEASE="${AAP_PRIVATE_ACCESS_OS_RELEASE:-/etc/os-release}"
PKG_ROOT="${AAP_PRIVATE_ACCESS_PKG_ROOT:-}"
PKG_BASE="https://pkgs.tailscale.com/stable"
TIMER="aap-private-access.timer"
DEFAULT_TAGS="tag:aap-panel"
DEFAULT_HOSTNAME="aap-panel"
TS_INTERFACE="tailscale0"

CMD=""
OPT_NETWORK=""
OPT_LOGIN_SERVER=""
OPT_LOGIN_SET=false
OPT_HOSTNAME=""
OPT_TAGS=""
KEY_SOURCE=""
KEY_FILE_ARG=""
NO_INSTALL=false
KEY=""
KEY_TMP=""
JQ=""
# Effective settings: options over saved settings over defaults.
NETWORK=""
LOGIN_SERVER=""
HOSTNAME_=""
TAGS=""
HAVE_CONF=false
GUARD_RESULT="not run"
PROBLEMS=()

usage() {
  echo "usage: $0 plan|apply|status|remove [--network tailscale|headscale] [--login-server URL] [--auth-key-file PATH | --auth-key-stdin] [--hostname NAME] [--tags tag:a,tag:b] [--no-install]" >&2
  exit 2
}

refuse() {
  echo "aap-private-access: refused: $1" >&2
  exit 2
}

cleanup() {
  if [ -n "$KEY_TMP" ]; then
    rm -f "$KEY_TMP"
  fi
  KEY=""
}
trap cleanup EXIT

# Any text with the key replaced; used for everything the client prints.
redact() {
  local text="$1"
  if [ -n "$KEY" ]; then
    text="${text//"$KEY"/[redacted]}"
  fi
  printf '%s' "$text"
}

# ── options ──────────────────────────────────────────────────────────────────

# A flag that would widen what the node does, with the reason it is refused.
refused_reason() {
  case "$1" in
    --exit-node | --exit-node-allow-lan-access) echo "an exit node would send this host's traffic through another device" ;;
    --advertise-exit-node) echo "an exit node would let tailnet devices leave through this host" ;;
    --advertise-routes) echo "advertised routes would expose this host's networks, customer networks included" ;;
    --accept-routes) echo "accepted routes would change the routing Docker builds on" ;;
    --accept-dns) echo "the tailnet's DNS would replace the resolver Docker builds on" ;;
    --ssh) echo "Tailscale SSH would open a root shell path the panel does not control" ;;
    --funnel | --serve) echo "Serve and Funnel publish this host outside the panel's control" ;;
    --webclient) echo "the web client is a second management page on the tailnet" ;;
    --shields-up) echo "shields up blocks the panel itself" ;;
    --netfilter-mode) echo "the client's firewall mode is fixed so the egress guard sees what it expects" ;;
    --operator) echo "a non-root operator could change these settings" ;;
    --advertise-connector) echo "an app connector would route traffic for other devices" ;;
    --auth-key | --authkey) echo "a key on the command line is visible to every process in ps and lands in shell history; use --auth-key-file or --auth-key-stdin" ;;
    *) return 1 ;;
  esac
}

parse_options() {
  local arg name value reason
  while [ $# -gt 0 ]; do
    arg="$1"
    name="${arg%%=*}"
    value=""
    if [[ "$arg" == *=* ]]; then value="${arg#*=}"; fi
    if reason="$(refused_reason "$name")"; then
      # Never echo the value: it may be a key.
      refuse "${name}: ${reason}"
    fi
    case "$name" in
      --network | --login-server | --auth-key-file | --hostname | --tags)
        if [[ "$arg" != *=* ]]; then
          [ $# -ge 2 ] || refuse "${name} needs a value"
          value="$2"
          shift
        fi
        case "$name" in
          --network) OPT_NETWORK="$value" ;;
          --login-server) OPT_LOGIN_SERVER="$value"; OPT_LOGIN_SET=true ;;
          --auth-key-file) KEY_SOURCE="file"; KEY_FILE_ARG="$value" ;;
          --hostname) OPT_HOSTNAME="$value" ;;
          --tags) OPT_TAGS="$value" ;;
        esac
        ;;
      --auth-key-stdin) KEY_SOURCE=stdin ;;
      --no-install) NO_INSTALL=true ;;
      *) echo "aap-private-access: unknown option: ${name}" >&2; usage ;;
    esac
    shift
  done
}

valid_login_server() {
  local scheme='https'
  [ "${AAP_PRIVATE_ACCESS_ALLOW_HTTP_LOGIN_SERVER:-}" != 1 ] || scheme='https?'
  # Host, optional port and path; no user, query, fragment or spaces.
  [[ "$1" =~ ^${scheme}://[A-Za-z0-9]([A-Za-z0-9.-]{0,252})(:[0-9]{1,5})?(/[A-Za-z0-9._~/-]*)?$ ]]
}
valid_hostname() { [[ "$1" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$ ]]; }
valid_tags() { [[ "$1" =~ ^tag:[a-z0-9][a-z0-9-]{0,62}(,tag:[a-z0-9][a-z0-9-]{0,62}){0,7}$ ]]; }
# Tailscale keys are tskey-…, Headscale keys hskey-… or hex: letters, digits, - _.
valid_key() { [[ "$1" =~ ^[A-Za-z0-9_-]{16,255}$ ]]; }

conf_value() {
  [ -r "$CONF_FILE" ] || return 0
  grep "^$1=" "$CONF_FILE" | tail -1 | cut -d= -f2-
}

check_paths() {
  local p
  for p in "$STATUS_FILE" "$CONF_FILE" "$LOCK_FILE" "$KEY_DIR" "$EGRESS_GUARD" "$OS_RELEASE"; do
    case "$p" in /*) ;; *) refuse "override paths must be absolute: ${p}" ;; esac
  done
  case "$PKG_ROOT" in "" | /*) ;; *) refuse "AAP_PRIVATE_ACCESS_PKG_ROOT must be absolute" ;; esac
}

# Options over saved settings over defaults, each value checked again (the
# saved file could have been edited by hand).
resolve_settings() {
  [ -e "$CONF_FILE" ] && HAVE_CONF=true
  NETWORK="${OPT_NETWORK:-$(conf_value NETWORK)}"
  NETWORK="${NETWORK:-tailscale}"
  case "$NETWORK" in tailscale | headscale) ;; *) refuse "--network must be tailscale or headscale (NetBird comes in a later release)" ;; esac
  if [ "$OPT_LOGIN_SET" = true ]; then
    LOGIN_SERVER="$OPT_LOGIN_SERVER"
  elif [ -z "$OPT_NETWORK" ] || [ "$OPT_NETWORK" = "$(conf_value NETWORK)" ]; then
    LOGIN_SERVER="$(conf_value LOGIN_SERVER)"
  fi
  if [ "$NETWORK" = headscale ]; then
    [ -n "$LOGIN_SERVER" ] || refuse "Headscale needs --login-server https://your-headscale-server"
    valid_login_server "$LOGIN_SERVER" || refuse "--login-server must be https://host[:port][/path], without user, query or fragment"
  elif [ -n "$LOGIN_SERVER" ]; then
    refuse "--login-server is for Headscale; Tailscale uses its own control server"
  fi
  HOSTNAME_="${OPT_HOSTNAME:-$(conf_value HOSTNAME)}"
  HOSTNAME_="${HOSTNAME_:-$DEFAULT_HOSTNAME}"
  valid_hostname "$HOSTNAME_" || refuse "--hostname must be lower-case letters, digits and -, at most 63"
  TAGS="${OPT_TAGS:-$(conf_value TAGS)}"
  TAGS="${TAGS:-$DEFAULT_TAGS}"
  valid_tags "$TAGS" || refuse "--tags must be tag:name[,tag:name] (lower-case letters, digits and -)"
}

# Read the key into KEY and write it to KEY_TMP. A key file must be a regular
# file owned by this user with no group or other access; it is deleted after
# the join attempt (cmd_apply), so it is used once.
read_key() {
  local line mode owner
  case "$KEY_SOURCE" in
    "") return 0 ;;
    stdin) IFS= read -r line || [ -n "${line:-}" ] || refuse "no key on stdin" ;;
    file)
      case "$KEY_FILE_ARG" in /*) ;; *) refuse "--auth-key-file must be an absolute path" ;; esac
      if [ ! -f "$KEY_FILE_ARG" ] || [ -L "$KEY_FILE_ARG" ]; then
        refuse "--auth-key-file must be a regular file"
      fi
      mode="$(stat -c %a "$KEY_FILE_ARG")"
      owner="$(stat -c %u "$KEY_FILE_ARG")"
      [ "$owner" = "$(id -u)" ] || refuse "the key file must belong to $(id -un)"
      case "$mode" in 400 | 600) ;; *) refuse "the key file must have mode 0600 (it has ${mode}); chmod 600 it and run again" ;; esac
      IFS= read -r line <"$KEY_FILE_ARG" || [ -n "${line:-}" ] || refuse "the key file is empty"
      ;;
  esac
  line="${line%$'\r'}"
  valid_key "$line" || refuse "that is not a join key (expected letters, digits, - and _)"
  KEY="$line"
  (umask 077 && mkdir -p "$KEY_DIR") || { echo "aap-private-access: cannot create ${KEY_DIR}" >&2; exit 1; }
  chmod 700 "$KEY_DIR"
  KEY_TMP="$(umask 077 && mktemp "${KEY_DIR}/key.XXXXXX")" || { echo "aap-private-access: cannot write a temporary key file" >&2; exit 1; }
  printf '%s\n' "$KEY" >"$KEY_TMP"
}

# ── the client ───────────────────────────────────────────────────────────────

ts() { tailscale "$@"; }

client_installed() { command -v tailscale >/dev/null 2>&1 && command -v tailscaled >/dev/null 2>&1; }

os_value() {
  [ -r "$OS_RELEASE" ] || return 0
  grep "^$1=" "$OS_RELEASE" | tail -1 | cut -d= -f2- | tr -d '"'
}

# Prints "rhel <url>", "apt <dist> <codename>" or nothing (unsupported).
package_path() {
  local id like ver major codename
  id="$(os_value ID)"
  like="$(os_value ID_LIKE)"
  ver="$(os_value VERSION_ID)"
  major="${ver%%.*}"
  codename="$(os_value VERSION_CODENAME)"
  case "$id" in
    fedora) echo "rhel ${PKG_BASE}/fedora/tailscale.repo"; return 0 ;;
    rocky | almalinux | rhel | centos | ol)
      [[ "$major" =~ ^[0-9]+$ ]] && echo "rhel ${PKG_BASE}/rhel/${major}/tailscale.repo"
      return 0
      ;;
    ubuntu | debian)
      [[ "$codename" =~ ^[a-z]+$ ]] && echo "apt ${id} ${codename}"
      return 0
      ;;
  esac
  case " $like " in
    *" rhel "* | *" centos "*) [[ "$major" =~ ^[0-9]+$ ]] && echo "rhel ${PKG_BASE}/rhel/${major}/tailscale.repo" ;;
  esac
}

install_hint() {
  echo "install the Tailscale client from https://tailscale.com/download/linux, start tailscaled, then run this again"
}

# 0 installed, 1 failed, 3 no package path.
install_client() {
  local path kind a b
  path="$(package_path)"
  [ -n "$path" ] || return 3
  read -r kind a b <<<"$path"
  echo "installing the Tailscale client from ${PKG_BASE}"
  if [ "$kind" = rhel ]; then
    mkdir -p "${PKG_ROOT}/etc/yum.repos.d" &&
      curl -fsSL --proto =https "$a" -o "${PKG_ROOT}/etc/yum.repos.d/tailscale.repo" &&
      dnf install -y tailscale || return 1
  else
    mkdir -p "${PKG_ROOT}/usr/share/keyrings" "${PKG_ROOT}/etc/apt/sources.list.d" &&
      curl -fsSL --proto =https "${PKG_BASE}/${a}/${b}.noarmor.gpg" -o "${PKG_ROOT}/usr/share/keyrings/tailscale-archive-keyring.gpg" &&
      curl -fsSL --proto =https "${PKG_BASE}/${a}/${b}.tailscale-keyring.list" -o "${PKG_ROOT}/etc/apt/sources.list.d/tailscale.list" &&
      apt-get update -y &&
      apt-get install -y tailscale || return 1
  fi
  systemctl enable --now tailscaled || return 1
}

# The flags every run sets, so nothing turned on by hand lasts.
safe_set_flags() {
  printf '%s\n' --accept-dns=false --accept-routes=false --ssh=false --advertise-exit-node=false \
    --advertise-routes= --exit-node= --shields-up=false --webclient=false
}

# Headscale (checked with v0.29.7) takes a node's tags from its pre-auth key
# (headscale preauthkeys create --tags tag:aap-panel): --advertise-tags with a
# tagged key is refused ("requested tags … are invalid or not permitted") and
# with an untagged key it is ignored. So it is passed to Tailscale only; on
# both, the tag check after the join says whether the node carries the tags.
join_args() {
  local args=(up --reset)
  if [ "$NETWORK" = headscale ]; then
    args+=("--login-server=${LOGIN_SERVER}")
  else
    args+=("--advertise-tags=${TAGS}")
  fi
  args+=("--auth-key=file:${1}" "--hostname=${HOSTNAME_}"
    --accept-dns=false --accept-routes=false --ssh=false --advertise-exit-node=false
    --advertise-routes= --exit-node= --shields-up=false --timeout=90s)
  printf '%s\n' "${args[@]}"
}

# ── state, problems, status file ─────────────────────────────────────────────

ts_status() { ts status --json 2>/dev/null; }

backend_state() { "$JQ" -r '.BackendState // "unknown"' <<<"$1" 2>/dev/null || echo unknown; }

# Fills PROBLEMS from the client's answers.
collect_problems() {
  local st="$1" prefs serve url want tag tags
  PROBLEMS=()
  prefs="$(ts debug prefs 2>/dev/null)" || { PROBLEMS+=("the client did not report its settings"); return; }
  serve="$(ts serve status --json 2>/dev/null)" || serve='{}'
  [ "$("$JQ" -r '.RouteAll' <<<"$prefs")" != true ] || PROBLEMS+=("accepts routes from the tailnet")
  [ "$("$JQ" -r '.CorpDNS' <<<"$prefs")" != true ] || PROBLEMS+=("accepts the tailnet's DNS")
  [ "$("$JQ" -r '.RunSSH' <<<"$prefs")" != true ] || PROBLEMS+=("Tailscale SSH is on")
  [ "$("$JQ" -r '.RunWebClient' <<<"$prefs")" != true ] || PROBLEMS+=("the web client is on")
  [ "$("$JQ" -r '.ShieldsUp' <<<"$prefs")" != true ] || PROBLEMS+=("shields up blocks the panel")
  [ -z "$("$JQ" -r '.ExitNodeID // ""' <<<"$prefs")" ] || PROBLEMS+=("uses an exit node")
  [ "$("$JQ" -r '(.AdvertiseRoutes // []) | length' <<<"$prefs")" = 0 ] || PROBLEMS+=("advertises routes or an exit node")
  [ "$("$JQ" -r '.AppConnector.Advertise // false' <<<"$prefs")" != true ] || PROBLEMS+=("advertises an app connector")
  [ "$("$JQ" -r 'if type == "object" then length else 0 end' <<<"$serve")" = 0 ] || PROBLEMS+=("Serve or Funnel is configured")
  if [ "$NETWORK" = headscale ]; then
    url="$("$JQ" -r '.ControlURL // ""' <<<"$prefs")"
    [ "$url" = "$LOGIN_SERVER" ] || PROBLEMS+=("the client uses login server $(printf '%s' "$url" | tr -cd 'A-Za-z0-9.:/_-'), not ${LOGIN_SERVER}")
  fi
  [ "$("$JQ" -r '.TUN' <<<"$st")" = true ] || PROBLEMS+=("the client runs in userspace networking: there is no ${TS_INTERFACE} for the anti-spoof rule")
  tags="$("$JQ" -r '(.Self.Tags // []) | join(",")' <<<"$st")"
  for want in ${TAGS//,/ }; do
    tag=",${tags},"
    [[ "$tag" == *",${want},"* ]] || PROBLEMS+=("the node is not tagged ${want}: use a key that carries the tag, and let your admins own it in tagOwners")
  done
}

# Written to a fresh temporary name and renamed over the target, as the egress
# guard does: update/ is shared with the panel container.
write_status() {
  local status="$1" reason="$2" st="${3:-}" dir tmp problems
  dir="$(dirname "$STATUS_FILE")"
  [ -d "$dir" ] || { echo "aap-private-access: ${dir} does not exist; status file not written" >&2; return 0; }
  [ -n "$JQ" ] || return 0
  [ -n "$st" ] || st='{}'
  problems="$(printf '%s\n' "${PROBLEMS[@]}" | "$JQ" -R . | "$JQ" -s 'map(select(length > 0))')"
  tmp="$(mktemp "${dir}/.private-access.XXXXXX")" || return 1
  # A jq program, not a shell expansion.
  # shellcheck disable=SC2016
  "$JQ" -n --arg status "$status" --arg reason "$(redact "$reason")" \
    --arg checked_at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    --arg network "$NETWORK" --arg login_server "$LOGIN_SERVER" \
    --arg interface "$TS_INTERFACE" --arg guard "$GUARD_RESULT" \
    --argjson st "$st" --argjson problems "$problems" '
    {status: $status, checked_at: $checked_at, reason: $reason,
     network: $network, login_server: $login_server,
     node_name: ($st.Self.HostName // ""),
     tailnet_ipv4: ((($st.Self.TailscaleIPs // []) | map(select(test("^[0-9.]+$"))) | first) // ""),
     interface: (if $st.TUN == true then $interface else "" end),
     tags: ($st.Self.Tags // []),
     client_version: ($st.Version // ""),
     backend_state: ($st.BackendState // ""),
     egress_guard: $guard,
     problems: $problems}' >"$tmp" || { rm -f "$tmp"; return 1; }
  chmod 644 "$tmp"
  mv -f "$tmp" "$STATUS_FILE"
}

save_settings() {
  local dir tmp
  dir="$(dirname "$CONF_FILE")"
  mkdir -p "$dir" || return 1
  tmp="$(mktemp "${dir}/.private-access.XXXXXX")" || return 1
  printf 'NETWORK=%s\nLOGIN_SERVER=%s\nHOSTNAME=%s\nTAGS=%s\nINTERFACE=%s\n' \
    "$NETWORK" "$LOGIN_SERVER" "$HOSTNAME_" "$TAGS" "$TS_INTERFACE" >"$tmp"
  chmod 644 "$tmp"
  mv -f "$tmp" "$CONF_FILE"
}

run_guard() {
  local rc=0 out
  if [ ! -x "$EGRESS_GUARD" ]; then
    GUARD_RESULT="missing: ${EGRESS_GUARD}"
    return 1
  fi
  out="$("$EGRESS_GUARD" apply 2>&1)" || rc=$?
  [ -z "$out" ] || printf '%s\n' "$out" | sed 's/^/  egress guard: /'
  if [ "$rc" -eq 0 ]; then
    GUARD_RESULT=active
    return 0
  fi
  GUARD_RESULT="not active (exit ${rc}); see ${EGRESS_GUARD} status"
  return 1
}

join_problems() {
  local out="" p
  for p in "${PROBLEMS[@]}"; do
    out="${out:+${out}; }${p}"
  done
  printf '%s' "$out"
}

take_lock() {
  local tries=30
  command -v flock >/dev/null 2>&1 || return 0
  exec 9>"$LOCK_FILE" || return 1
  until flock -n 9; do
    tries=$((tries - 1))
    [ "$tries" -gt 0 ] || return 1
    sleep 1
  done
}

find_jq() {
  JQ="$(command -v jq 2>/dev/null)" || JQ=""
  [ -n "$JQ" ] || [ ! -x /usr/local/bin/jq ] || JQ=/usr/local/bin/jq
}

fail() {
  echo "aap-private-access: failed: $(redact "$1")" >&2
  write_status failed "$1" "${2:-}"
  exit 1
}

# ── commands ─────────────────────────────────────────────────────────────────

cmd_plan() {
  local path
  echo "# network: ${NETWORK}${LOGIN_SERVER:+ (login server ${LOGIN_SERVER})}, node ${HOSTNAME_}, tags ${TAGS}"
  if ! client_installed; then
    path="$(package_path)"
    if [ -z "$path" ]; then
      echo "# the client is not installed and this system has no package path: $(install_hint)"
    elif [[ "$path" == rhel* ]]; then
      echo "# install: ${path#rhel } -> ${PKG_ROOT}/etc/yum.repos.d/tailscale.repo; dnf install -y tailscale; systemctl enable --now tailscaled"
    else
      read -r _ a b <<<"$path"
      echo "# install: ${PKG_BASE}/${a}/${b}.noarmor.gpg and ${PKG_BASE}/${a}/${b}.tailscale-keyring.list; apt-get install -y tailscale; systemctl enable --now tailscaled"
    fi
  fi
  echo "# with a one-time key (--auth-key-file or --auth-key-stdin):"
  echo "tailscale $(join_args '<one-time key file>' | tr '\n' ' ')"
  echo "# every run:"
  echo "tailscale set $(safe_set_flags | tr '\n' ' ')"
  echo "tailscale serve reset"
  echo "# save ${CONF_FILE} (INTERFACE=${TS_INTERFACE}), then: ${EGRESS_GUARD} apply; systemctl enable --now ${TIMER}"
}

cmd_apply() {
  local rc=0 out st state
  take_lock || { echo "aap-private-access: another run holds ${LOCK_FILE}" >&2; exit 1; }
  find_jq
  # Nothing set up and nothing asked: the timer has nothing to do.
  if [ "$HAVE_CONF" = false ] && [ -z "$KEY_SOURCE" ]; then
    write_status off "private access is not set up"
    echo "off: private access is not set up"
    return 0
  fi
  read_key
  # The source file is used once, whatever happens next.
  [ "$KEY_SOURCE" != file ] || rm -f "$KEY_FILE_ARG"
  [ -n "$JQ" ] || fail "jq is missing (the installer puts it in /usr/local/bin)"
  if ! client_installed; then
    [ "$NO_INSTALL" = false ] || fail "the Tailscale client is not installed (--no-install): $(install_hint)"
    install_client || rc=$?
    if [ "$rc" -eq 3 ]; then
      write_status unsupported "no package path for this system: $(install_hint)"
      echo "unsupported: no package path for this system: $(install_hint)" >&2
      exit 3
    fi
    [ "$rc" -eq 0 ] || fail "installing the Tailscale client failed"
    client_installed || fail "the Tailscale client is still not installed after the package install"
  fi
  if [ -n "$KEY" ]; then
    local args=()
    mapfile -t args < <(join_args "$KEY_TMP")
    out="$(ts "${args[@]}" 2>&1)" || rc=$?
    [ -z "$out" ] || { redact "$out"; echo; } | sed 's/^/  tailscale: /'
    rm -f "$KEY_TMP"
    [ "$rc" -eq 0 ] || fail "the join failed (exit ${rc}); see the client's message above. The key was used; ask for a new one if it was a one-off key"
  fi
  st="$(ts_status)" || fail "the client did not answer (is tailscaled running?)"
  state="$(backend_state "$st")"
  if [ "$state" != Running ]; then
    write_status disconnected "the node is not logged in (${state}); run apply again with a new one-time join key" "$st"
    echo "disconnected: the node is not logged in (${state}); run apply again with a new one-time join key" >&2
    exit 1
  fi
  local flags=()
  mapfile -t flags < <(safe_set_flags)
  ts set "${flags[@]}" >/dev/null 2>&1 || PROBLEMS+=("tailscale set failed")
  ts serve reset >/dev/null 2>&1 || true
  save_settings || fail "could not write ${CONF_FILE}" "$st"
  run_guard || true
  if command -v systemctl >/dev/null 2>&1; then
    systemctl enable --now "$TIMER" >/dev/null 2>&1 || echo "aap-private-access: could not enable ${TIMER}" >&2
  fi
  st="$(ts_status)" || st='{}'
  local set_failed=("${PROBLEMS[@]}")
  collect_problems "$st"
  PROBLEMS+=("${set_failed[@]}")
  [ "$GUARD_RESULT" = active ] || PROBLEMS+=("the egress guard is ${GUARD_RESULT}")
  if [ "${#PROBLEMS[@]}" -gt 0 ]; then
    fail "$(join_problems)" "$st"
  fi
  write_status connected "" "$st"
  echo "connected: $("$JQ" -r '.Self.HostName + " " + ((.Self.TailscaleIPs // []) | map(select(test("^[0-9.]+$"))) | first // "")' <<<"$st")"
}

cmd_status() {
  local st state
  find_jq
  if [ "$HAVE_CONF" = false ]; then
    echo off
    return 0
  fi
  [ -n "$JQ" ] || { echo "not connected: jq is missing"; exit 1; }
  client_installed || { echo "not connected: the Tailscale client is not installed"; exit 1; }
  st="$(ts_status)" || { echo "not connected: the client did not answer"; exit 1; }
  state="$(backend_state "$st")"
  [ "$state" = Running ] || { echo "not connected: ${state}"; exit 1; }
  collect_problems "$st"
  if [ "${#PROBLEMS[@]}" -gt 0 ]; then
    echo "not connected: $(join_problems)"
    exit 1
  fi
  echo "connected: $("$JQ" -r '.Self.HostName + " " + ((.Self.TailscaleIPs // []) | map(select(test("^[0-9.]+$"))) | first // "")' <<<"$st")"
}

cmd_remove() {
  take_lock || { echo "aap-private-access: another run holds ${LOCK_FILE}" >&2; exit 1; }
  find_jq
  if client_installed; then
    ts logout >/dev/null 2>&1 || echo "aap-private-access: logout failed; delete the node in your tailnet's admin console" >&2
  fi
  if command -v systemctl >/dev/null 2>&1; then
    systemctl disable --now "$TIMER" >/dev/null 2>&1 || true
    systemctl disable --now tailscaled >/dev/null 2>&1 || true
  fi
  rm -f "$CONF_FILE" || fail "could not delete ${CONF_FILE}"
  run_guard || echo "aap-private-access: the egress guard did not apply; run ${EGRESS_GUARD} apply" >&2
  write_status off "removed by aap-private-access.sh remove"
  echo "removed. Also delete the node in your tailnet's admin console (Headscale: headscale nodes delete). The tailscale package stays installed."
}

[ $# -ge 1 ] || usage
CMD="$1"
shift
case "$CMD" in
  plan | apply | status | remove) ;;
  *) usage ;;
esac
check_paths
parse_options "$@"
case "$CMD" in
  status | remove) [ -z "$KEY_SOURCE" ] || refuse "a key is only used by apply" ;;
esac
resolve_settings
[ "$CMD" = apply ] || [ "$CMD" = plan ] || [ -z "$OPT_NETWORK$OPT_HOSTNAME$OPT_TAGS" ] || refuse "options are for plan and apply"
[ "$CMD" != plan ] || [ -z "$KEY_SOURCE" ] || refuse "plan does not use a key"
"cmd_${CMD}"
AAP_EMBED_PRIVATE_ACCESS_EOF
}
_aap_embed_private_access_service() {
  cat <<'AAP_EMBED_PRIVATE_ACCESS_SERVICE_EOF'
[Unit]
Description=AI Admin Panel — private access: keep the tailnet node's safe settings and refresh its status (oneshot)
Documentation=https://docs.aiadminpanel.com/getting-started/private-access
After=tailscaled.service docker.service
Wants=tailscaled.service

[Service]
Type=oneshot
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Runs as root (AI-2194). Without a key it never joins: it turns off again
# anything that widens what the node does (routes, DNS, SSH, exit node, Serve,
# Funnel, the web client), re-runs the egress guard and writes
# update/private-access.json for the panel. Nothing is set up until an
# operator runs `aap-private-access.sh apply` with a one-time key.
ExecStart=/opt/aiadminpanel/aap-private-access.sh apply
AAP_EMBED_PRIVATE_ACCESS_SERVICE_EOF
}
_aap_embed_private_access_timer() {
  cat <<'AAP_EMBED_PRIVATE_ACCESS_TIMER_EOF'
[Unit]
Description=AI Admin Panel — re-check private access every 5 minutes
Documentation=https://docs.aiadminpanel.com/getting-started/private-access

[Timer]
# Enabled by aap-private-access.sh apply after a join and disabled by its
# remove; the installer only writes this file. OnCalendar for the reason
# aap-egress-guard.timer gives.
OnBootSec=45s
OnCalendar=*:2/5
Persistent=true
AccuracySec=30s

[Install]
WantedBy=timers.target
AAP_EMBED_PRIVATE_ACCESS_TIMER_EOF
}
_aap_embed_close_legacy() {
  cat <<'AAP_EMBED_CLOSE_LEGACY_EOF'
#!/usr/bin/env bash
# close-legacy-secret-format.sh — close the old encryption format for one kind
# of stored secret, now, instead of waiting for the next update (AI-1345).
#
# Usage (root, on the panel host):
#   /opt/aiadminpanel/close-legacy-secret-format.sh <purpose>
#   e.g. close-legacy-secret-format.sh setting
#
# Why: until a kind of secret ("purpose") is closed, the panel still opens
# values written in the old format, and a value planted in the database by
# someone who can write one row still opens there. Closing makes the panel
# refuse the old format for that purpose from its next start.
#
# What it does: asks the running panel whether every stored value of that
# purpose is in the new format; only then appends the purpose to
# secrets/legacy_closed (one per line, root-owned) and recreates the panel,
# which reads the file only at start. aap-update.sh does the same automatically
# after every healthy update; this script is for closing earlier.
#
# It only ever adds a line. To undo a close (needed after restoring a database
# dump with old-format values), remove the line as root and restart the panel;
# see the docs page "Secrets Manager", section "How the panel stores secrets".
set -uo pipefail

PANEL_DIR="${PANEL_DIR:-/opt/aiadminpanel}"
COMPOSE_FILE="${COMPOSE_FILE:-${PANEL_DIR}/docker-compose.yml}"
PANEL_CONTAINER="${PANEL_CONTAINER:-aiadminpanel_panel}"
MARKER="${PANEL_DIR}/secrets/legacy_closed"
WORK_DIR="${PANEL_DIR}/.update-work"
LOCK_FILE="${WORK_DIR}/lock"
LOCK_WAIT="${LOCK_WAIT:-600}"

die() { echo "close-legacy-secret-format: $*" >&2; exit 1; }

[ "$#" -eq 1 ] || { echo "usage: close-legacy-secret-format.sh <purpose>" >&2; exit 2; }
purpose="$1"
[[ "$purpose" =~ ^[a-z0-9][a-z0-9-]*$ ]] || die "'${purpose}' is not a purpose name (lowercase letters, digits and dashes)"

[ -f "$MARKER" ] || die "${MARKER} is missing; create it empty with \"install -m 600 /dev/null ${MARKER}\" and start the panel first"
grep -qF -- "secrets/legacy_closed" "$COMPOSE_FILE" 2>/dev/null \
  || die "the installed compose file does not give the panel ${MARKER}; update the panel first"

# One writer at a time: the host updater takes the same lock.
if [ -L "$WORK_DIR" ] || ! mkdir -p "$WORK_DIR" || ! chmod 700 "$WORK_DIR"; then
  die "cannot use the updater's work area ${WORK_DIR}"
fi
exec 9>"$LOCK_FILE"
waited=0
until flock -n 9; do
  [ "$waited" -lt "$LOCK_WAIT" ] || die "an update or backup is still running; try again later"
  sleep 1
  waited=$((waited + 1))
done

if grep -qxF -- "$purpose" "$MARKER"; then
  echo "${purpose} is already closed; nothing changed"
  exit 0
fi

ready="$(timeout 120 docker exec "$PANEL_CONTAINER" panel secrets reencrypt --status --ready 2>/dev/null)" \
  || die "the panel did not answer which kinds of secret are ready; nothing changed"
grep -qxF -- "$purpose" <<<"$ready" \
  || die "the panel does not report ${purpose} ready: values in the old format remain, or the last conversion pass had failures; nothing changed"

{ [ ! -s "$MARKER" ] || [ -z "$(tail -c1 "$MARKER")" ] || echo >> "$MARKER"; } || die "could not write ${MARKER}"
printf '%s\n' "$purpose" >> "$MARKER" || die "could not write ${MARKER}"
echo "closed the old format for ${purpose} in ${MARKER}"

compose_args=(--project-directory "$PANEL_DIR" -f "$COMPOSE_FILE")
[ -f "${PANEL_DIR}/docker-compose.gpu.yml" ] && compose_args+=(-f "${PANEL_DIR}/docker-compose.gpu.yml")
docker compose "${compose_args[@]}" up -d --no-deps --force-recreate panel >/dev/null 2>&1 \
  || die "${purpose} is closed in ${MARKER}, but recreating the panel failed; run \"docker compose up -d --no-deps --force-recreate panel\" in ${PANEL_DIR}"
echo "the panel was recreated and refuses the old format for ${purpose} from now on"
AAP_EMBED_CLOSE_LEGACY_EOF
}

# ── The updater's lock (AI-1471) ──────────────────────────────────────────────
# The same file, the same folder checks and the same retry loop as
# aap-update.sh and backup-databases.sh. --refresh-updater holds it while it
# writes the updater, so it never swaps the script under a running update or
# the nightly backup. The lock is on fd 9 and is released by closing it.
acquire_updater_lock() {
  local work_dir="${PANEL_DIR}/.update-work"
  local lock="${work_dir}/lock" wait="${REFRESH_LOCK_WAIT:-600}" waited=0
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "wait up to ${wait}s for the updater lock ${lock} (an update or the nightly backup holds it while it runs)"
    return 0
  fi
  if [ -L "$work_dir" ] || ! mkdir -p "$work_dir" || ! chmod 700 "$work_dir"; then
    error "Cannot use the updater's work area ${work_dir}; nothing was changed."
  fi
  exec 9>"$lock"
  # A retry loop, not `flock -w`: BusyBox flock has no -w.
  until flock -n 9; do
    if [ "$waited" -eq 0 ]; then
      info "An update or the nightly backup is running; waiting for it to finish (up to ${wait}s)..."
    fi
    if [ "$waited" -ge "$wait" ]; then
      exec 9>&-
      error "The updater lock ${lock} is still taken after ${wait}s; nothing was changed. Run this again once the update or backup has finished."
    fi
    sleep 1
    waited=$((waited + 1))
  done
}

release_updater_lock() {
  [ "$DRY_RUN" = "true" ] || exec 9>&-
}

# Private access (AI-2194): the host script that puts this server on the
# operator's own Tailscale or Headscale network, and its units. Only written:
# nothing joins and no timer runs until the operator runs
# `aap-private-access.sh apply` with a one-time key (docs: private-access). The
# egress guard reads its saved settings for the anti-spoof rule.
install_private_access_files() {
  local script_dest="${PANEL_DIR}/aap-private-access.sh"
  # SYSTEMD_UNIT_DIR exists for tests (a temporary root); hosts use the default.
  local unit_dir="${SYSTEMD_UNIT_DIR:-/etc/systemd/system}"
  local service_unit="${unit_dir}/aap-private-access.service"
  local timer_unit="${unit_dir}/aap-private-access.timer"
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "write ${script_dest} (755) + ${service_unit} + ${timer_unit}; systemctl daemon-reload (nothing enabled)"
    return 0
  fi
  command -v systemctl >/dev/null 2>&1 || return 0
  _write_if_changed "$script_dest"  "$(_aap_embed_private_access)"         755
  _write_if_changed "$service_unit" "$(_aap_embed_private_access_service)" 644
  _write_if_changed "$timer_unit"   "$(_aap_embed_private_access_timer)"   644
  systemctl daemon-reload >/dev/null 2>&1 || true
  info "Private access is available but off: sudo ${script_dest} plan shows how to put this server on your own Tailscale or Headscale network."
}

# --refresh-updater: the host files only. The updater is written under its
# lock; the egress guard after it, so a running update waits no longer than it
# must.
refresh_host_files() {
  acquire_updater_lock
  install_host_updater
  release_updater_lock
  install_egress_guard
  install_private_access_files
  docker_address_pools_hint
  info "Host updater and container egress guard refreshed. The panel, its configuration and its containers were not changed."
}

# ── Install plan: bake and first boot (AI-2328, unit U1) ─────────────────────
# A cloud image (AWS AMI, built once) must hold the machine setup but nothing
# that differs per server: a snapshot taken after a full install would give
# every buyer the same passwords, vault key and setup code. So every step of the
# install belongs to one phase:
#   bake        sets the machine up (packages, Docker, firewall, host files).
#               The same on every server; creates no secret and no identity.
#   first-boot  gives this one server its identity: domain, licence, secrets,
#               .env, setup code, the stack and its databases, the admin.
#   both        cheap read-only checks that each phase runs for itself.
# The table is docs/specs/2026-11-installer-bake-first-boot.md section 2.1.
#
# A normal install (no phase) runs the whole plan in the order below, which is
# exactly the order of every release before this table existed: the two phases
# interleave (setup_secrets runs before generate_config, for example), and
# changing that order is a behaviour change for later units, not this one.
# tests/installer/install_phases.bats holds main()'s recorded trace from before
# the table (fixtures/install_phases/) and fails on any difference.
#
# phase_bake and phase_first_boot run one phase each, in the same relative
# order, and set INSTALL_PHASE for the steps that span both. --bake (bake_main
# below: refusals, image pre-pull, bake marker; AI-2745, unit U3) runs
# phase_bake; --first-boot (with its instance binding) is unit U4. Split steps:
# create_directories leaves secrets/ out of a bake, install_host_updater writes
# the backup files in a bake but turns its timer on only outside one, and
# install_egress_guard (applying it needs the stack) stays first-boot.
#
# Each install_step_* function prints one progress line (`step`); TOTAL_STEPS
# in main() counts them (tests/installer/step_count.bats). Plan rows without a
# step function are calls that belong to the step above them.
# @AAP_INSTALL_PLAN_BEGIN@
install_step_platform() {
  step "Detecting platform..."
  detect_and_gate_platform
}

# AI-2319: before the domain prompt, which can claim a temporary domain over
# the network, and before any package install. A DNS server that answers
# nothing otherwise surfaces as dnf's "Could not resolve host" much later.
install_step_dns() {
  step "Checking DNS resolution..."
  if [ "$DRY_RUN" = "true" ]; then
    check_resolver || warn "DNS check reported a problem (non-fatal in dry-run)."
  else
    check_resolver || exit $?
  fi
}

install_step_prompt() {
  step "Prompting for configuration..."
  prompt_domain
  prompt_license
}

install_step_preflight() {
  step "Running pre-flight checks..."
  if [ "$DRY_RUN" = "true" ]; then
    preflight_checks || warn "Pre-flight reported issues (non-fatal in dry-run)."
  else
    preflight_checks || exit $?
  fi
}

# AI-2330: early, before anything stateful, so the reboot (20) and Secure
# Boot (21) stops after a driver install happen before the box has changed.
# In dry-run the step only narrates and never stops the run.
install_step_gpu_driver() {
  step "Checking the graphics card (GPU) and its driver..."
  wait_for_apt_lock || exit $?
  if [ "$DRY_RUN" = "true" ]; then
    gpu_driver_step || warn "The GPU driver step reported a problem (non-fatal in dry-run)."
  else
    gpu_driver_step || exit $?
  fi
}

install_step_directories() {
  step "Creating directories..."
  create_directories
}

# AI-2199: before Docker, so Docker finds firewalld running when it starts
# and creates its docker zone and forwarding policy.
install_step_host_firewall() {
  step "Turning on a host firewall (only if none is running)..."
  wait_for_apt_lock || exit $?
  ensure_host_firewall
}

install_step_docker() {
  step "Installing Docker..."
  wait_for_apt_lock || exit $?
  install_docker
  configure_docker_daemon
}

install_step_gpu_toolkit() {
  step "Configuring GPU support (NVIDIA Container Toolkit, if a GPU is present)..."
  wait_for_apt_lock || exit $?
  install_nvidia_container_toolkit
}

install_step_secrets() {
  step "Generating secrets..."
  setup_secrets
}

install_step_config() {
  step "Generating configuration..."
  generate_config
}

install_step_litellm_config() {
  step "Writing LiteLLM proxy config..."
  setup_litellm_config
}

install_step_env_file() {
  step "Generating environment file..."
  generate_env_file
  ensure_setup_token
  # AI-428: on a GPU host, write the compose overlay that gives the bundled
  # Ollama the host GPU (deploy_stack merges it). No-op / stale-cleanup on CPU.
  generate_ollama_gpu_override
}

install_step_infra() {
  step "Starting infrastructure (PostgreSQL, Valkey, Traefik)..."
  deploy_infra
}

install_step_keycloak() {
  step "Setting up Keycloak..."
  setup_keycloak
}

install_step_litellm_db() {
  step "Setting up LiteLLM database..."
  setup_litellm_db
}

install_step_stack() {
  step "Deploying full stack..."
  deploy_stack
}

install_step_host_updater() {
  step "Installing host updater (one-click updates)..."
  install_host_updater
}

# AI-1184: the admin account exists before the firewall opens. (Docker
# publishes 80/443 itself, so this narrows the window on firewalled hosts;
# the setup code is what closes it.)
install_step_keycloak_ready() {
  step "Waiting for Keycloak readiness..."
  wait_for_keycloak
}

install_step_admin() {
  step "Creating admin user..."
  create_keycloak_admin
}

install_step_river() {
  step "Creating River queue tables..."
  create_river_tables
}

install_step_panel_ready() {
  step "Waiting for panel readiness..."
  wait_for_ready
  ensure_panel_admin_row
}

install_step_openbao_key() {
  step "Protecting the OpenBao unseal key at rest..."
  protect_openbao_key
}

install_step_open_ports() {
  step "Opening host firewall for ports 80/443..."
  open_firewall_ports
}

# After the ports are opened: a firewalld reload there could drop the guard's
# rules for up to five minutes, until the timer puts them back. The private
# access files, the security baselines and the smoke tests that follow it in
# the plan are part of this step's progress line.
install_step_egress_guard() {
  step "Installing the container egress guard (host firewall)..."
  install_egress_guard
}

install_step_model_pull() {
  step "Pulling the bundled metered-AI model into Ollama (one-time)..."
  pull_metered_model
}

# AI-2745: the two steps only --bake runs, after the bake rows of the plan. They
# are not plan rows: a normal install pulls its images in deploy_stack and
# writes no bake marker (spec 2.4).
bake_step_images() {
  step "Downloading the Compose file and pulling every image it names..."
  deploy_stack_download_compose
  bake_pull_images
}

bake_step_marker() {
  step "Writing the bake marker ${CONFIG_DIR}/baked.json..."
  write_bake_marker
}

# AI-2747: what the first boot of each server made from the image runs.
bake_step_first_boot_files() {
  step "Installing the first-boot files..."
  install_first_boot_files
}
BAKE_ONLY_STEPS=(bake_step_images bake_step_marker bake_step_first_boot_files)

# AI-2747: the step only --first-boot runs, after the first-boot rows of the
# plan. Not a plan row: a normal install turns the backup timer on inside
# install_host_updater, a bake row that writes the files (spec 2.1, 2.4).
first_boot_step_backups() {
  step "Turning on the nightly backup..."
  install_host_backup
}
FIRST_BOOT_ONLY_STEPS=(first_boot_step_backups)

# "<phase>:<function>", run top to bottom.
INSTALL_PLAN=(
  both:install_step_platform
  both:install_step_dns
  first-boot:install_step_prompt
  both:install_step_preflight
  bake:install_step_gpu_driver
  bake:install_step_directories
  bake:install_step_host_firewall
  bake:install_step_docker
  bake:install_step_gpu_toolkit
  first-boot:install_step_secrets
  bake:install_step_config
  first-boot:install_step_litellm_config
  first-boot:install_step_env_file
  first-boot:install_step_infra
  first-boot:install_step_keycloak
  first-boot:install_step_litellm_db
  first-boot:install_step_stack
  bake:install_step_host_updater
  first-boot:install_step_keycloak_ready
  first-boot:install_step_admin
  first-boot:install_step_river
  first-boot:install_step_panel_ready
  first-boot:install_step_openbao_key
  first-boot:install_step_open_ports
  first-boot:install_step_egress_guard
  bake:install_private_access_files
  bake:run_security_baselines
  # AI-2776: fail2ban, sshd drop-in, security updates (lib/hardening.sh). First
  # boot, not bake: key-only SSH depends on this server's authorized keys,
  # which cloud-init puts in place at the first boot.
  first-boot:hardening_apply
  first-boot:smoke_tests
  first-boot:install_step_model_pull
)
# @AAP_INSTALL_PLAN_END@

# run_install_plan all|bake|first-boot: run the plan rows of that phase (all
# runs every row), in plan order. A failing row stops the installer exactly
# as the same call did in main() before the plan (set -e, or the row's own
# exit). An unknown phase or tag is a bug in this file, not a user error.
run_install_plan() {
  local want="$1" row tag fn
  case "$want" in
    all | bake | first-boot) ;;
    *) echo "run_install_plan: unknown phase '${want}'" >&2; exit 2 ;;
  esac
  for row in "${INSTALL_PLAN[@]}"; do
    tag="${row%%:*}"
    fn="${row#*:}"
    case "$tag" in
      bake | first-boot | both) ;;
      *) echo "run_install_plan: plan row '${row}' has no phase" >&2; exit 2 ;;
    esac
    if [ "$want" = "all" ] || [ "$tag" = "both" ] || [ "$tag" = "$want" ]; then
      "$fn"
    fi
  done
}

phase_bake() { INSTALL_PHASE=bake; run_install_plan bake; }
phase_first_boot() { INSTALL_PHASE=first-boot; run_install_plan first-boot; }

# ── install.sh --bake (AI-2745, spec 2.2) ────────────────────────────────────
# Run by Packer (once per AWS image) and by the Vultr wrapper (on each new
# server). The result may be snapshotted and given to many buyers, so the bake
# refuses any input or state that belongs to one server, and creates none.

# Placeholders for the Compose variables that must be set (:?) before
# `docker compose config` parses the file. They live in the environment of that
# one command only, never in a file, and are not secrets.
BAKE_COMPOSE_PLACEHOLDER_ENV=(
  LITELLM_MASTER_KEY=bake-placeholder-not-a-key
  LITELLM_DATABASE_URL=postgresql://bake-placeholder@localhost/bake-placeholder
)
# Filled by bake_pull_images: "<image as Compose names it> <digest>" per line.
BAKE_IMAGE_DIGESTS=""

# bake_names_matching <list> → the names in <list> (one per line) of panel
# volumes or containers: aiadminpanel_* or *_postgres_data (spec 1.4 item 28).
bake_names_matching() {
  local name
  while IFS= read -r name; do
    case "$name" in aiadminpanel_* | *_postgres_data) printf '%s\n' "$name" ;; esac
  done <<<"$1"
}

# bake_refuse_if_configured → 0 when this server may be baked. Otherwise it
# names every reason and returns 2; it changes nothing either way.
bake_refuse_if_configured() {
  local reasons=() var found out
  for var in PANEL_DOMAIN ADMIN_PASSWORD SETUP_TOKEN LICENSE_KEY; do
    [ -z "${!var:-}" ] || reasons+=("${var} is set. A cloud image must not carry one server's ${var}: unset it; the first boot sets it per server.")
  done
  [ ! -e "$SECRETS_DIR" ] || reasons+=("${SECRETS_DIR} exists: this server already has an install.")
  [ ! -e "${PANEL_DIR}/.env" ] || reasons+=("${PANEL_DIR}/.env exists: this server already has an install.")
  if command -v docker >/dev/null 2>&1; then
    if ! out="$(docker volume ls -q 2>/dev/null)"; then
      reasons+=("Docker is installed but does not answer, so its volumes cannot be checked. Start it (systemctl start docker) and run the bake again.")
    else
      found="$(bake_names_matching "$out")"
      [ -z "$found" ] || reasons+=("Docker volumes of an install exist: $(printf '%s' "$found" | tr '\n' ' ')")
      if out="$(docker ps -a --format '{{.Names}}' 2>/dev/null)"; then
        found="$(bake_names_matching "$out")"
        [ -z "$found" ] || reasons+=("Containers of an install exist: $(printf '%s' "$found" | tr '\n' ' ')")
      else
        reasons+=("Docker does not list its containers, so they cannot be checked. Run the bake again once docker ps -a works.")
      fi
    fi
  fi
  [ "${#reasons[@]}" -gt 0 ] || return 0
  local r
  for r in "${reasons[@]}"; do
    echo "--bake refused: ${r}" >&2
  done
  echo "--bake builds a cloud image and never runs on a configured server. Nothing was changed." >&2
  return 2
}

# bake_compose_images <compose file> → every image the file names, once each.
bake_compose_images() {
  env "${BAKE_COMPOSE_PLACEHOLDER_ENV[@]}" PANEL_VERSION="$PANEL_VERSION" \
    docker compose -f "$1" config --images | sort -u
}

# bake_image_digest <image> → the sha256 digest of the pulled <image>: the one
# the reference pins, or the registry digest Docker recorded for its tag.
bake_image_digest() {
  local image="$1" repo line
  case "$image" in *@sha256:*) printf '%s\n' "${image##*@}"; return 0 ;; esac
  repo="${image%@*}"
  case "${repo##*/}" in *:*) repo="${repo%:*}" ;; esac
  while IFS= read -r line; do
    if [ "${line%@*}" = "$repo" ] && [[ "${line##*@}" =~ ^sha256:[0-9a-f]{64}$ ]]; then
      printf '%s\n' "${line##*@}"
      return 0
    fi
  done < <(docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$image" 2>/dev/null)
  return 1
}

# bake_pull_images: pull every image of the downloaded Compose file, so the
# first boot starts the stack without a download, and record each digest.
bake_pull_images() {
  local compose_file="${PANEL_DIR}/docker-compose.yml" images image digest n=0
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "docker compose -f ${compose_file} config --images (placeholders in the environment only), then docker pull each image and record its digest"
    return 0
  fi
  images="$(bake_compose_images "$compose_file")" ||
    error "docker compose could not read the image list of ${compose_file}."
  [ -n "$images" ] || error "${compose_file} names no image."
  BAKE_IMAGE_DIGESTS=""
  while IFS= read -r image; do
    [[ "$image" =~ ^[A-Za-z0-9._/:@-]+$ ]] || error "Unexpected image reference in ${compose_file}: ${image}"
    info "Pulling ${image}..."
    run docker pull "$image" >/dev/null || error "Could not pull ${image}. Check the network and retry the bake."
    digest="$(bake_image_digest "$image")" || error "Docker recorded no registry digest for ${image}."
    BAKE_IMAGE_DIGESTS+="${image} ${digest}"$'\n'
    n=$((n + 1))
  done <<<"$images"
  info "Pulled ${n} images."
}

# write_bake_marker: /etc/aiadminpanel/baked.json, written by rename. Not a
# secret: the first boot reads it to skip downloads and to refuse a Compose
# file that changed after the bake.
write_bake_marker() {
  local marker="${CONFIG_DIR}/baked.json" compose_file="${PANEL_DIR}/docker-compose.yml"
  local channel="${AAP_INSTALL_SOURCE:-custom}" compose_sha baked_at images_json="" image digest
  [[ "$channel" =~ ^[a-z0-9][a-z0-9._-]*$ ]] || error "AAP_INSTALL_SOURCE must be a channel name such as aws-marketplace or vultr (got '${channel}')."
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "write ${marker} (644): version ${PANEL_VERSION}, the SHA-256 of ${compose_file}, each image's digest, channel ${channel}, the time"
    return 0
  fi
  compose_sha="$(sha256_hex <"$compose_file")" || error "Could not compute the SHA-256 of ${compose_file}."
  baked_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  while read -r image digest; do
    [ -n "$image" ] || continue
    images_json+="${images_json:+,}\"${image}\":\"${digest}\""
  done <<<"$BAKE_IMAGE_DIGESTS"
  [ -n "$images_json" ] || error "No image was pulled; refusing to write a bake marker without images."
  mkdir -p "$CONFIG_DIR"
  printf '{"version":"%s","compose_sha256":"%s","images":{%s},"channel":"%s","baked_at":"%s"}\n' \
    "$PANEL_VERSION" "$compose_sha" "$images_json" "$channel" "$baked_at" >"${marker}.tmp"
  chmod 644 "${marker}.tmp"
  mv -f "${marker}.tmp" "$marker"
  info "Bake marker written: ${marker}"
}

# install_self_copy <dest>: this installer, kept on the image for the first
# boot (install.sh --first-boot). The file this run was started from; for a
# piped run (curl | bash) the pinned release's own install.sh, checked against
# its SHA256SUMS. An unpinned piped run has neither and stops.
install_self_copy() {
  local dest="$1"
  if [ -n "$INSTALLER_SELF" ] && [ -f "$INSTALLER_SELF" ] && grep -q '^# AI Admin Panel Installer' "$INSTALLER_SELF"; then
    cp -f "$INSTALLER_SELF" "${dest}.tmp"
  elif [ "$RELEASE_ASSET_BASE" != "$GET_BASE" ]; then
    fetch_release_asset install.sh "${dest}.tmp" ||
      error "Could not download ${RELEASE_ASSET_BASE}/install.sh for the first boot."
  else
    error "--bake keeps a copy of this installer for the first boot, but it was piped (curl | bash) and PANEL_VERSION names no release. Download it first (curl -fsSL ${GET_BASE} -o install.sh) and run: bash install.sh --bake"
  fi
  chmod 700 "${dest}.tmp"
  mv -f "${dest}.tmp" "$dest"
}

# install_first_boot_files: the installer copy every channel's first boot
# runs, and on the Vultr Marketplace channel the cloud-init hook that runs it once per new
# server (Vultr's snapshot-build model; image pipeline spec section 5). It
# reads the deploy form from Vultr's metadata service and keeps SSH open
# (pipeline spec PD5). Other channels start the first boot themselves.
# is_vultr_marketplace_channel <channel>: the channel name is what licence
# events report as install_source (cmd/panel/main.go, ADR-0008 section 2), so
# Marketplace servers use vultr-marketplace, the name the attribution counts
# use. "vultr" was this channel's first name (AI-2747); it stays an alias, so
# a bake that still says vultr gets the hook too (AI-2749).
is_vultr_marketplace_channel() {
  case "$1" in
    vultr-marketplace | vultr) return 0 ;;
  esac
  return 1
}

install_first_boot_files() {
  local channel="${AAP_INSTALL_SOURCE:-custom}" lib="$FIRST_BOOT_LIB_DIR"
  local hook="${CLOUD_PER_INSTANCE_DIR}/aap-vultr-first-boot"
  if [ "$DRY_RUN" = "true" ]; then
    dryrun "copy this installer to ${lib}/install.sh (700)"
    ! is_vultr_marketplace_channel "$channel" || dryrun "write ${hook} (700): cloud-init runs it once on each new server"
    return 0
  fi
  mkdir -p "$lib"
  chmod 755 "$lib"
  install_self_copy "${lib}/install.sh"
  info "Installer kept for the first boot: ${lib}/install.sh"
  if is_vultr_marketplace_channel "$channel"; then
    mkdir -p "$CLOUD_PER_INSTANCE_DIR"
    _write_if_changed "$hook" "$(_aap_embed_vultr_first_boot)" 700 ||
      error "Could not write the first-boot hook ${hook}."
    info "Vultr first-boot hook installed: ${hook} (cloud-init runs it once on each new server)"
  else
    info "No first-boot hook for channel ${channel}: run ${lib}/install.sh --first-boot on each new server."
  fi
}

# bake_main: the whole --bake run. The refusals come first, before the log
# directory or anything else is created.
bake_main() {
  bake_refuse_if_configured || exit $?
  # No temporary-domain claim can happen in a bake (spec 1.6 item 41).
  MANAGED_DOMAIN=off
  if [ "$DRY_RUN" = "true" ]; then
    info "=== DRY RUN MODE: No changes will be made ==="
  fi
  mkdir -p "$LOG_DIR" 2>/dev/null || true
  echo ""
  echo "${COLOR_BOLD}AI Admin Panel image bake${COLOR_RESET}"
  echo "Version: ${PANEL_VERSION}"
  echo ""
  info "AI Admin Panel image bake v${PANEL_VERSION}"
  info "Install log: ${INSTALL_LOG}"
  local row
  TOTAL_STEPS="${#BAKE_ONLY_STEPS[@]}"
  for row in "${INSTALL_PLAN[@]}"; do
    case "$row" in bake:install_step_* | both:install_step_*) TOTAL_STEPS=$((TOTAL_STEPS + 1)) ;; esac
  done
  phase_bake
  local fn
  for fn in "${BAKE_ONLY_STEPS[@]}"; do
    "$fn"
  done
  step_timing_finish
  if [ "$DRY_RUN" = "true" ]; then
    info "=== DRY RUN complete: no changes were made ==="
  else
    # AI-2749: install_updater_marker builds updater.json in the updater's work
    # area and renames it out, leaving the folder empty; the image may not hold
    # it (bake spec row 21). Every user of it creates it again (mkdir -p).
    # rmdir removes only an EMPTY folder: anything inside stays for the
    # leftover check to report.
    rmdir "${PANEL_DIR}/.update-work" 2>/dev/null || true
    info "Bake complete. No secret, .env, volume or container was created; each server gets them at its first boot."
  fi
}

# ── install.sh --first-boot (AI-2747, spec 2.3, 4.3, 4.4) ───────────────────
# The per-server half of a baked image. A Vultr snapshot or an AWS AMI made
# after --bake holds the machine setup and every image, and nothing that
# belongs to one server. The first boot of each new server creates that part:
# domain, secrets, .env, setup code, the stack and its databases, the admin.
#
# Binding (spec 4.3): the installer keeps secrets it finds on disk (that makes
# a re-run safe). On a copied disk that would quietly keep another server's
# vault key and passwords, so the first boot records which server made the
# secrets (the instance ID in update/first-boot.json) and refuses (exit 3) to
# run on secrets this server did not make.
#
# Exit codes (spec 4.4): 0 done or already done, 1 a step failed (run it again;
# the secrets this server made are kept), 2 wrong invocation (no bake marker,
# a changed Compose file, another PANEL_VERSION), 3 another server's secrets.

# Where the first boot and the bake's first-boot files live. Plain variables:
# tests/installer/install_trace.bash points them at a temporary root.
FIRST_BOOT_LIB_DIR="/usr/local/lib/aap-marketplace"
CLOUD_PER_INSTANCE_DIR="/var/lib/cloud/scripts/per-instance"
FIRST_BOOT_MOTD="/etc/motd.d/50-aiadminpanel"
FIRST_BOOT_CONSOLE="/dev/console"
MACHINE_ID_FILE="/etc/machine-id"
INSTANCE_METADATA_BASE="http://169.254.169.254"

# Set by first_boot_read_instance_id.
FIRST_BOOT_INSTANCE_ID=""
FIRST_BOOT_ID_SOURCE=""
# The run's state for the status file: running, failed, done, foreign-secrets.
FIRST_BOOT_STATE=""
FIRST_BOOT_STARTED_AT=""
FIRST_BOOT_STEP=""

# json_string <text> → <text> as a JSON string, quotes included. Handles the
# characters an installer message can hold; control characters become spaces.
json_string() {
  local s="$1"
  s="${s//\\/\\\\}"
  s="${s//\"/\\\"}"
  s="$(printf '%s' "$s" | tr '\000-\037' ' ')"
  printf '"%s"' "$s"
}

# json_field <file> <key> → the string value of "<key>" in a one-line JSON
# file this installer wrote (baked.json, first-boot.json), or nothing.
json_field() {
  [ -f "$1" ] || return 0
  sed -n "s/.*\"$2\":\"\\([^\"]*\\)\".*/\\1/p" "$1" | head -n 1
}

first_boot_status_file() { printf '%s/update/first-boot.json\n' "$PANEL_DIR"; }

# first_boot_write_status <state> [error] [owner instance ID]: the status file
# (0644, written by rename). No secret ever goes in: the state, the step, the
# times, the instance IDs and the installer's own (secret-free) message. The
# owner is the server whose secrets are on disk; it differs from this server's
# ID only in a refusal, so a refusal stays a refusal on the next run.
first_boot_write_status() {
  local state="$1" err="${2:-}" owner="${3-$FIRST_BOOT_INSTANCE_ID}" file finished=""
  file="$(first_boot_status_file)"
  FIRST_BOOT_STATE="$state"
  case "$state" in running) ;; *) finished="$(date -u +%Y-%m-%dT%H:%M:%SZ)" ;; esac
  mkdir -p "$(dirname "$file")"
  {
    printf '{"instance_id":%s,"instance_id_source":%s,"this_instance_id":%s' \
      "$(json_string "$owner")" "$(json_string "$FIRST_BOOT_ID_SOURCE")" "$(json_string "$FIRST_BOOT_INSTANCE_ID")"
    printf ',"state":%s,"step":%s,"step_index":%s,"steps_total":%s' \
      "$(json_string "$state")" "$(json_string "$FIRST_BOOT_STEP")" "${CURRENT_STEP:-0}" "${TOTAL_STEPS:-0}"
    printf ',"version":%s,"started_at":%s,"finished_at":%s,"error":%s,"log":%s}\n' \
      "$(json_string "$PANEL_VERSION")" "$(json_string "$FIRST_BOOT_STARTED_AT")" "$(json_string "$finished")" \
      "$(json_string "$err")" "$(json_string "$INSTALL_LOG")"
  } >"${file}.tmp"
  chmod 644 "${file}.tmp"
  mv -f "${file}.tmp" "$file"
}

# first_boot_banner <line>...: the login banner (world-readable, so it holds
# no secret) and the same lines on the console (Vultr's web console, the EC2
# system log). Best effort: a host without either still installs.
first_boot_banner() {
  local line
  {
    mkdir -p "$(dirname "$FIRST_BOOT_MOTD")" &&
      {
        for line in "$@"; do printf '%s\n' "$line"; done
        printf 'Status: %s\n' "$(first_boot_status_file)"
        printf 'Install log: %s\n' "$INSTALL_LOG"
      } >"${FIRST_BOOT_MOTD}.tmp" &&
      chmod 644 "${FIRST_BOOT_MOTD}.tmp" &&
      mv -f "${FIRST_BOOT_MOTD}.tmp" "$FIRST_BOOT_MOTD"
  } 2>/dev/null || true
  if [ -w "$FIRST_BOOT_CONSOLE" ]; then
    { printf 'aiadminpanel first boot: %s\n' "$1" >"$FIRST_BOOT_CONSOLE"; } 2>/dev/null || true
  fi
}

# first_boot_on_step <title>: STEP_HOOK of a first boot (lib/log.sh step).
first_boot_on_step() {
  FIRST_BOOT_STEP="$1"
  first_boot_write_status running
  first_boot_banner "AI Admin Panel ${PANEL_VERSION}: first boot, step ${CURRENT_STEP} of ${TOTAL_STEPS}: $1" \
    "SSH stays open; the panel is not ready yet."
  return 0
}

# first_boot_on_exit: the EXIT trap of a first boot. A run that stops before
# it is done is recorded as failed (exit 1, retryable), with the step it
# stopped in and the installer's last error line.
first_boot_on_exit() {
  local rc=$?
  trap - EXIT
  set +e
  if [ "$FIRST_BOOT_STATE" = running ]; then
    [ "$rc" -ne 0 ] || rc=1
    local msg
    msg="$(sed -n 's/^\[[^]]*\] \[ERROR\] //p' "$INSTALL_LOG" 2>/dev/null | tail -n 1)"
    [ -n "$msg" ] || msg="exit ${rc}"
    first_boot_write_status failed "Step ${CURRENT_STEP:-0} of ${TOTAL_STEPS:-0} (${FIRST_BOOT_STEP:-start}) failed: ${msg}"
    first_boot_banner "AI Admin Panel ${PANEL_VERSION}: first boot FAILED in step ${CURRENT_STEP:-0} of ${TOTAL_STEPS:-0}: ${FIRST_BOOT_STEP:-start}" \
      "Run it again: sudo ${FIRST_BOOT_LIB_DIR}/install.sh --first-boot (this server's secrets are kept)."
    echo "First boot failed in step ${CURRENT_STEP:-0} of ${TOTAL_STEPS:-0}. Run install.sh --first-boot again; this server's secrets are kept." >&2
    exit 1
  fi
  exit "$rc"
}

# first_boot_read_instance_id: which server this is. Vultr's metadata service
# first (instance-v2-id, the instance's UUID), else /etc/machine-id. Read on
# the host only; containers never reach the metadata address (egress guard).
first_boot_read_instance_id() {
  local id=""
  id="$(curl -fsS --connect-timeout 2 --max-time 3 --retry 1 -H 'METADATA-TOKEN: vultr' \
    "${INSTANCE_METADATA_BASE}/v1/instance-v2-id" 2>/dev/null)" || id=""
  if [[ "$id" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ]]; then
    FIRST_BOOT_INSTANCE_ID="$id" FIRST_BOOT_ID_SOURCE=vultr-metadata
    return 0
  fi
  id="$(tr -d '[:space:]' <"$MACHINE_ID_FILE" 2>/dev/null)" || id=""
  if [[ "$id" =~ ^[0-9a-f]{32}$ ]]; then
    FIRST_BOOT_INSTANCE_ID="$id" FIRST_BOOT_ID_SOURCE=machine-id
    return 0
  fi
  return 1
}

# first_boot_check_bake <marker>: the server is the one the bake made. Sets
# PANEL_VERSION to the baked version (the images on disk), refuses another
# version or a Compose file that changed after the bake. Exit 2, no change.
first_boot_check_bake() {
  local marker="$1" baked_version want_sha got_sha compose="${PANEL_DIR}/docker-compose.yml"
  baked_version="$(json_field "$marker" version)"
  [ -n "$baked_version" ] || { echo "--first-boot: ${marker} names no version. Run install.sh --bake again. Nothing was changed." >&2; exit 2; }
  if [ -z "$PANEL_VERSION_GIVEN" ]; then
    PANEL_VERSION="$baked_version"
    RELEASE_ASSET_BASE="$(release_asset_base "$GET_BASE" "$PANEL_VERSION")"
  elif [ "$PANEL_VERSION" != "$baked_version" ]; then
    echo "--first-boot: this server was baked with version ${baked_version}, not PANEL_VERSION=${PANEL_VERSION}. Unset PANEL_VERSION. Nothing was changed." >&2
    exit 2
  fi
  want_sha="$(json_field "$marker" compose_sha256)"
  got_sha="$(sha256_hex <"$compose" 2>/dev/null)" || got_sha=""
  if [ -z "$want_sha" ] || [ "$got_sha" != "$want_sha" ]; then
    echo "--first-boot: ${compose} is missing or differs from the one the bake recorded in ${marker}; its images may not be on disk. Run install.sh --bake again. Nothing was changed." >&2
    exit 2
  fi
}

# first_boot_bind: spec 4.3. Returns when this run may go on: a fresh server,
# or a first boot of this same server that stopped. Exits 0 when this server's
# first boot is already done, 3 when the secrets on disk are another server's.
first_boot_bind() {
  local file owner state
  file="$(first_boot_status_file)"
  owner="$(json_field "$file" instance_id)"
  state="$(json_field "$file" state)"
  if [ -n "$owner" ] && [ "$owner" = "$FIRST_BOOT_INSTANCE_ID" ] && [ "$state" = "done" ]; then
    info "The first boot of this server is already done (${file}). Nothing to do."
    exit 0
  fi
  if [ ! -e "$SECRETS_DIR" ] && [ ! -e "${PANEL_DIR}/.env" ]; then
    return 0
  fi
  # This server made the secrets: a first boot that stopped (running, failed),
  # or one whose record another server's refused run overwrote. Resume.
  if [ -n "$owner" ] && [ "$owner" = "$FIRST_BOOT_INSTANCE_ID" ]; then
    info "Resuming this server's first boot (it stopped in: $(json_field "$file" step)). Its secrets are kept."
    return 0
  fi
  local why
  if [ -z "$owner" ]; then
    why="no first-boot record says this server made them"
  else
    why="they were made by another server (${owner})"
  fi
  # O2 (spec 12): a copy of a finished server keeps running on its copied
  # secrets (its containers start by restart policy); nothing is regenerated,
  # that would lock its data out. The refusal is the warning.
  FIRST_BOOT_STEP="binding"
  first_boot_write_status foreign-secrets "This disk holds another server's secrets: ${why}. Nothing was changed." "$owner"
  first_boot_banner "AI Admin Panel: first boot REFUSED: this disk holds another server's secrets (${why})." \
    "Nothing was changed. Deploy a fresh server from the image instead."
  echo "--first-boot refused: ${SECRETS_DIR} or ${PANEL_DIR}/.env exists, and ${why}. This disk holds another server's secrets; nothing was changed." >&2
  exit 3
}

# print_first_boot_success: the end screen of a first boot (spec 4.4). Where
# to go and which commands print what, never a value: no admin password, setup
# code or recovery key, on a terminal or not.
print_first_boot_success() {
  local domain="${PANEL_DOMAIN:-localhost}"
  write_setup_link_file # AI-2792: still written, no longer shown (deprecated)
  cat <<EOF

${COLOR_GREEN}${COLOR_BOLD}===========================================================
  AI Admin Panel is ready (first boot done)
===========================================================${COLOR_RESET}

  Panel URL:      https://${domain}
  Sign-in e-mail: ${ADMIN_EMAIL:-admin@${domain}}
  Admin password: the one you chose when you deployed the server
                  (or: sudo cat ${SECRETS_DIR}/admin_password)
  Next:           open the panel and sign in; the setup wizard opens next
  Recovery key:   sudo aap-openbao-key export          (store it offline)
  Status:         $(first_boot_status_file)

EOF
}

# first_boot_main: the whole --first-boot run.
first_boot_main() {
  if [ "$BAKE" = "true" ] || [ "$REFRESH_UPDATER" = "true" ] || [ "$DOCKER_ADDRESS_POOLS" = "true" ] || [ "$NEW_SETUP_TOKEN" = "true" ]; then
    echo "--first-boot cannot be combined with --bake, --refresh-updater, --docker-address-pools or --new-setup-token." >&2
    exit 2
  fi
  if [ "$DRY_RUN" = "true" ]; then
    echo "--first-boot has no dry run: it creates this server's secrets. Use --bake --dry-run, or a plain --dry-run." >&2
    exit 2
  fi
  local marker="${CONFIG_DIR}/baked.json"
  if [ ! -f "$marker" ]; then
    echo "--first-boot needs a baked server: ${marker} is missing. Run install.sh --bake first. Nothing was changed." >&2
    exit 2
  fi
  first_boot_check_bake "$marker"
  if ! first_boot_read_instance_id; then
    echo "--first-boot cannot tell which server this is: no instance ID from the metadata service and no ${MACHINE_ID_FILE}. Nothing was changed." >&2
    exit 1
  fi
  first_boot_bind

  # A first boot has no one at the keyboard (cloud-init), and its screen may
  # be a log: unattended, and no metered-model download (owner decision O5;
  # the model comes later from the AI Models page).
  UNATTENDED=true
  AAP_SKIP_MODEL_PULL="${AAP_SKIP_MODEL_PULL:-true}"
  INSTALL_PHASE=first-boot
  mkdir -p "$LOG_DIR" 2>/dev/null || true
  echo ""
  echo "${COLOR_BOLD}AI Admin Panel first boot${COLOR_RESET}"
  echo "Version: ${PANEL_VERSION}"
  echo ""
  info "AI Admin Panel first boot v${PANEL_VERSION} (instance ${FIRST_BOOT_INSTANCE_ID}, from ${FIRST_BOOT_ID_SOURCE})"
  info "Install log: ${INSTALL_LOG}"

  local row
  TOTAL_STEPS="${#FIRST_BOOT_ONLY_STEPS[@]}"
  for row in "${INSTALL_PLAN[@]}"; do
    case "$row" in first-boot:install_step_* | both:install_step_*) TOTAL_STEPS=$((TOTAL_STEPS + 1)) ;; esac
  done
  FIRST_BOOT_STARTED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  first_boot_write_status running
  trap first_boot_on_exit EXIT
  STEP_HOOK=first_boot_on_step

  phase_first_boot
  local fn
  for fn in "${FIRST_BOOT_ONLY_STEPS[@]}"; do
    "$fn"
  done
  step_timing_finish

  STEP_HOOK=""
  FIRST_BOOT_STEP="done"
  first_boot_write_status "done"
  first_boot_banner "AI Admin Panel ${PANEL_VERSION}: ready at https://${PANEL_DOMAIN:-<see the status file>}" \
    "Sign in as ${ADMIN_EMAIL:-admin@${PANEL_DOMAIN:-<panel domain>}}; the setup wizard opens next."
  print_first_boot_success
  trap - EXIT
}

# ── Main ──────────────────────────────────────────────────────────────────────

main() {
  # First boot of a baked server (AI-2747): before the bake check, so
  # --first-boot --bake is refused as a combination (exit 2).
  if [ "$FIRST_BOOT" = "true" ]; then
    first_boot_main
    return 0
  fi

  # Cloud image build (AI-2745). Never combined with the host-file modes;
  # first, so a refusal happens before anything (even the log) is written.
  if [ "$BAKE" = "true" ]; then
    if [ "$REFRESH_UPDATER" = "true" ] || [ "$DOCKER_ADDRESS_POOLS" = "true" ] || [ "$NEW_SETUP_TOKEN" = "true" ]; then
      echo "--bake cannot be combined with --refresh-updater, --docker-address-pools or --new-setup-token." >&2
      exit 1
    fi
    bake_main
    return 0
  fi

  if [ "$DRY_RUN" = "true" ]; then
    info "=== DRY RUN MODE: No changes will be made ==="
  fi

  # Host files only: the updater and the container egress guard (AI-1104).
  # Nothing of the install below runs, so an existing install's configuration,
  # secrets and containers are not touched. The guard does change the host
  # firewall.
  if [ "$REFRESH_UPDATER" = "true" ]; then
    check_root || exit $?
    refresh_host_files
    return 0
  fi

  # Docker address pools only (AI-1446). Kept apart from --refresh-updater
  # because a change restarts Docker and with it every container.
  if [ "$DOCKER_ADDRESS_POOLS" = "true" ]; then
    check_root || exit $?
    configure_docker_address_pools_only || exit 1
    return 0
  fi

  # Setup code only (AI-1184): same shape as --refresh-updater above.
  if [ "$NEW_SETUP_TOKEN" = "true" ]; then
    check_root || exit $?
    new_setup_token || exit 1
    return 0
  fi

  # Ensure log directory exists early (best-effort)
  mkdir -p "$LOG_DIR" 2>/dev/null || true

  echo ""
  echo "${COLOR_BOLD}AI Admin Panel Installer${COLOR_RESET}"
  echo "Version: ${PANEL_VERSION}"
  echo ""

  info "AI Admin Panel Installer v${PANEL_VERSION}"
  info "Install log: ${INSTALL_LOG}"

  # AI-2332: the number of `step` calls in the install_step_* functions of the
  # install plan above. Change it when you add or remove a step;
  # tests/installer/step_count.bats fails until the two agree.
  TOTAL_STEPS=26

  run_install_plan all
  # AI-2777: the last step's time and the total, in the install log.
  step_timing_finish

  if [ "$DRY_RUN" = "false" ]; then
    print_success
  else
    info "=== DRY RUN complete: no changes were made ==="
  fi
}

main "$@"
