#!/bin/bash
#===============================================================================
# EvoBox Installation Script
#
# Version: 1.4.0
# Release Date: 2026-04-20
#
# Purpose: Transform a fresh Ubuntu/Lubuntu mini PC into a production-ready
#          streaming device for automated pool match broadcasting
#
# Execution: Runs every 5 minutes via cron job (idempotent) — see evo_crontab
# Repository: daemon-install-script
#
# Fault Tolerance Design:
# -----------------------
# This script is designed to be fully fault-tolerant:
#
# 1. Non-Blocking Execution: Script continues even if individual tasks fail
# 2. Comprehensive Logging: All successes and failures are logged with context
# 3. Error Handling: Each critical operation checks for failures and logs them
# 4. Idempotent Operations: Safe to run repeatedly, only installs missing components
# 5. Graceful Degradation: Failures don't prevent other tasks from executing
#
# Error Handling Strategy:
# - Use 'set +e' to continue on errors
# - Check exit codes for critical operations
# - Log errors with log_error() but continue execution
# - Return error codes from functions without stopping script
#
# Benefits:
# - Partial installations can still provide functionality
# - Network issues don't brick the entire installation
# - Transient failures (apt locks, network timeouts) don't halt progress
# - Each cron run attempts to complete remaining tasks
#===============================================================================

set +e  # Continue on errors (fault-tolerant mode)
export DEBIAN_FRONTEND=noninteractive  # Suppress interactive prompts (runs via cron)

#===============================================================================
# CONFIGURATION
#===============================================================================

# Daemon configuration
readonly SECOND_DAEMON_FLAG_FILE="$HOME/secondDaemon"
readonly SECOND_DAEMON=$([ -f "$SECOND_DAEMON_FLAG_FILE" ] && echo "true" || echo "false")

# Directory structure
readonly EVOSPORTS_ROOT="$HOME/evosports"
readonly EVOSPORTS_MAIN_DAEMON="$EVOSPORTS_ROOT/evo-obs-daemon-main"
readonly EVOSPORTS_SECOND_DAEMON="$EVOSPORTS_ROOT/evo-daemon-second"
# Durable copies of each daemon's evo.json (main.json, second.json) plus an
# append-only history.log. Outside both daemon trees, so no wipe touches it, and
# never deleted by this script. A deliberate re-identity means removing both the
# live evo.json and the copy here (#67).
readonly EVO_IDENTITY_DIR="$HOME/.local/state/evobox-identity"
# What a usable evo.json object looks like. Applied with `jq -s` to the whole
# file, so a 0-byte, truncated or concatenated file fails. Real ids include
# suffixed ones such as evo-91-secondtest. Spliced into the daemon runner too.
readonly EVO_IDENTITY_JQ='type == "object" and (.deviceId | type == "string" and test("^evo-[A-Za-z0-9._-]+$"))'
readonly EVOSPORTS_LOGS="$HOME/logs"
readonly EVOSPORTS_INSTALL_LOG="$EVOSPORTS_LOGS/daemon_install_stdout.log"

# Node.js configuration
# NODE_VERSION is the runtime the daemon runs on. Node 20 reached upstream
# end-of-life on 2026-04-30, so the fleet moves to Node 22.
readonly NODE_VERSION="v22.23.4"
# The runtime the fleet was provisioned with before NODE_VERSION moved to
# Node 22. It stays installed beside NODE_VERSION so that an `nvm install`
# failure (nodejs.org unreachable, disk full, power cut mid-extract) leaves a
# device on a working runtime instead of none. install_nvm(), the daemon runner
# and the NDI check wrapper use it only while NODE_VERSION is unusable.
# Removing this constant and the 20.5.1 tree on disk is a separate, later
# release, once the fleet has been confirmed on NODE_VERSION.
readonly NODE_FALLBACK_VERSION="v20.5.1"
# How long a failed `nvm install $NODE_VERSION` backs off on a device that is
# still running NODE_FALLBACK_VERSION. A device with no usable Node at all
# ignores this and retries every tick.
readonly NODE_INSTALL_RETRY_TTL=3600
# Pinned pnpm version. Bump deliberately to roll a new pnpm to the fleet.
# Installed globally into the nvm-managed Node toolchain by install_pnpm().
readonly PNPM_VERSION="10.10.0"

# Kill switch for run_bootstrap_once()'s blanket `apt-get upgrade`. Paused
# because `upgrade` never installs NEW packages: Mesa 24.3.0 split the gallium
# drivers out into mesa-libgallium, so evobox-0047 took libgl1-mesa-dri to
# 24.3.0 while the rest of the mesa set stayed at 24.1.0, and the ABI mismatch
# ("libEGL fatal: did not find extension DRI_Mesa version 1") put OBS off the
# air mid-broadcast (issue #41). Unpause only together with the
# security-origin-scoped rewrite of the `apt-get upgrade` calls in
# run_bootstrap_once() — an unscoped upgrade re-opens the same partial
# transaction. Deliberately no auto-expiry: a dangerous operation resuming on a
# timer is worse than a stale pause. owner: jason@evosports.live
#
# Devices without .evo-bootstrap-v1 stay flagless while this is true — the
# guard sits above the flag check, so the safe implementation still gets its
# turn on every device that never bootstrapped.
readonly BOOTSTRAP_APT_UPGRADE_PAUSED=true

# APT lock: the fleet's apt "lockfile". Ubuntu packages resolve against one
# snapshot of the Ubuntu archive (snapshot.ubuntu.com) and third-party packages
# against exact versions, so every device that applies a lock ends on the
# versions a test device was verified on. Nothing happens on a device until one
# of these three values changes. Bump them in a PR only for a serious CVE or a
# deliberate need, ship to beta, verify on the test device, then main.
# owner: jason@evosports.live
#
# Only APT_LOCK_PACKAGES and APT_LOCK_PINS are requested, with
# `install --only-upgrade`: a package a device does not have is skipped rather
# than installed, and a pin older than what a device already runs is never a
# downgrade. A dependency the snapshot needs at a newer version (libnspr4 for
# libnss3, say) moves with them unless apt_lock_guard refuses it: a removal, a
# kernel package, or an unlisted package in APT_LOCK_GUARD_REGEX or the mesa
# source stops the lock. The snapshot is used by this step alone, through a private sources
# file and lists directory, so every other apt call in this script keeps
# resolving against the live archive and /var/lib/apt/lists is never rewritten.
# The private sources file always names archive.ubuntu.com, whatever regional
# mirror the device's own sources.list uses: the snapshot service only covers
# the main archive and security hosts.
#
# Timing (device-local): lists and downloads happen late in a tick whenever the
# lock changes, without opening dpkg. The install itself runs from the local
# cache only on the 05:00 or 05:05 tick, after the 04:00 daemon restart and the
# 04:40 NDI probe, and is skipped while OBS is streaming. A missed window waits
# for the next day. On a test device, `touch ~/.evo-apt-lock-now` skips the
# stagger, backoff and window until the current lock is applied or refused.
readonly APT_LOCK_SNAPSHOT="20261027T000000Z"
readonly APT_LOCK_PACKAGES="ca-certificates libnss3"
readonly APT_LOCK_PINS="tailscale=1.104.2"
# Never upgraded as a side effect of the lists above: kernels need a planned
# reboot, a partial Mesa/GPU/OBS set took OBS off the air (#41), and the
# initramfs/bootloader chain is the #28 class. A simulated transaction that
# touches one of these without it being listed, or that removes any package, is
# refused. Kernel packages (linux-*) are refused even when listed.
readonly APT_LOCK_GUARD_REGEX='^(linux-|mesa-|libgl1|libegl|libgles|libglx|libgbm|libglapi|libosmesa|libxatracker|libd3dadapter|libdrm|libva|va-driver|i965-va-driver|libigd|libigc|libigfx|libze|level-zero|libmfx|libvpl|intel-|xserver-xorg|obs-studio|nvidia|initramfs-tools|dracut|zstd|grub|shim)'
# off: nothing runs anywhere (kill switch; changing it does not move the
# fingerprint, so switching back resumes where each device stopped).
# trial: only devices carrying ~/.evo-apt-lock-trial take part, whatever their
# deployment channel. fleet: every jammy device.
readonly APT_LOCK_MODE="fleet"
readonly APT_LOCK_WINDOW_HOUR="05"
# Repeated dead ends page once per lock instead of only logging: a window
# skipped this many times for a live or unreadable stream (two windows a day),
# or this many failed list refreshes / downloads.
readonly APT_LOCK_ALERT_AFTER_SKIPS=6
readonly APT_LOCK_ALERT_AFTER_FAILURES=5
readonly APT_LOCK_VIEW_DIR="/var/lib/evobox-apt-lock"
readonly APT_LOCK_STATE_DIR="$HOME/.local/state/evobox-apt-lock"
# A failed download is retried at most once an hour, so a device on a bad
# venue network does not spend every tick on it.
readonly APT_LOCK_RETRY_SECONDS=3600

# Freshness-guard cache. Slow GCS round-trips (crontab download, OBS-NDI
# version manifest, download_media.py) only need to run once per 12 hours
# on healthy devices — those payloads change rarely. Daemon-version checks
# stay UNGATED so deploys still propagate within one cron tick.
#
# Operator override: `touch $EVO_FORCE_REFRESH_FLAG` to force every gated
# fetch to run on the next tick. The flag is auto-deleted at end-of-tick.
# Set EVO_GCS_FRESHNESS_TTL=<seconds> in env to shorten/lengthen the window
# (used by integration tests).
readonly EVO_CACHE_DIR="$HOME/.evo-cache"
readonly EVO_FORCE_REFRESH_FLAG="$HOME/.evo-force-refresh"
readonly EVO_UPTIME_PATH="${EVO_UPTIME_PATH:-/proc/uptime}"
readonly EVO_GCS_FRESHNESS_TTL="${EVO_GCS_FRESHNESS_TTL:-$((12 * 3600))}"
# Monotonic origin of the watchdog sleep armed in main(), and the headroom that
# watchdog_headroom_available() derives from it. Both empty until main() runs.
WATCHDOG_UPTIME_BASELINE=""
WATCHDOG_HEADROOM_SECONDS=""
# How long a *failed* Mesa repair waits before trying again: long enough to skip
# one six-hour stagger window, deliberately UNDER two of them. The stamp is
# written later in the tick than the stagger check that produced it, so a TTL of
# exactly two windows (12h) is always still open at the second eligible slot and
# silently pushes the real retry out to 18h. Explicit rather than inheriting
# EVO_GCS_FRESHNESS_TTL, which is scoped to GCS manifest freshness and has
# nothing to do with apt retry cadence.
readonly MESA_REPAIR_RETRY_TTL=$((11 * 3600))
export DISPLAY=:0

# GCS paths
readonly GCS_BASE="https://storage.googleapis.com/releases-evosports"
readonly GCS_EVOBOX="${GCS_BASE}/evobox"
readonly GCS_DEPLOYMENT="${GCS_EVOBOX}/deployment"
readonly GCS_MEDIA="${GCS_EVOBOX}/media"
readonly GCS_MONITORING="${GCS_EVOBOX}/monitoring"
readonly GCS_UTILS="${GCS_EVOBOX}/utils"
readonly GCS_NDI="${GCS_EVOBOX}/ndi"
readonly GCS_NGINX="${GCS_EVOBOX}/nginx"
readonly GCS_SCENES="${GCS_EVOBOX}/scenes"
readonly GCS_OBS="${GCS_EVOBOX}/obs"
readonly GCS_OBS_PLUGINS="${GCS_EVOBOX}/obs-plugins"
readonly GCS_USB_WIFI="${GCS_EVOBOX}/usb-wifi-config"
readonly GCS_ZOWIE_NDI_PROBE="${GCS_EVOBOX}/zowie-ndi-probe"
# The probe is a single self-contained binary installed at one stable path. The
# installed version is simply the sha256 of that file — no sidecar, no
# content-addressed release tree. Updates are an atomic `mv -T` over this path;
# a probe already executing keeps its old inode, so a replace never corrupts it.
readonly ZOWIE_NDI_PROBE_BIN="$HOME/.local/bin/zowie-ndi-probe"
readonly ZOWIE_NDI_PROBE_CHECK_TTL=43200
readonly ZOWIE_NDI_PROBE_RETRY_TTL=3600
readonly ZOWIE_NDI_PROBE_QUERY_TIMEOUT=30    # --help / runtime-info should return near-instantly
readonly ZOWIE_NDI_PROBE_SETUP_TIMEOUT=300   # setup may run apt-get; stay well under the 600s watchdog
# Scheduled, out-of-process NDI health-check wrapper. The 04:10 cron line that
# invokes it lives in the centrally-deployed crontab (evo_crontab[_beta]), NOT
# in this installer — see check_and_update_zowie_ndi_probe()'s sibling wrapper.
readonly ZOWIE_NDI_PROBE_CHECK_WRAPPER="/usr/local/bin/zowie-ndi-probe-check"

# --- publishd (publisher-v2) --------------------------------------------------
# The Rust publisher that replaces the Chrome publish path when a device's
# publisherV2 flag is true. Installing it fleet-wide is safe and inert: the
# daemon only calls isAvailable() when desiredPublisher returns 'publishd',
# which requires publisherV2 === true, so on the 300+ devices where the flag is
# false the binary is never touched. Chrome remains the fallback and the
# rollback, which is why fleet-wide installation has a low risk ceiling.
# End-to-end contract: evobox-publisher-v2/docs/publishd-auto-install.md
readonly GCS_PUBLISHER_V2="${GCS_EVOBOX}/publisher-v2"
# Every publishd path derives from this one root, so the self-check in
# tests/test-publishd-install.sh can redirect all of them into a temp dir. The
# value itself is not configurable at runtime: /opt/evobox/gstreamer/env.sh
# bakes in its own absolute prefix, so the runtime cannot live anywhere else.
readonly PUBLISHD_OPT_ROOT="/opt/evobox"
readonly PUBLISHD_DIR="$PUBLISHD_OPT_ROOT/publishd"
readonly PUBLISHD_BIN="$PUBLISHD_DIR/publishd"
readonly PUBLISHD_LAUNCHER="$PUBLISHD_DIR/publishd-run.sh"
readonly GSTREAMER_DIR="$PUBLISHD_OPT_ROOT/gstreamer"
# THIRD copy of a pin whose authority is evobox-publisher-v2/dev-env/versions.sh
# (GST_PINNED_VERSION); the second is that repo's docs/publishd-deploy.md §5.
# A device has no repo checkout to read it from, so it is spelled out
# here. All three must be bumped together. Deliberately NOT a manifest object:
# this pin has never moved, and a manifest would add a fleet-wide fetch and a
# new failure mode to a constant that changes less often than this script does.
readonly GSTREAMER_TARBALL="gstreamer-1.26.11-jammy-amd64.tar.gz"
# Channel selector, INDEPENDENT of ~/.evo-beta (which selects the daemon build).
# A device with ~/.evo-beta and no ~/.evo-publishd therefore runs a beta daemon
# against a production publishd — a safe combination given Chrome is the
# fallback, but not what "beta device" looks like at a glance. See
# resolve_publishd_object() for the value grammar.
readonly PUBLISHD_CHANNEL_FLAG="$HOME/.evo-publishd"
readonly PUBLISHD_CHECK_TTL=43200          # 12h success cache on the binary check
readonly PUBLISHD_RETRY_TTL=3600           # 1h backoff after a failed attempt
readonly OBS_NDI_RETRY_TTL=3600            # 1h backoff after a failed OBS/NDI install
# Staged rollout, now at Stage 2: a device with no ~/.evo-publishd marker
# tracks publishd-latest, so the whole fleet installs publishd on the next
# ./publish.sh main. Stage 1 shipped this empty, which meant a markerless
# device did NOTHING — not even the 134 MB GStreamer fetch — and only
# 0015/0093 (carrying an explicit marker) were affected.
#
# Rolling back is shipping "" here again, NOT deleting markers: under Stage 2
# the devices affected are precisely the ones with no file to delete. That is
# also why the fleet is moved by this constant rather than by writing a marker
# onto every device — a materialised marker would make "absent" unreachable,
# permanently disarming this switch and leaving PUBLISHD_INSTALL_PAUSED as the
# only remaining lever.
readonly PUBLISHD_DEFAULT_CHANNEL="latest"
# Kill switch, modelled on BOOTSTRAP_APT_UPGRADE_PAUSED: ship the script with
# this true to stop every device installing publishd, without needing device
# access. Deliberately no auto-expiry. owner: jason@evosports.live
readonly PUBLISHD_INSTALL_PAUSED=false
# Instantaneous peak while swapping the runtime: 134 MB tarball + 609 MB staged
# tree + 609 MB existing tree. The fleet cannot be inventoried box by box, so
# the check is unconditional.
readonly PUBLISHD_MIN_FREE_MB=2048
# Watchdog headroom the GStreamer EXTRACT needs, vs the 300s the shared helper
# defaults to. It covers unpacking 609 MB plus the staged `timeout 60` functional
# check, neither of which can be resumed if SIGKILLed partway: the recovery is to
# discard the staging tree and start over. The download ahead of it keeps the bare
# 300s floor, because that one does resume across ticks.
readonly PUBLISHD_RUNTIME_HEADROOM_SECONDS=480

# Splashtop configuration
readonly SPLASHTOP_DEPLOYMENT_ID="5Z3LPXPZH243"

# Tailscale configuration
# Replace this with the Tailscale OAuth client secret that has the auth_keys
# scope and permission to apply tag:evobox plus the deployment tags below.
readonly TAILSCALE_OAUTH_SECRET="tskey-client-kDULW9Py7621CNTRL-DUDR7rzEYcEuwANXHhDXdEuw4w5NgUgK"
readonly TAILSCALE_AUTH_CREDENTIAL="${TAILSCALE_OAUTH_SECRET}?ephemeral=false&preauthorized=true"

# Webhook destinations. Format: name|provider|url
# provider currently supports google_chat and discord.
# Use one Google Chat destination for deployment progress and daemon alerts.
readonly GOOGLE_CHAT_WEBHOOK_URL="https://chat.googleapis.com/v1/spaces/AAQA1dGPGIg/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=6R1Icx-VDgd43R_8pMOjz40luxLitT8B8gtkUpi10Kw"
readonly DISCORD_WEBHOOK_URL="https://discord.com/api/webhooks/1509643923411435610/bjB3VlMKFODQVhvaAoHZrnIopAYfAmf7kMyANtg0F-ixaioCTjHhssbiGQxxcTVf8dhY"

readonly WEBHOOK_DESTINATIONS=(
    "fleet-google-chat|google_chat|$GOOGLE_CHAT_WEBHOOK_URL"
    "fleet-discord|discord|$DISCORD_WEBHOOK_URL"
)

readonly DAEMON_ALERT_WEBHOOK_DESTINATIONS=(
    "daemon-google-chat|google_chat|$GOOGLE_CHAT_WEBHOOK_URL"
    "daemon-discord|discord|$DISCORD_WEBHOOK_URL"
)

# Fleet config history (oldest to newest, last element is current target)
readonly CFG_HISTORY=(
    "MTIzNDVtaW5pcGM="  # oldest
    "ZXZvYm94MTIz"      # older
    "ZXZvMDQwOTEx"      # current target (newest)
)

# SSH configuration - add new public keys to this array
readonly SSH_TAILSCALE_CONF="/etc/ssh/sshd_config.d/tailscale-only.conf"
# evo-gateway@elosports is the cloud gateway's (evo-remote-gateway) service key.
# The private half lives in gs://elosports-evo-gateway-ssh/evobox/, so the
# from= option limits it to tailnet source addresses (Tailscale's CGNAT and
# ULA ranges): a leaked copy cannot log in from anywhere off the tailnet.
readonly SSH_AUTHORIZED_KEYS=(
    "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMa9xuRxAdIDTrgUYdft4If/9Ww+RiAEFD1Ij4l75PtU Colin MBPMax"
    'from="100.64.0.0/10,fd7a:115c:a1e0::/48" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGJqlrQrA6vFjd2dwW1mZTT6KxKTwd1cDT9I5IgcI0Py evo-gateway@elosports'
)

# Lock file configuration (prevents concurrent execution from cron overlap)
readonly LOCKFILE="/tmp/evobox-install.lock"
readonly LOCK_TIMEOUT=600        # 10 minutes — wall-clock hang ceiling enforced by watchdog in main()
readonly LOCK_STALE_CEILING=600  # 10 minutes — matches LOCK_TIMEOUT. If an external process holds fd 200
                                 # longer than this, break the lock in main(). Covers orphan holders
                                 # (e.g. legacy nohup'd daemon that inherited fd 200 pre-systemd migration)
                                 # that the in-process watchdog cannot reach.
readonly LOCK_WARN_THRESHOLD=30  # A healthy tick finishes in 2–3 s; anything beyond this is unusual.
                                 # Used to promote install-duration and lock-skip logs to WARN so GCP
                                 # Monitoring / log scanners can surface stuck installs before they hit
                                 # the hard ceiling.

# No-op retained for backward compatibility with existing call sites.
# The lock is now held via flock on fd 200 and auto-released on process exit
# (normal, crash, SIGKILL, reboot). See main() for acquisition + watchdog.
refresh_lock() { :; }

#===============================================================================
# UTILITY FUNCTIONS
#===============================================================================

# Initialize logs directory
mkdir -p "$EVOSPORTS_LOGS"

# Clean up old log files from home directory (moved to $HOME/logs)
cleanup_legacy_logs() {
    if [ -d "$EVOSPORTS_LOGS" ]; then
        local old_logs=(
            "daemon_install_stdout.log"
            "daemon_stdout.log"
            "daemon_stderr.log"
            "daemon2_stdout.log"
            "daemon2_stderr.log"
            "telemetry.log"
        )

        for log in "${old_logs[@]}"; do
            [ -f "$HOME/$log" ] && rm -f "$HOME/$log"
        done
    fi
}
cleanup_legacy_logs

# Logging function
log() {
    echo "($$)[$(date "+%Y-%m-%d %H:%M:%S.%3N")]$1" | tee -a "$EVOSPORTS_INSTALL_LOG"
}

# Debug-only logging. Suppressed in steady-state to keep daemon_install_stdout.log
# from ballooning (runs 1440x/day). Enable on a device with `touch ~/.evo-debug`
# when diagnosing. Use for "already configured / up-to-date / no-change"
# confirmations and any per-tick chatter that doesn't represent a real event.
log_debug() {
    [ -f "$HOME/.evo-debug" ] || return 0
    echo "($$)[$(date "+%Y-%m-%d %H:%M:%S.%3N")][DEBUG] $1" | tee -a "$EVOSPORTS_INSTALL_LOG"
}

# Error logging function
log_error() {
    echo "($$)[$(date "+%Y-%m-%d %H:%M:%S.%3N")][ERROR] $1" | tee -a "$EVOSPORTS_INSTALL_LOG"
}

# Safe command execution with error logging
safe_exec() {
    local description="$1"
    shift

    if "$@"; then
        log "[SUCCESS] $description"
        return 0
    else
        local exit_code=$?
        log_error "$description (exit code: $exit_code)"
        return $exit_code
    fi
}

log "[EVODAEMON:INSTALL START] EvoBox install script running..."
_INSTALL_START_TS=$(date +%s)

# Check if command exists
check_command() {
    command -v "$1" > /dev/null 2>&1
}

# String parser utility
parse_config() { echo "$1" | base64 -d; }

# Send webhook notifications to every configured destination. Each destination
# entry is name|provider|url, so URL changes stay centralized above.
get_primary_ip() {
    local ip
    ip=$(hostname -I 2>/dev/null | awk '{print $1}')
    [ -z "$ip" ] && ip="unknown-ip"
    printf '%s' "$ip"
}

format_webhook_text() {
    local title="$1"
    local severity="$2"
    local message="$3"
    local host ip now
    host=$(hostname 2>/dev/null || echo "unknown-host")
    ip=$(get_primary_ip)
    now=$(date -u "+%Y-%m-%dT%H:%M:%SZ")

    printf '%s\nSeverity: %s\nHost: %s\nIP: %s\nTime: %s\n\n%s' \
        "$title" "$severity" "$host" "$ip" "$now" "$message"
}

truncate_discord_content() {
    local content="$1"
    local max_len=1900
    if [ "${#content}" -le "$max_len" ]; then
        printf '%s' "$content"
        return 0
    fi

    printf '%s\n\n[truncated]' "${content:0:$((max_len - 13))}"
}

build_webhook_payload() {
    local provider="$1"
    local text="$2"
    local safe

    case "$provider" in
        google_chat)
            if command -v jq >/dev/null 2>&1; then
                jq -nc --arg text "$text" '{text: $text}'
            else
                safe=$(printf '%s' "$text" | tr '\n' ' ' | sed 's/\\/\\\\/g; s/"/\\"/g')
                printf '{"text":"%s"}' "$safe"
            fi
            ;;
        discord)
            text=$(truncate_discord_content "$text")
            if command -v jq >/dev/null 2>&1; then
                jq -nc --arg content "$text" '{content: $content}'
            else
                safe=$(printf '%s' "$text" | tr '\n' ' ' | sed 's/\\/\\\\/g; s/"/\\"/g')
                printf '{"content":"%s"}' "$safe"
            fi
            ;;
        *)
            return 64
            ;;
    esac
}

post_webhook_destination() {
    local destination="$1"
    local title="$2"
    local severity="$3"
    local message="$4"
    local name provider url text payload

    IFS='|' read -r name provider url <<< "$destination"
    if [ -z "$name" ] || [ -z "$provider" ] || [ -z "$url" ]; then
        log_error "[NOTIFY] Invalid webhook destination config: ${name:-unknown}"
        return 64
    fi

    text=$(format_webhook_text "$title" "$severity" "$message")
    if ! payload=$(build_webhook_payload "$provider" "$text"); then
        log_error "[NOTIFY] Unsupported webhook provider for ${name}: ${provider}"
        return 64
    fi

    if curl --fail --connect-timeout 20 --max-time 30 --retry 2 \
        -s -o /dev/null -X POST -H 'Content-Type: application/json' \
        -d "$payload" "$url"; then
        log "[NOTIFY] Webhook delivered to ${name}: ${title}"
    else
        log_error "[NOTIFY] Webhook delivery failed for ${name}: ${title}"
        return 1
    fi
}

post_webhook_destinations() {
    local title="$1"
    local severity="$2"
    local message="$3"
    shift 3

    local destination failures=0
    for destination in "$@"; do
        post_webhook_destination "$destination" "$title" "$severity" "$message" || failures=$((failures + 1))
    done

    [ "$failures" -eq 0 ]
}

render_shell_array_entries() {
    local value
    for value in "$@"; do
        printf '  %q\n' "$value"
    done
}

# Default fleet notification wrapper. Use sparingly — guarded by
# scenario-specific flag files (e.g. .evo-first-setup) so it does NOT fire
# on every cron tick. Fire-and-forget: failures are logged, never fatal.
notify_webhook() {
    local message="$1"
    local title="${2:-EvoBox Install Notification}"
    local severity="${3:-info}"

    post_webhook_destinations "$title" "$severity" "$message" "${WEBHOOK_DESTINATIONS[@]}" || true
}

# Immediate alert for a fatal install event the device cannot repair on its own.
#
# notify_webhook() has no memory, and this runs every 5-minute tick, so the
# same stuck device would page 288 times a day. The first occurrence is sent in
# the tick that hits it; an unresolved block is repeated every six hours, and a
# delivery that failed is tried again after one hour. The stamp lives in
# EVO_CACHE_DIR, which survives a reboot, so a device stuck across restarts does
# not announce itself again on every boot.
#
# Callers drop the stamp with fresh_clear "install_blocked_<key>" once the
# event is gone, so a later recurrence is announced immediately.
#
# The message goes to chat channels: never put a password, token or key in it.
# Fire-and-forget like notify_webhook(): always returns 0.
readonly INSTALL_BLOCKED_TITLE="EvoBox Install Blocked"
readonly INSTALL_BLOCKED_REPEAT_SECONDS=21600
readonly INSTALL_BLOCKED_RETRY_SECONDS=3600
notify_install_blocked() {
    local key="$1"
    local message="$2"
    local op="install_blocked_${key}"

    if fresh_backoff_active "$op" "$INSTALL_BLOCKED_REPEAT_SECONDS"; then
        return 0
    fi

    if post_webhook_destinations "$INSTALL_BLOCKED_TITLE" "critical" "$message" "${WEBHOOK_DESTINATIONS[@]}"; then
        fresh_mark "$op"
    else
        # Not every destination got it. Back-date the stamp so the next try is
        # one retry delay away instead of a full repeat interval.
        mkdir -p "$EVO_CACHE_DIR" 2>/dev/null
        touch -d "@$(( $(date +%s) - INSTALL_BLOCKED_REPEAT_SECONDS + INSTALL_BLOCKED_RETRY_SECONDS ))" \
            "$EVO_CACHE_DIR/${op}.lastrun" 2>/dev/null || true
    fi
    return 0
}

# --- Actionable Tailscale / SSH alerts -------------------------------------
#
# notify_webhook() above is fire-and-forget: it has no memory, so it can only
# be used for one-shot scenarios guarded by a flag file. These three events are
# different — they repeat on every 5-minute tick until a human acts, and they
# also *recover*. observe_tailscale_alert() records this tick's observation,
# flush_tailscale_alerts() reconciles it against a persisted per-destination
# delivery ledger so each destination is told once, reminded only when the
# problem is critical, and told exactly once when it clears.
#
# Only failures a device cannot repair itself belong here. Transient API
# timeouts, blocked SSH migrations and broken receipts retry next tick and stay
# in the log.
readonly TAILSCALE_ALERT_STATE_VERSION=1
readonly TAILSCALE_ALERT_TITLE="EvoBox Tailscale / SSH Alert"
# A *failed* delivery is not retried for an hour; an unresolved critical is
# repeated every six hours. Warnings are announced exactly once per destination.
readonly TAILSCALE_ALERT_RETRY_SECONDS=3600
readonly TAILSCALE_ALERT_CRITICAL_REPEAT_SECONDS=21600
# One tab-separated "EVENT<TAB>failed|healthy<TAB>details<TAB>source" record per
# call, filled during the tick and drained by flush_tailscale_alerts(). An event
# nobody observed keeps whatever the ledger already says about it. A plain
# string, not an associative array: this script is also exercised by the
# self-checks on developer machines still running bash 3.2.
TAILSCALE_ALERT_OBSERVATIONS=""

# Print the ONE complete JSON object that FILE must contain, or return 1.
#
# `jq -s` (slurp) is what makes this a whole-file check, and it is the only
# form these callers may use. Plain `jq <filter> file` treats the file as a
# STREAM: it applies the filter to every document it finds, so a receipt or an
# API body built from two concatenated objects passes a validation that only
# looks at the last one, and a later `jq -r .field` on the same file then
# prints one line per document — the caller reads field A from one document and
# field B from the other. A valid prefix with trailing garbage fails to parse
# outright, and an array or scalar fails the type test. Callers must work from
# the value printed here and never re-read the raw file.
_tailscale_json_single_object() {
    local out
    out=$(jq -sec '
        if length == 1 then .[0] else empty end
        | select(type == "object")' "$1" 2>/dev/null) || return 1
    [ -n "$out" ] || return 1
    printf '%s\n' "$out"
}

_tailscale_alert_severity() {
    case "$1" in
        SSH_UNAVAILABLE) printf 'critical' ;;
        *) printf 'warning' ;;
    esac
}

# The one thing the operator should actually do. Fixed text: the device has
# already established it cannot fix this itself.
_tailscale_alert_action() {
    case "$1" in
        SSH_UNAVAILABLE) printf 'SSH down on device; check via VNC or on-site' ;;
        NAME_REPAIR_SKIPPED) printf 'Fix in Tailscale Admin Console: delete stale node, rename current to canonical' ;;
        TAILSCALE_AUTH_BLOCKED) printf 'Approve device or check OAuth client scope devices:core' ;;
        *) printf 'Investigate on device' ;;
    esac
}

# observe_tailscale_alert EVENT OBSERVATION DETAILS [SOURCE]
# OBSERVATION is failed|healthy. A branch that never ran must NOT call this:
# no observation means "unchanged", which is not the same as healthy. Always
# returns 0 — observation must never alter a repair path's control flow.
#
# SOURCE names the independent path that made the observation ("status", or
# "api:GET device/<id>"). One event can be raised by several paths at once —
# TAILSCALE_AUTH_BLOCKED comes from both the backend state and the device API —
# and a healthy result from ONE path is no evidence about the others, so it
# clears only its own source. The event stays open while any source is failing.
observe_tailscale_alert() {
    local event="$1" observation="$2" details="${3:-}" source="${4:-default}"

    case "$event" in
        SSH_UNAVAILABLE|NAME_REPAIR_SKIPPED|TAILSCALE_AUTH_BLOCKED) ;;
        *)
            log_error "[ALERT] Ignoring unknown alert event: ${event:-<empty>}"
            return 0
            ;;
    esac

    case "$observation" in
        failed|healthy) ;;
        *)
            log_error "[ALERT] Ignoring unknown observation for ${event}: ${observation:-<empty>}"
            return 0
            ;;
    esac

    # The source becomes a JSON object key and a record field: keep it to a
    # bounded, delimiter-free character set.
    source=$(printf '%s' "$source" | tr -c 'A-Za-z0-9:._/ -' '_')
    [ -n "$source" ] || source="default"
    [ "${#source}" -gt 80 ] && source="${source:0:80}"

    # DETAILS reaches a chat channel: one line, bounded, and never a URL or a
    # token even if a caller is careless with what it interpolated. Tabs go too
    # — they delimit the record below.
    details=$(printf '%s' "$details" | tr '\n\r\t' '   ' \
        | sed -E 's#[a-zA-Z][a-zA-Z0-9+.-]*://[^[:space:]]*#[redacted-url]#g')
    [ "${#details}" -gt 200 ] && details="${details:0:200}"

    TAILSCALE_ALERT_OBSERVATIONS="${TAILSCALE_ALERT_OBSERVATIONS}${event}	${observation}	${details}	${source}
"
    return 0
}

# The ledger this tick works with. A rehearsal (EVO_TEST_WEBHOOK_DESTINATION)
# gets its OWN file: the ledger records what each destination was already told,
# so a rehearsal sharing the production file could mark a real alert announced
# and silence the page that follows -- or, if it is interrupted between
# observing and delivering, leave an entry that the next production tick sends
# to the fleet channels. Separate files make a rehearsal unable to read or
# write production bookkeeping at all, while the formal path is unchanged.
_tailscale_alert_state_path() {
    if [ -n "${EVO_TEST_WEBHOOK_DESTINATION:-}" ]; then
        printf '%s/tailscale-alerts.rehearsal.json' "$EVO_CACHE_DIR"
    else
        printf '%s/tailscale-alerts.json' "$EVO_CACHE_DIR"
    fi
}

# Read the ledger at $1 and print it back as {version, events} ONLY when every
# part of it matches the schema this code writes. Returns 1 (printing nothing)
# for anything else.
#
# A version check alone is not enough. Every field below is used as a decision
# input: `active` selects what goes into a message, `announced` decides whether
# a destination has already been paged, and the two timestamps drive the retry
# and repeat windows. A string where a boolean belongs, or a negative/"1"
# timestamp, makes jq's comparisons answer something plausible instead of
# failing — so a hand-edited or partially-written ledger could silence a page
# or repeat one forever. Unknown event keys are rejected for the same reason:
# this device only ever writes the three it knows how to close.
_tailscale_alert_state_document() {
    local raw out
    raw=$(_tailscale_json_single_object "$1") || return 1
    out=$(printf '%s' "$raw" | jq -c --argjson v "$TAILSCALE_ALERT_STATE_VERSION" '
        def stamp_ok: (. == null) or ((type == "number") and (. >= 0));
        def delivery_ok:
            (type == "object")
            and ((.announced | type) == "boolean")
            and (.last_attempt_at | stamp_ok)
            and (.last_sent_at | stamp_ok)
            # Semantics, not just types. "announced" means a message for this
            # event reached this destination, and the only record of when that
            # happened is last_sent_at: announced with no send time cannot be
            # aged out of the critical repeat window, and a send time without
            # the announcement would re-page an operator who was already told.
            # A send is always an attempt, and an attempt can only be newer
            # than the last success, so a last_sent_at without a last_attempt_at
            # at least as recent is a ledger nothing here could have written.
            and (if .announced then (.last_sent_at != null) else (.last_sent_at == null) end)
            and ((.last_sent_at == null)
                 or ((.last_attempt_at != null) and (.last_attempt_at >= .last_sent_at)));
        def event_ok:
            (type == "object")
            and ((.active | type) == "boolean")
            and ((.details | type) == "string")
            and ((has("sources") | not)
                 or (((.sources | type) == "object")
                     and ((.sources | to_entries | map((.value | type) == "boolean") | all))))
            and ((.deliveries | type) == "object")
            and ((.deliveries | to_entries | map(.value | delivery_ok) | all));
        if (.version == $v)
           and ((.events | type) == "object")
           and ((.events | keys_unsorted
                 | map(. == "SSH_UNAVAILABLE"
                       or . == "NAME_REPAIR_SKIPPED"
                       or . == "TAILSCALE_AUTH_BLOCKED") | all))
           and ((.events | to_entries | map(.value | event_ok) | all))
        then {version: .version, events: .events}
        else empty end' 2>/dev/null) || return 1
    [ -n "$out" ] || return 1
    printf '%s\n' "$out"
}

# Every TAILSCALE_AUTH_BLOCKED source this device still owes a probe.
#
# Two situations qualify, and the second is the one that is easy to miss. A
# source that is still failing obviously has to be re-read. But a source that
# went healthy and whose RECOVERY HAS NOT BEEN DELIVERED YET is equally
# unsettled: the operator has been told the path is broken and has not been
# told it is fixed, so the announcement on file is still what they believe.
# If nothing re-reads that path while the recovery is queued, a relapse in the
# same window is invisible and the next successful flush sends a "Recovered"
# for a path that is failing again. So the recorded sources stay on the event
# (set to false, not deleted) until the recovery actually goes out, and they
# are replayed until then — a relapse re-marks the source failing, which
# cancels the queued recovery instead of letting it lie.
_tailscale_alert_unsettled_sources() {
    local file doc
    file=$(_tailscale_alert_state_path)
    [ -f "$file" ] || return 0
    doc=$(_tailscale_alert_state_document "$file") || return 0
    printf '%s' "$doc" | jq -r '
        (.events.TAILSCALE_AUTH_BLOCKED // empty)
        | . as $event
        | (([ (.deliveries // {}) | .[] | select(.announced == true) ] | length) > 0) as $owed
        | (.sources // {})
        | to_entries[]
        | select((.value == true) or ($owed and ($event.active != true)))
        | .key' 2>/dev/null
    return 0
}

# Relative device API paths whose authorization is unsettled in the ledger this
# run owns. Only GET sources are printed: replaying a POST or a DELETE to
# "prove" recovery would mutate the tailnet, and a 200 on one endpoint is no
# evidence about another. The caller re-validates the shape of each path
# before anything is sent.
_tailscale_alert_blocked_get_paths() {
    local source
    while IFS= read -r source; do
        case "$source" in
            "api:GET device/"*) printf '%s\n' "${source#api:GET }" ;;
        esac
    done <<< "$(_tailscale_alert_unsettled_sources)"
    return 0
}

# Atomic, 0600, same-directory temp + mv. Callers only reach here when the
# rendered state actually differs, so a healthy tick writes nothing to eMMC.
_tailscale_alert_state_write() {
    local content="$1"
    local state_file
    state_file=$(_tailscale_alert_state_path)
    local tmp

    mkdir -p "$EVO_CACHE_DIR" 2>/dev/null
    tmp=$(mktemp "$EVO_CACHE_DIR/.tailscale-alerts.XXXXXX" 2>/dev/null) || {
        log_error "[ALERT] Cannot create a temp file in $EVO_CACHE_DIR; alert state not saved"
        return 1
    }
    # Permissions first, and fail closed: a ledger this function could not
    # restrict must never reach its final name. It records which destination
    # has already been paged, and the cache directory is world-readable.
    if ! chmod 600 "$tmp" 2>/dev/null; then
        rm -f "$tmp"
        log_error "[ALERT] Cannot restrict permissions on the alert state temp file; alert state not saved"
        return 1
    fi
    if ! printf '%s\n' "$content" > "$tmp"; then
        rm -f "$tmp"
        log_error "[ALERT] Failed to write alert state temp file"
        return 1
    fi
    if ! mv -f "$tmp" "$state_file"; then
        rm -f "$tmp"
        log_error "[ALERT] Failed to replace $state_file"
        return 1
    fi
    return 0
}

# Reconcile this tick's observations with the persisted ledger and send at most
# one aggregated message per destination. Never fatal: main() calls it with
# `|| true` and every internal failure degrades to "try again next tick".
#
# EVO_TEST_WEBHOOK_DESTINATION (name|provider|url) replaces the production
# destinations for this function only, and switches the ledger to its own file,
# so an on-device rehearsal cannot page the fleet channels and cannot leave
# bookkeeping behind that a later production tick would act on. No other
# notification path reads it.
flush_tailscale_alerts() {
    local state_file
    state_file=$(_tailscale_alert_state_path)
    local state original_state now event

    # Nothing observed and no ledger: the overwhelmingly common tick. No jq, no
    # stat churn, no write.
    if [ -z "$TAILSCALE_ALERT_OBSERVATIONS" ] && [ ! -f "$state_file" ]; then
        return 0
    fi

    if ! command -v jq > /dev/null 2>&1; then
        log_error "[ALERT] jq is unavailable; skipping alert bookkeeping this tick"
        return 0
    fi

    if [ -f "$state_file" ]; then
        # A corrupt, foreign-version or off-schema ledger is left exactly as
        # found: we cannot tell what was already announced, so announcing again
        # (or silently discarding a recovery) would both be wrong. Two
        # concatenated ledgers are exactly that case — the second one would
        # decide which destination has already been paged — so the whole file
        # is rejected rather than reduced to its last document.
        if ! state=$(_tailscale_alert_state_document "$state_file"); then
            log_error "[ALERT] $state_file is unreadable, not version ${TAILSCALE_ALERT_STATE_VERSION}, or does not match the alert ledger schema; leaving it untouched and sending nothing this tick"
            return 0
        fi
    else
        state=$(jq -nc --argjson v "$TAILSCALE_ALERT_STATE_VERSION" '{version: $v, events: {}}') || return 0
    fi
    original_state="$state"

    now=$(date -u +%s)
    [[ "$now" =~ ^[0-9]+$ ]] || {
        log_error "[ALERT] Cannot read the current time; skipping alert bookkeeping this tick"
        return 0
    }

    # A tick can observe the same event from two code paths (the backend state
    # and the device API both feed TAILSCALE_AUTH_BLOCKED). Each path is tracked
    # as its own source: a failure from one source keeps the event open even
    # when another source reported healthy in the same tick, and a healthy
    # result only ever clears the source that produced it.
    local failed_pairs="" observation details source
    while IFS="$(printf '\t')" read -r event observation details source; do
        [ "$observation" = "failed" ] || continue
        [ -n "$source" ] || source="default"
        case "|${failed_pairs}|" in
            *"|${event}::${source}|"*) ;;
            *) failed_pairs="${failed_pairs}|${event}::${source}" ;;
        esac
    done <<< "$TAILSCALE_ALERT_OBSERVATIONS"

    while IFS="$(printf '\t')" read -r event observation details source; do
        [ -z "$event" ] && continue
        [ -n "$source" ] || source="default"
        if [ "$observation" = "healthy" ]; then
            case "|${failed_pairs}|" in
                *"|${event}::${source}|"*) continue ;;
            esac
            # An event we never recorded needs no node: a device that was
            # always fine must not create state. A ledger written before
            # sources existed carries none, and is cleared wholesale.
            #
            # A cleared source is kept as `false` rather than deleted. The
            # node survives until its recovery has actually been delivered,
            # and while it does, that list is the only record of which
            # read-only paths have to keep being probed to notice a relapse
            # before the operator is told the problem is over
            # (_tailscale_alert_unsettled_sources). The whole node is dropped
            # once the recovery lands, so nothing accumulates.
            state=$(printf '%s' "$state" | jq -c --arg e "$event" --arg s "$source" '
                if (.events[$e] == null) then .
                elif ((.events[$e].sources // null) | type) == "object"
                then (.events[$e].sources[$s] = false
                      | .events[$e].active =
                          (([ .events[$e].sources | .[] | select(. == true) ] | length) > 0))
                else .events[$e].active = false
                end') || return 0
        else
            # Re-failing before its recovery went out keeps announced as-is, so
            # the destination is not told twice about the same open issue.
            state=$(printf '%s' "$state" | jq -c --arg e "$event" --arg d "$details" --arg s "$source" \
                '.events[$e] = ((.events[$e] // {})
                    | .deliveries = (.deliveries // {})
                    | .sources = ((.sources // {}) | .[$s] = true)
                    | .active = true
                    | .details = $d)') || return 0
        fi
    done <<< "$TAILSCALE_ALERT_OBSERVATIONS"

    # Drop resolved events nobody was ever told about — including self-healed
    # ones that never reached a destination.
    state=$(printf '%s' "$state" | jq -c \
        '.events |= with_entries(select((.value.active == true)
            or ([(.value.deliveries // {}) | .[] | select(.announced == true)] | length) > 0))') || return 0

    # Sending is the abortable part: a webhook can block for 30s per
    # destination. Record the observations, then leave delivery to the next
    # tick rather than risk the watchdog killing the tick mid-notification.
    if ! watchdog_headroom_available 300; then
        log "[ALERT] Deferring alert delivery — only ${WATCHDOG_HEADROOM_SECONDS:-unreadable}s of watchdog headroom left"
        [ "$state" != "$original_state" ] && _tailscale_alert_state_write "$state"
        return 0
    fi

    local destinations=()
    if [ -n "${EVO_TEST_WEBHOOK_DESTINATION:-}" ]; then
        # The rehearsal ledger is a separate file, so this can no longer corrupt
        # production bookkeeping -- but a rehearsal that answers to a production
        # destination's NAME still produces messages and log lines an operator
        # cannot tell apart from the real channel's. That ambiguity is the whole
        # point of the rehearsal, so the run is refused; the observations
        # recorded above are kept, and a correctly named rehearsal (or the next
        # production tick) still delivers them.
        local test_name formal formal_name
        test_name="${EVO_TEST_WEBHOOK_DESTINATION%%|*}"
        for formal in "${WEBHOOK_DESTINATIONS[@]}"; do
            formal_name="${formal%%|*}"
            if [ -n "$test_name" ] && [ "$test_name" = "$formal_name" ]; then
                log_error "[ALERT] EVO_TEST_WEBHOOK_DESTINATION name '${test_name}' collides with a production destination; sending nothing"
                [ "$state" != "$original_state" ] && _tailscale_alert_state_write "$state"
                return 0
            fi
        done
        destinations=("$EVO_TEST_WEBHOOK_DESTINATION")
    else
        destinations=("${WEBHOOK_DESTINATIONS[@]}")
    fi

    local destination dest_name due_open_events recovered_events active_events
    local body severity outcome due_json recovered_json listed_json line
    # What the ledger on disk currently says. Everything up to here has only
    # been held in memory, so that is still the pre-tick file (or, when no file
    # exists yet, the empty document standing in for it).
    local persisted_state="$original_state"
    for destination in "${destinations[@]}"; do
        dest_name="${destination%%|*}"
        if [ -z "$dest_name" ] || [ "$dest_name" = "$destination" ]; then
            log_error "[ALERT] Skipping malformed webhook destination entry"
            continue
        fi

        # Two different questions, deliberately kept apart:
        #   * WHAT MAKES THIS DESTINATION DUE a message right now — a newly
        #     opened event, a critical one past its repeat window, or a
        #     recovery it is owed;
        #   * WHAT IS ACTUALLY WRONG with the device right now — every active
        #     event, including warnings this destination was already told
        #     about.
        # Only the first drives delivery bookkeeping; the second is what the
        # message has to say. Reporting only the due events would hand the
        # operator a partial picture: a device with SSH down and an open name
        # conflict would page "name conflict", then page "SSH down" and never
        # mention the name conflict again.
        #
        # An attempt that FAILED holds the destination off for an hour; a
        # successful send does not (last_attempt_at == last_sent_at then), so a
        # recovery five minutes after an announcement still goes out.
        due_open_events=$(printf '%s' "$state" | jq -r --arg d "$dest_name" \
            --argjson now "$now" \
            --argjson retry "$TAILSCALE_ALERT_RETRY_SECONDS" \
            --argjson repeat "$TAILSCALE_ALERT_CRITICAL_REPEAT_SECONDS" '
            .events | to_entries[]
            | .key as $key
            | ((.value.deliveries // {})[$d] // {}) as $dl
            | select(.value.active == true)
            | select(($dl.last_attempt_at // null) == null
                or (($dl.last_sent_at // null) != null and $dl.last_attempt_at <= $dl.last_sent_at)
                or ($now - $dl.last_attempt_at) >= $retry)
            | select(($dl.announced != true)
                or ($key == "SSH_UNAVAILABLE"
                    and ($dl.last_sent_at // null) != null
                    and ($now - $dl.last_sent_at) >= $repeat))
            | $key') || {
            log_error "[ALERT] Could not select the open events for ${dest_name}; sending nothing this tick"
            return 0
        }

        recovered_events=$(printf '%s' "$state" | jq -r --arg d "$dest_name" \
            --argjson now "$now" \
            --argjson retry "$TAILSCALE_ALERT_RETRY_SECONDS" '
            .events | to_entries[]
            | ((.value.deliveries // {})[$d] // {}) as $dl
            | select(.value.active != true)
            | select($dl.announced == true)
            | select(($dl.last_attempt_at // null) == null
                or (($dl.last_sent_at // null) != null and $dl.last_attempt_at <= $dl.last_sent_at)
                or ($now - $dl.last_attempt_at) >= $retry)
            | .key') || {
            log_error "[ALERT] Could not select the recovered events for ${dest_name}; sending nothing this tick"
            return 0
        }

        [ -z "$due_open_events" ] && [ -z "$recovered_events" ] && continue

        active_events=$(printf '%s' "$state" | jq -r '
            .events | to_entries[] | select(.value.active == true) | .key') || {
            log_error "[ALERT] Could not select the active events for ${dest_name}; sending nothing this tick"
            return 0
        }

        body=""
        severity="info"
        if [ -n "$active_events" ]; then
            body="Open issues:"
            while IFS= read -r line; do
                [ -z "$line" ] && continue
                details=$(printf '%s' "$state" | jq -r --arg e "$line" '.events[$e].details // ""') || {
                    log_error "[ALERT] Could not read the details for ${line}; sending nothing this tick"
                    return 0
                }
                body="${body}"$'\n'"- ${line}: ${details:-no details} | $(_tailscale_alert_action "$line")"
                if [ "$(_tailscale_alert_severity "$line")" = "critical" ]; then
                    severity="critical"
                elif [ "$severity" != "critical" ]; then
                    severity="warning"
                fi
            done <<< "$active_events"
        fi
        if [ -n "$recovered_events" ]; then
            [ -n "$body" ] && body="${body}"$'\n'
            body="${body}Recovered:"
            while IFS= read -r line; do
                [ -z "$line" ] && continue
                body="${body}"$'\n'"- ${line}: resolved"
            done <<< "$recovered_events"
        fi
        # A truncated body no longer proves which events the operator can read,
        # so only the events this destination was actually due are credited
        # below; everything still open stays unannounced and pages next tick.
        listed_json="[]"
        if [ "${#body}" -gt 1900 ]; then
            body="${body:0:1887}"$'\n[truncated]'
        else
            listed_json=$(printf '%s' "$active_events" | jq -R -s -c 'split("\n") | map(select(length > 0))') || continue
        fi

        if post_webhook_destination "$destination" "$TAILSCALE_ALERT_TITLE" "$severity" "$body"; then
            outcome="sent"
        else
            outcome="failed"
            log_error "[ALERT] Alert delivery to ${dest_name} failed; retrying in ${TAILSCALE_ALERT_RETRY_SECONDS}s at the earliest"
        fi

        # A delivered message is the announcement for every open event it
        # listed, not only for the ones that made the destination due. An event
        # whose own attempt failed an hour ago is held off from *triggering* a
        # send, but once another event triggers one it is in the body the
        # operator reads -- crediting it here is what stops the same open issue
        # being paged again later as if it were new.
        #
        # An already-announced event that merely rode along keeps its existing
        # timestamps: rewriting them would keep resetting the retry and repeat
        # windows that govern it. A failed send announces nothing and records an
        # attempt only against the events it actually tried to deliver.
        due_json=$(printf '%s' "$due_open_events" | jq -R -s -c 'split("\n") | map(select(length > 0))') || continue
        recovered_json=$(printf '%s' "$recovered_events" | jq -R -s -c 'split("\n") | map(select(length > 0))') || continue
        state=$(printf '%s' "$state" | jq -c --arg d "$dest_name" --argjson now "$now" \
            --argjson due "$due_json" --argjson recovered "$recovered_json" \
            --argjson listed "$listed_json" --arg outcome "$outcome" '
            . as $before
            | (if $outcome == "sent"
               then [ $listed[]
                      | . as $k
                      | select((($before.events[$k].deliveries // {})[$d].announced // false) != true) ]
               else [] end) as $ride
            | ($due + $ride | unique) as $announce
            | reduce ($announce + $recovered)[] as $e (.;
                .events[$e].deliveries = ((.events[$e].deliveries // {}))
                | .events[$e].deliveries[$d] =
                    (((.events[$e].deliveries[$d]) // {announced: false, last_attempt_at: null, last_sent_at: null})
                     | .last_attempt_at = $now
                     | if $outcome == "sent"
                       then (if (($announce | index($e)) != null)
                             # An open event this message announced: the send
                             # time is what the repeat window is measured from.
                             then .announced = true | .last_sent_at = $now
                             # A DELIVERED RECOVERY. The destination no longer
                             # holds an open announcement, so "announced" goes
                             # false — and the timestamps that only mean
                             # something alongside an announcement go with it.
                             # Leaving last_sent_at set writes a row the ledger
                             # validator rejects (announced false with a send
                             # time), which makes the whole file unreadable from
                             # the next tick on: no page is ever delivered
                             # again, and the name-reconciliation shortcut stays
                             # blocked forever. The row is kept rather than
                             # dropped so the pruning below still sees which
                             # destinations were told, and a partially
                             # delivered recovery is finished by a later tick
                             # from a document that still loads.
                             else .announced = false
                                  | .last_sent_at = null
                                  | .last_attempt_at = null end)
                       else . end))') || return 0

        # Persist this destination's row BEFORE talking to the next one. A
        # watchdog kill (or a power cut) between two destinations would
        # otherwise discard the fact that this one was already paged, and the
        # next tick would send it the same alert again — or, after a recovery,
        # re-announce an event it had already been told about. The writer only
        # runs when the rendered ledger actually changed, so a tick that sends
        # nothing still writes nothing.
        if [ "$state" != "$persisted_state" ]; then
            if _tailscale_alert_state_write "$state"; then
                persisted_state="$state"
            else
                # Bookkeeping we cannot save must not be extended: every further
                # send this tick would be equally unrecorded and equally likely
                # to repeat next tick. Stop here and let the next tick redo it.
                log_error "[ALERT] Could not persist the delivery ledger after ${dest_name}; stopping further deliveries this tick"
                break
            fi
        fi
    done

    # A recovery that reached every destination that knew about the event
    # retires the event node entirely.
    state=$(printf '%s' "$state" | jq -c \
        '.events |= with_entries(select((.value.active == true)
            or ([(.value.deliveries // {}) | .[] | select(.announced == true)] | length) > 0))') || return 0

    # Compared against what is actually on disk, not against the pre-tick
    # document: the per-destination writes above may already have saved most of
    # this, and an interrupted tick that stopped early still gets one last
    # chance to save the pruning here.
    if [ "$state" != "$persisted_state" ]; then
        _tailscale_alert_state_write "$state"
    fi
    return 0
}

# Send the one-time "plugged in, starting deployment" notification.
# Guarded by $HOME/.evo-first-setup so it fires exactly once per device.
notify_first_setup_once() {
    local flag="$HOME/.evo-first-setup"
    [ -f "$flag" ] && return 0

    notify_webhook "EvoBox plugged into the network, starting deployment. Do not unplug it until you see the deployment finished message."
    touch "$flag"
}

# Send the one-time "deployment finished" notification after the first
# successful end-to-end install run. Guarded by $HOME/.evo-first-setup-done
# so it fires exactly once per device.
notify_first_setup_finish_once() {
    local flag="$HOME/.evo-first-setup-done"
    [ -f "$flag" ] && return 0

    notify_webhook "EvoBox deployment finished, ready to be shipped. Reboot the device once before testing."
    touch "$flag"
}

# Fire a webhook if this device is still on the legacy nohup-managed daemon
# (no systemd unit installed). Silent no-op on systemd hosts — the common
# case — so this is safe to invoke every tick. Rate-limited to one
# notification per NOHUP_NOTIFY_RATE_LIMIT seconds via a tmpfs state file.
#
# Deliberately called BEFORE the flock check in main() so it fires even on
# devices with a stuck fd-200 lock (the exact population we want to surface).
# Failures are fire-and-forget and never fatal.
readonly NOHUP_NOTIFY_RATE_LIMIT=3600
readonly NOHUP_NOTIFY_STATE_FILE="/tmp/evo-nohup-last-notified"
notify_if_nohup_mode() {
    # Systemd-managed host → silent no-op.
    if [ -f /etc/systemd/system/evo-obs-daemon.service ]; then
        return 0
    fi

    # Rate-limit: skip if we notified recently. /tmp is tmpfs so this resets
    # on reboot, which is desirable — one notification per boot cycle.
    local now last=0
    now=$(date +%s)
    [ -f "$NOHUP_NOTIFY_STATE_FILE" ] && last=$(cat "$NOHUP_NOTIFY_STATE_FILE" 2>/dev/null || echo 0)
    if [ $((now - last)) -lt "$NOHUP_NOTIFY_RATE_LIMIT" ]; then
        return 0
    fi

    local lock_holders last_install_end
    lock_holders=$(fuser "$LOCKFILE" 2>/dev/null | tr -s ' ' | head -c 120)
    [ -z "$lock_holders" ] && lock_holders="(none)"
    last_install_end=$(grep -a 'INSTALL END' "$EVOSPORTS_INSTALL_LOG" 2>/dev/null | tail -1 | head -c 160)
    [ -z "$last_install_end" ] && last_install_end="(never)"

    notify_webhook "Legacy nohup mode detected (no systemd unit). Lock holders: ${lock_holders}. Last INSTALL END: ${last_install_end}" \
        "EvoBox Legacy Daemon Notice" "warning"

    # Record notification time regardless of webhook success — a broken
    # webhook must not cause a notification storm when it recovers.
    echo "$now" > "$NOHUP_NOTIFY_STATE_FILE" 2>/dev/null || true
}

# Detect whether this device is on an unrestricted network, a Mainland China
# network (Great Firewall), or has no internet at all. Uses symmetric 204
# captive-portal endpoints (cheap: no response body, plain HTTP, designed
# by Android OEMs to always be reachable on their respective networks).
#
# Returns (via exit code):
#   0 — UNRESTRICTED  (Google reachable) — proceed with full install
#   1 — CHINA         (Google unreachable, at least one China probe reachable)
#   2 — NO_INTERNET   (nothing reachable)
check_network_region() {
    local probe_google="http://www.google.com/generate_204"
    local probe_cn_primary="http://connectivitycheck.platform.hicloud.com/generate_204"
    local probe_cn_fallback="http://connect.rom.miui.com/generate_204"

    local code
    code=$(curl -s -o /dev/null -w '%{http_code}' \
        --connect-timeout 5 --max-time 8 --retry 0 --max-redirs 0 \
        "$probe_google" 2>/dev/null)
    if [ "$code" = "204" ]; then
        log "[REGION] Probe: google=204 → UNRESTRICTED"
        return 0
    fi

    local cn_code
    cn_code=$(curl -s -o /dev/null -w '%{http_code}' \
        --connect-timeout 5 --max-time 8 --retry 0 --max-redirs 0 \
        "$probe_cn_primary" 2>/dev/null)
    if [ "$cn_code" = "204" ]; then
        log "[REGION] Probe: google=${code:-none}, huawei=204 → CHINA"
        return 1
    fi

    local cn_code2
    cn_code2=$(curl -s -o /dev/null -w '%{http_code}' \
        --connect-timeout 5 --max-time 8 --retry 0 --max-redirs 0 \
        "$probe_cn_fallback" 2>/dev/null)
    if [ "$cn_code2" = "204" ]; then
        log "[REGION] Probe: google=${code:-none}, huawei=${cn_code:-none}, xiaomi=204 → CHINA"
        return 1
    fi

    log "[REGION] Probe: google=${code:-none}, huawei=${cn_code:-none}, xiaomi=${cn_code2:-none} → NO_INTERNET"
    return 2
}

# `sudo install -d` on OBSERVABILITY_STATE_DIR created any missing parent as
# root:root 0755. A device with no ~/.local/state before the observability
# cutover (evobox-oem-0063) was left unable to write the identity backup or the
# APT lock state, so the identity guard skipped every daemon version check.
# Hand the two parents back; only the directories themselves, not their
# contents. Steady state is two tests and no writes.
ensure_local_state_owner() {
    local d owner me
    me="$(id -un)"
    for d in "$HOME/.local" "$HOME/.local/state"; do
        [ -d "$d" ] && [ ! -O "$d" ] || continue
        owner="$(stat -c '%U:%G' "$d" 2>/dev/null)"
        if sudo chown "$me:$(id -gn)" "$d"; then
            log "[LOCAL-STATE] $d was owned by ${owner:-unknown}; returned to $me"
        else
            log_error "[LOCAL-STATE] Cannot return $d (owned by ${owner:-unknown}) to $me"
        fi
    done
}

# True only when a NOPASSWD rule is in effect right now.
#
# A bare `sudo -n true` is not that test. It also passes on a warm credential
# cache, and sync_device_config's `sudo -S` leaves one behind. On a fresh OEM
# device the first tick therefore saw "passwordless sudo works", skipped writing
# /etc/sudoers.d/evobox-nopasswd, and then failed every sudo call that the
# cache did not reach (child scripts, `timeout` wrappers, later steps) with
# "a password is required" until the next tick (evobox-oem-0189). `-k` makes
# sudo ignore cached credentials for this one call and leaves the cache alone.
sudo_nopasswd_active() {
    sudo -k -n true 2>/dev/null
}

ensure_sudo_nopasswd() {
    if sudo_nopasswd_active; then
        return 0
    fi

    log "[SUDO] NOPASSWD not configured, attempting setup..."

    # Iterate CFG_HISTORY newest-first. sync_device_config runs immediately
    # before this in main() and normally aligns the device with
    # CFG_HISTORY[-1] (the target), so the first attempt usually wins.
    # Falling back through older entries covers OEM-first-boot and partially
    # synchronized devices.
    local i try_cfg
    for (( i=${#CFG_HISTORY[@]}-1; i>=0; i-- )); do
        try_cfg=$(parse_config "${CFG_HISTORY[i]}")
        if [ -z "$try_cfg" ]; then
            continue
        fi

        if echo "$try_cfg" | sudo -S bash -c \
            'echo "evobox ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/evobox-nopasswd && chmod 440 /etc/sudoers.d/evobox-nopasswd' 2>/dev/null; then
            if sudo_nopasswd_active; then
                log "[SUDO] NOPASSWD configured successfully"
                return 0
            fi
            echo "$try_cfg" | sudo -S rm -f /etc/sudoers.d/evobox-nopasswd 2>/dev/null
        fi
    done

    log_error "[SUDO] Failed to configure NOPASSWD — no CFG_HISTORY entry accepted by sudo."
    return 1
}

# Check if a package is installed
check_package_installed() {
    dpkg -l "$1" &> /dev/null
    return $?
}

# Read the installed Mesa runtime family without consulting apt's candidates.
# Development header packages are deliberately excluded: they do not affect OBS
# or VA-API at runtime, and Intel can retire an individual `*-dev` binary while
# the corresponding runtime packages remain current. The binary package field is
# otherwise retained verbatim so multiarch rows remain distinct.
mesa_family_inventory() {
    dpkg-query -W -f='${binary:Package}\t${db:Status-Abbrev}\t${source:Package}\t${source:Version}\n' 2>/dev/null \
        | awk -F '\t' '$3 == "mesa" && $1 !~ /-dev(:[[:alnum:]]+)?$/ { print $1 "\t" substr($2, 1, 2) "\t" $4 }'
}

# Print healthy, inconsistent, or unknown for one Mesa inventory snapshot. Every
# row is scanned before any verdict, so the outcome does not depend on row order:
# malformed metadata anywhere means unknown, and unknown outranks inconsistent.
# Bash-only on purpose — this runs on every five-minute tick, fleet-wide.
#
# Classification is on the SECOND character of the status abbreviation (the
# current state), not the whole pair: the first character is only the desired
# action. Matching "ii" verbatim would call a held-but-installed package ("hi") a
# fault, and since a plain apt-get install does not clear a dpkg hold selection,
# the post-repair verification would fail forever on the same device.
mesa_family_state() {
    local package status version
    local first_version=""
    local consistent=true
    local unknown=false

    while IFS=$'\t' read -r package status version; do
        [ -n "$package" ] || { unknown=true; continue; }
        if mesa_status_is_absent "$status"; then
            continue
        fi
        case "$status" in
            ?i) ;;                                # installed, hold included
            *) consistent=false; continue ;;      # H/U/F/W/t: transaction fault
        esac
        [ -n "$version" ] || { unknown=true; continue; }
        first_version="${first_version:-$version}"
        [ "$version" = "$first_version" ] || consistent=false
    done <<< "$1"

    if [ "$unknown" = true ]; then
        printf 'unknown\n'
    elif [ "$consistent" != true ]; then
        printf 'inconsistent\n'
    elif [ -n "$first_version" ]; then
        printf 'healthy\n'
    else
        printf 'unknown\n'   # nothing installed: rc-only, or no Mesa rows at all
    fi
}

# The absent status rule is shared by classification and operand selection. Keep
# it in one place: a dpkg row whose second status character is c or n is absent,
# not a package that repair should reinstall.
mesa_status_is_absent() {
    case "$1" in
        ?[cn]) return 0 ;;
        *) return 1 ;;
    esac
}

# Print every Mesa package that is present in any form — installed, held, or left
# half-installed by a broken transaction. A faulted row is exactly what needs to
# be an operand. No version is ever passed to apt; apt resolves the current
# repository movement and any newly split deps.
mesa_family_operands() {
    local package status version
    while IFS=$'\t' read -r package status version; do
        [ -n "$package" ] || continue
        mesa_status_is_absent "$status" || printf '%s\n' "$package"
    done <<< "$1"
}

# Shared hostname bucket: the crontab runs at five-minute granularity, so each
# host gets one stable slot in a 72-slot (six-hour) window.
stagger_bucket_is_due() {
    (( $(date +%s) / 300 % 72 == $(hostname | cksum | cut -d' ' -f1) % 72 ))
}

# Whole seconds of uptime, monotonic and immune to the NTP steps that
# configure_time_synchronization() can make mid-tick. Fractions are dropped:
# nothing here needs sub-second resolution, and integers keep every consumer on
# bash arithmetic instead of forking awk on the every-5-minutes path.
read_uptime_seconds() {
    local up _
    read -r up _ < "$EVO_UPTIME_PATH" 2>/dev/null || return 1
    up="${up%.*}"
    [[ "$up" =~ ^[0-9]+$ ]] || return 1
    printf '%s\n' "$up"
}

# Return true only when the watchdog has at least five minutes left. Sets
# WATCHDOG_HEADROOM_SECONDS so a deferral can log how much was actually left.
# $1 (optional) raises the floor above the 300s default, for a caller whose next
# step is itself long and unabortable. Headroom only ever shrinks inside a tick,
# so a late re-check cannot rescue a step that has already started.
watchdog_headroom_available() {
    local now floor="${1:-300}"
    WATCHDOG_HEADROOM_SECONDS=""
    [[ "${WATCHDOG_UPTIME_BASELINE:-}" =~ ^[0-9]+$ ]] || return 1
    now="$(read_uptime_seconds)" || return 1
    WATCHDOG_HEADROOM_SECONDS=$(( LOCK_TIMEOUT - (now - WATCHDOG_UPTIME_BASELINE) ))
    [ "$WATCHDOG_HEADROOM_SECONDS" -ge "$floor" ]
}

# Filled by diagnose_mesa_package_family(); read by repair_mesa_package_family().
# Set on EVERY tick, so the repair always works from this tick's snapshot.
MESA_FAMILY_DIAGNOSIS_INVENTORY=""
MESA_FAMILY_DIAGNOSIS_STATE="unknown"

# Read-only Mesa diagnosis entry point. Only the actionable state reaches the
# install log: this runs 288x/day on every device, and log_debug()'s contract
# covers exactly this kind of per-tick no-change confirmation.
diagnose_mesa_package_family() {
    MESA_FAMILY_DIAGNOSIS_INVENTORY="$(mesa_family_inventory)"
    MESA_FAMILY_DIAGNOSIS_STATE="$(mesa_family_state "$MESA_FAMILY_DIAGNOSIS_INVENTORY")"
    if [ "$MESA_FAMILY_DIAGNOSIS_STATE" = "inconsistent" ]; then
        log "[PACKAGE-DIAGNOSTIC] Mesa packages: $MESA_FAMILY_DIAGNOSIS_STATE"
    else
        log_debug "[PACKAGE-DIAGNOSTIC] Mesa packages: $MESA_FAMILY_DIAGNOSIS_STATE"
    fi
}

# Render-stack evidence is deliberately collected on every tick. These helpers
# never restart X/OBS or invoke apt; the only state they may write is the
# existing 12-hour notification stamp after a degraded result is reported.
render_stack_log_file_is_encoder_initialized() {
    grep -a -Eiq 'initiali[sz](ing|ed)[[:space:]]+.*encoder|encoder.*initiali[sz](ing|ed)|starting[[:space:]]+encoder|encoder.*started' "$1"
}

# A small OBS log is only a startup failure when its last nonblank line is the
# OpenGL initialization marker. Healthy short fixture logs can contain that
# marker near the beginning, so a simple substring match would be a false alarm.
render_stack_obs_log_stopped_at_opengl_init() {
    tail -c 256 "$1" 2>/dev/null \
        | grep -a -Ev '^[[:space:]]*$' \
        | tail -n 1 \
        | grep -a -Eiq 'Initializing OpenGL\.\.\.[[:space:]]*$'
}

# Return the newest readable OBS text log, optionally requiring an encoder
# initialization marker. The single traversal keeps startup and encoder-fallback
# evidence on the same path, extension, timestamp, and NUL-safe filename rules.
render_stack_newest_obs_log_matching() {
    local log_dir="$1" require_encoder="${2:-false}" file mtime newest="" newest_mtime=-1
    [ -d "$log_dir" ] || return 1
    while IFS= read -r -d '' file; do
        [ -r "$file" ] || continue
        if [ "$require_encoder" = true ] \
            && ! render_stack_log_file_is_encoder_initialized "$file"; then
            continue
        fi
        mtime=$(stat -c %Y "$file" 2>/dev/null)
        [[ "$mtime" =~ ^[0-9]+$ ]] || mtime=0
        if [ -z "$newest" ] || [ "$mtime" -gt "$newest_mtime" ]; then
            newest="$file"
            newest_mtime=$mtime
        fi
    done < <(find "$log_dir" -type f -name '*.txt' -print0 2>/dev/null)
    [ -n "$newest" ] || return 1
    printf '%s\n' "$newest"
}

# Return the newest readable OBS text log. Each filename remains quoted inside
# render_stack_newest_obs_log_matching().
render_stack_newest_obs_log() {
    render_stack_newest_obs_log_matching "$1"
}

# Return the newest OBS log that contains an actual encoder initialization, not
# merely a configuration mention.
render_stack_newest_encoder_log() {
    render_stack_newest_obs_log_matching "$1" true
}

# Read-only R3b diagnosis. A missing or unreadable input is unknown; only an
# observed negative is degraded. This function intentionally has no OBS-running
# guard: software fallback is observable while OBS is serving a live table.
ensure_render_stack_integrity() {
    local xorg_log="${RENDER_STACK_XORG_LOG:-/var/log/Xorg.0.log}"
    local obs_log_dir="${RENDER_STACK_OBS_LOG_DIR:-$HOME/.config/obs-studio/logs}"
    local mesa_state="${MESA_FAMILY_DIAGNOSIS_STATE:-unknown}"
    local mesa_consistent=unknown glamor_ok=unknown vaapi_x11_ok=unknown
    local encoder_fallback=unknown obs_startup_complete=unknown
    local x_identity=unknown reason="" status=healthy
    local x_pid x_ps obs_log obs_size encoder_log vaapi_output vaapi_rc

    case "$mesa_state" in
        healthy) mesa_consistent=true ;;
        inconsistent) mesa_consistent=false ;;
        *) mesa_consistent=unknown ;;
    esac

    if [ -r "$xorg_log" ]; then
        if grep -a -Eiq 'glamor initialization failed' "$xorg_log"; then
            glamor_ok=false
            reason="glamor_failed"
        else
            glamor_ok=true
        fi
    else
        reason="glamor_evidence_missing"
    fi

    if command -v pgrep >/dev/null 2>&1; then
        x_pid=$(pgrep -x Xorg 2>/dev/null | head -n 1)
        if [ -n "$x_pid" ] && command -v ps >/dev/null 2>&1; then
            x_ps=$(ps -o pid=,lstart= -p "$x_pid" 2>/dev/null)
            if [ -n "$x_ps" ]; then
                x_identity="$(printf '%s' "$x_ps" | tr -s '[:space:]' '_')"
            fi
        fi
    fi
    obs_log="$(render_stack_newest_obs_log "$obs_log_dir")"
    if [ -n "$obs_log" ] && [ -r "$obs_log" ]; then
        obs_size=$(wc -c < "$obs_log" 2>/dev/null | tr -d '[:space:]')
        if [[ "$obs_size" =~ ^[0-9]+$ ]] && [ "$obs_size" -le 4096 ] \
            && render_stack_obs_log_stopped_at_opengl_init "$obs_log"; then
            obs_startup_complete=false
            reason="${reason:+$reason+}obs_startup_truncated"
        elif grep -a -Eiq 'Initializing OpenGL\.\.\.' "$obs_log" \
            && grep -a -Eiq 'OpenGL (version|loaded successfully|renderer)' "$obs_log"; then
            obs_startup_complete=true
        else
            reason="${reason:+$reason+}obs_startup_evidence_unknown"
        fi
    else
        reason="${reason:+$reason+}obs_evidence_missing"
    fi

    encoder_log="$(render_stack_newest_encoder_log "$obs_log_dir")"
    if [ -n "$encoder_log" ] && [ -r "$encoder_log" ]; then
        if grep -a -Eiq 'not[[:space:]]+on[[:space:]]+intel[[:space:]]+gpu' "$encoder_log"; then
            encoder_fallback=true
            reason="${reason:+$reason+}encoder_fallback"
        else
            encoder_fallback=false
        fi
    else
        reason="${reason:+$reason+}encoder_evidence_missing"
    fi

    # DISPLAY=:0 is intentional: DRM VA-API can pass while the X11 path used by
    # OBS is poisoned. Bound vainfo so a broken display server cannot consume a
    # whole installer tick; no timeout utility means the evidence is unknown.
    if [ "$x_identity" = unknown ]; then
        reason="${reason:+$reason+}vaapi_x11_display_missing"
    elif command -v vainfo >/dev/null 2>&1 && command -v timeout >/dev/null 2>&1; then
        vaapi_output="$(DISPLAY=:0 timeout 20 vainfo 2>&1)"
        vaapi_rc=$?
        if [ "$vaapi_rc" -eq 124 ]; then
            reason="${reason:+$reason+}vaapi_x11_timeout"
        elif [ "$vaapi_rc" -ne 0 ] \
            && printf '%s' "$vaapi_output" | grep -a -Eiq 'authorization required|cannot open display|can.t open display|failed to open display|no protocol specified'; then
            reason="${reason:+$reason+}vaapi_x11_display_missing"
        elif [ "$vaapi_rc" -ne 0 ]; then
            vaapi_x11_ok=false
            reason="${reason:+$reason+}vaapi_x11_failed"
        elif [ -z "$vaapi_output" ]; then
            reason="${reason:+$reason+}vaapi_x11_evidence_unknown"
        # A DRM attempt can be a fallback after X11 failed; H.264 listed after
        # that attempt is not proof that OBS's X11 path is usable.
        elif printf '%s' "$vaapi_output" | grep -a -Eiq 'trying display:[[:space:]]*drm'; then
            vaapi_x11_ok=false
            reason="${reason:+$reason+}vaapi_x11_failed"
        elif printf '%s' "$vaapi_output" | grep -a -Eiq 'VAProfileH264'; then
            vaapi_x11_ok=true
        else
            vaapi_x11_ok=false
            reason="${reason:+$reason+}vaapi_x11_failed"
        fi
    elif ! command -v vainfo >/dev/null 2>&1; then
        reason="${reason:+$reason+}vaapi_x11_evidence_missing"
    else
        reason="${reason:+$reason+}vaapi_x11_timeout_missing"
    fi

    [ "$mesa_consistent" = true ] || reason="${reason:+$reason+}mesa_${mesa_consistent}"
    [ "$glamor_ok" = true ] || reason="${reason:+$reason+}glamor_${glamor_ok}"
    [ "$vaapi_x11_ok" = true ] || reason="${reason:+$reason+}vaapi_${vaapi_x11_ok}"
    [ "$encoder_fallback" = false ] || reason="${reason:+$reason+}encoder_${encoder_fallback}"
    [ "$obs_startup_complete" = true ] || reason="${reason:+$reason+}obs_startup_${obs_startup_complete}"
    [ "$x_identity" != unknown ] || reason="${reason:+$reason+}x_identity_unknown"

    case "$reason" in
        *false*|*degraded*|*failed*|*fallback*|*truncated*|*inconsistent*) status=degraded ;;
        *unknown*|*missing*) status=unknown ;;
        *) reason=all_checks_passed ;;
    esac

    log "[RENDER-STACK] status=$status mesa_consistent=$mesa_consistent glamor_ok=$glamor_ok vaapi_x11_ok=$vaapi_x11_ok encoder_fallback=$encoder_fallback obs_startup_complete=$obs_startup_complete x_identity=$x_identity reason=$reason"

    if [ "$status" = degraded ] && fresh_due "render_stack_degraded_notify" $((12 * 3600)); then
        notify_webhook "Render stack degraded: $reason" "EvoBox Render Stack Alert" "warning"
        fresh_mark "render_stack_degraded_notify"
    fi

    return 0
}

# True if $1 is a lowercase 64-hex SHA-256 digest.
is_sha256() {
    [[ "$1" =~ ^[0-9a-f]{64}$ ]]
}

# Print the SHA-256 digest (hex only) of file $1, or nothing on error.
sha_of() {
    sha256sum "$1" 2>/dev/null | awk '{print $1}'
}

#===============================================================================
# Freshness guards — skip slow GCS round-trips when content is recent
#===============================================================================
# Background: pre-fix every cron tick re-downloaded the crontab, OBS-NDI
# version manifest, download_media.py, and re-ran the media script. On
# devices with slow networks (e.g., evobox-oem-0157) these added ~5s/tick.
# These payloads change at most once per day, so a 12h cache is plenty.

# fresh_due <op> [ttl_seconds]
#   Returns 0 if the named operation should run (no prior stamp, stamp is
#   older than TTL, or the force-refresh flag is set), 1 if it can be
#   safely skipped. Default TTL is EVO_GCS_FRESHNESS_TTL (12h).
fresh_due() {
    local op="$1"
    local ttl="${2:-$EVO_GCS_FRESHNESS_TTL}"

    [ -f "$EVO_FORCE_REFRESH_FLAG" ] && return 0

    local stamp="$EVO_CACHE_DIR/${op}.lastrun"
    [ ! -f "$stamp" ] && return 0

    local now stamp_mtime age
    now=$(date +%s)
    stamp_mtime=$(stat -c %Y "$stamp" 2>/dev/null || echo 0)
    age=$(( now - stamp_mtime ))

    [ "$age" -ge "$ttl" ] && return 0
    return 1
}

# fresh_mark <op>
#   Record that the named operation just completed successfully.
#   Callers should only invoke this on a clean success path so failures
#   trigger a retry on the next tick.
#   One sanctioned exception: a <op>_attempt stamp paired with
#   fresh_backoff_active() may be armed immediately BEFORE a step that is unsafe
#   to interrupt (see repair_mesa_package_family()). A SIGKILL mid-step then
#   leaves the backoff open instead of inviting an immediate retry, and the
#   success path releases it with fresh_clear().
fresh_mark() {
    mkdir -p "$EVO_CACHE_DIR" 2>/dev/null
    touch "$EVO_CACHE_DIR/${1}.lastrun"
}

# fresh_clear <op>
#   Drop the stamp for <op> so its next check runs immediately. Used to release
#   a failure-backoff window after a clean success. Inverse of fresh_mark.
fresh_clear() {
    rm -f "$EVO_CACHE_DIR/${1}.lastrun"
}

# fresh_backoff_active <op> [ttl_seconds]
#   Returns 0 (true, "skip") if a stamp for <op> exists and is younger than
#   ttl — i.e. a failure-backoff window is still open — and 1 otherwise.
#   Unlike fresh_due(), this DELIBERATELY IGNORES the force-refresh flag: a
#   force refresh should re-run a successful/cached operation once, but must
#   not defeat the safety backoff that prevents re-downloading a known-broken
#   artifact on every tick. To force an immediate retry, clear the stamp
#   (rm "$EVO_CACHE_DIR/<op>.lastrun"). Default TTL is EVO_GCS_FRESHNESS_TTL.
fresh_backoff_active() {
    local stamp="$EVO_CACHE_DIR/${1}.lastrun"
    local ttl="${2:-$EVO_GCS_FRESHNESS_TTL}"
    [ ! -f "$stamp" ] && return 1

    local now stamp_mtime age
    now=$(date +%s)
    stamp_mtime=$(stat -c %Y "$stamp" 2>/dev/null || echo 0)
    age=$(( now - stamp_mtime ))

    [ "$age" -lt "$ttl" ] && return 0
    return 1
}

# Consume the force-refresh flag (called once at end of main()). The flag
# is intentionally one-shot — operators touch it to force a single re-run
# of every gated fetch, then the script auto-clears it. This avoids
# accidental "stuck on force-refresh forever" if a flag is forgotten.
fresh_consume_force_flag() {
    if [ -f "$EVO_FORCE_REFRESH_FLAG" ]; then
        rm -f "$EVO_FORCE_REFRESH_FLAG"
        log "[FRESH] Force-refresh flag consumed; subsequent ticks resume 12h cache"
    fi
}

# Marks that apt lists have been refreshed since boot. A global because the
# boot-integrity block also refreshes them (unconditionally — see there) and
# should let the callers below skip their own.
readonly APT_UPDATE_FLAG="/tmp/evobox_apt_updated"

# Run apt update only once per session
run_apt_update_if_needed() {
    if [ ! -f "$APT_UPDATE_FLAG" ]; then
        log "Running apt-get update..."
        if sudo apt-get update; then
            touch "$APT_UPDATE_FLAG"
            log "[SUCCESS] apt-get update completed"
        else
            log_error "apt-get update failed, continuing anyway"
        fi
    fi
}

#===============================================================================
# DOWNLOAD FUNCTIONS
#===============================================================================

download_wifi_service() {
    local udev_rule="99-usb-wifi-config.rules"
    local systemd_service="usb-wifi-config.service"
    local wifi_script="usb-wifi-config.sh"

    if ! sudo curl --connect-timeout 20 --max-time 30 -L -o "/etc/udev/rules.d/$udev_rule" \
        "${GCS_USB_WIFI}/${udev_rule}" -f --retry 5; then
        log_error "Failed to download $udev_rule"
        return 1
    fi

    if ! sudo curl --connect-timeout 20 --max-time 30 -L -o "/etc/systemd/system/$systemd_service" \
        "${GCS_USB_WIFI}/${systemd_service}" -f --retry 5; then
        log_error "Failed to download $systemd_service"
        return 1
    fi

    if ! sudo curl --connect-timeout 20 --max-time 30 -L -o "/usr/local/bin/$wifi_script" \
        "${GCS_USB_WIFI}/${wifi_script}" -f --retry 5; then
        log_error "Failed to download $wifi_script"
        return 1
    fi

    sudo chmod +x "/usr/local/bin/$wifi_script" || log_error "Failed to chmod wifi script"
    sudo systemctl daemon-reload || log_error "Failed to reload systemd daemon"
    sudo udevadm control --reload-rules || log_error "Failed to reload udev rules"

    log "[SUCCESS] WiFi service downloaded and configured"
    return 0
}

# Seconds to wait for a foreign dpkg/apt transaction to finish before giving up
# and deferring to the next cron tick (five minutes later). Deliberately short:
# main()'s watchdog ends the whole run at LOCK_TIMEOUT, and every second spent
# waiting here is a second the OBS transaction below cannot use.
readonly DPKG_LOCK_WAIT_SECONDS=90

# Seconds already spent waiting on the dpkg lock in this run of
# install_obs_ndi_archive(), which resets it. The headroom reserve budgets ONE
# wait, but the install path calls wait_for_dpkg_lock several times
# (pre-download, pre-dpkg, and once per NDI package), and each call can consume
# the full DPKG_LOCK_WAIT_SECONDS and still succeed if the holder releases in
# the last moment. Billing them all against one budget keeps the total inside
# the reserve, so a lock that is repeatedly taken and released — the
# intermittent form of the unattended-upgrades contention this exists to
# survive — cannot walk the run into the watchdog's SIGKILL mid-transaction.
DPKG_LOCK_WAIT_SPENT=0

# Which PIDs hold the dpkg/apt locks, with command names, for one log line.
# Best effort: fuser lives in psmisc, which is on these images but not
# guaranteed. sudo is required — the lock files are root-owned, and an unsudoed
# fuser reports a held lock as free.
dpkg_lock_holders() {
    command -v fuser > /dev/null 2>&1 || { echo "unknown (fuser unavailable)"; return 0; }

    local pids
    pids=$(sudo fuser /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock \
        /var/cache/apt/archives/lock 2>/dev/null \
        | tr -s ' ' '\n' | grep -E '^[0-9]+$' | sort -u | tr '\n' ' ')
    [ -z "$pids" ] && { echo "none"; return 0; }

    local out="" pid
    for pid in $pids; do
        out="${out}${pid}($(ps -o comm= -p "$pid" 2>/dev/null || echo '?')) "
    done
    echo "${out% }"
}

# Returns 0 once nothing else holds the dpkg/apt locks, 1 if they are still held
# after DPKG_LOCK_WAIT_SECONDS. A freshly imaged device runs unattended-upgrades
# on first boot, so the installer's very first OBS install regularly loses that
# race; the caller must treat a loss as "retry next tick", never as success.
# Without fuser we cannot observe the lock, so proceed and let the caller's exit
# status check catch a failure.
wait_for_dpkg_lock() {
    command -v fuser > /dev/null 2>&1 || return 0

    # A spent budget still checks the lock: a free lock must not read as busy
    # just because earlier waits used the budget up.
    local budget=$(( DPKG_LOCK_WAIT_SECONDS - DPKG_LOCK_WAIT_SPENT ))
    local waited=0
    while sudo fuser /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock \
        /var/cache/apt/archives/lock > /dev/null 2>&1; do
        if [ "$waited" -ge "$budget" ]; then
            DPKG_LOCK_WAIT_SPENT=$(( DPKG_LOCK_WAIT_SPENT + waited ))
            log_error "[APT] dpkg lock still held after ${waited}s (budget ${budget}s) by: $(dpkg_lock_holders)"
            return 1
        fi
        [ "$waited" -eq 0 ] && log "[APT] Waiting for dpkg lock, held by: $(dpkg_lock_holders)"
        sleep 5
        waited=$(( waited + 5 ))
    done

    DPKG_LOCK_WAIT_SPENT=$(( DPKG_LOCK_WAIT_SPENT + waited ))
    [ "$waited" -gt 0 ] && log "[APT] dpkg lock released after ${waited}s (${DPKG_LOCK_WAIT_SPENT}s waited this run)"
    return 0
}

# Seconds to allow one dpkg/apt transaction, derived from what the watchdog has
# left. The evobox watchdog cannot signal root's dpkg, so without a bound a
# transaction that hangs outlives the tick and keeps the lock. The bound runs as
# root (`setsid --wait timeout -k`, as in run_bounded_apt_get()), so the cut is
# a SIGTERM that lets dpkg unwind, escalating to SIGKILL only after
# APT_KILL_GRACE_SECONDS, and prepare_apt_environment()'s `dpkg --configure -a`
# finishes the job next tick. An unreadable headroom gets the full budget.
readonly DPKG_TRANSACTION_MAX=240    # no point bounding tighter than needed
readonly DPKG_TRANSACTION_MIN=60     # below this a transaction cannot finish
readonly DPKG_TRANSACTION_RESERVE=30 # covers the -k grace, then logging and exit
# Result of the last dpkg_transaction_timeout() call: the bound in seconds, or
# 0 meaning "defer, there is not enough left to finish".
DPKG_TRANSACTION_TIMEOUT=0

# Written as a global setter, not stdout-echo, for the same reason as
# resolve_pinned_daemon_url(): a $() caller runs this in a subshell, so the
# WATCHDOG_HEADROOM_SECONDS it refreshes would not reach the caller and the
# deferral log lines would quote a stale figure from the up-front gate — a
# diagnostic contradicting the decision it explains, which is the exact failure
# mode this whole change exists to remove.
dpkg_transaction_timeout() {
    watchdog_headroom_available 0 > /dev/null 2>&1
    if [ -z "${WATCHDOG_HEADROOM_SECONDS:-}" ]; then
        DPKG_TRANSACTION_TIMEOUT="$DPKG_TRANSACTION_MAX"
        return 0
    fi

    # Only ever clamped DOWN. Clamping up to a floor would hand back a bound
    # longer than the headroom it exists to respect — the watchdog would fire
    # first, in precisely the low-headroom case this is for. When even the floor
    # does not fit, the caller defers instead; that is cheap, because the
    # archive stays cached.
    local t=$(( WATCHDOG_HEADROOM_SECONDS - DPKG_TRANSACTION_RESERVE ))
    [ "$t" -gt "$DPKG_TRANSACTION_MAX" ] && t="$DPKG_TRANSACTION_MAX"
    [ "$t" -lt "$DPKG_TRANSACTION_MIN" ] && t=0
    DPKG_TRANSACTION_TIMEOUT="$t"
}

# Map a bounded transaction's exit status to install_obs_ndi_archive()'s return
# codes: 0 it was not cut off, 2 it was cut off by a bound that headroom had
# clamped below DPKG_TRANSACTION_MAX (the next tick starts with full headroom,
# so defer), 1 it was cut off at the full DPKG_TRANSACTION_MAX (more time will
# not help, so fail and let the caller arm the 1h backoff). 124 is timeout's
# SIGTERM, 137 its -k SIGKILL.
dpkg_bound_outcome() {
    local rc="$1" bound="$2" what="$3"
    case "$rc" in
        124|137) ;;
        *) return 0 ;;
    esac
    if [ "$bound" -lt "$DPKG_TRANSACTION_MAX" ]; then
        log "[OBS-NDI] $what hit its ${bound}s bound, clamped by watchdog headroom; deferring to next tick"
        return 2
    fi
    log_error "[OBS-NDI] $what hit the full ${bound}s bound; treating it as a failure"
    return 1
}

# True when a package is registered as fully installed — not merely unpacked,
# half-configured, or reduced to config files by a purge. A held package
# ("hold ok installed") is installed too.
dpkg_package_installed() {
    dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -qE '^(install|hold) ok installed$'
}

# True when a package is fully installed at exactly the given version. On an
# upgrade, dpkg can refuse the new .deb and roll back, which leaves the old
# version "install ok installed": a status check alone reads that as success.
dpkg_package_at_version() {
    dpkg_package_installed "$1" || return 1
    [ "$(dpkg-query -W -f='${Version}' "$1" 2>/dev/null)" = "$2" ]
}

# True when every "package=version" pair in $1 is installed at that version.
obs_debs_at_target() {
    local pair
    for pair in $1; do
        dpkg_package_at_version "${pair%%=*}" "${pair#*=}" || return 1
    done
    return 0
}

# OBS as the daemon would find it. Probed via PATH *and* the packaged absolute
# path on purpose: this script runs from cron with a minimal PATH, and a false
# "OBS is missing" here would force a needless reinstall on every device.
obs_binary_present() {
    command -v obs > /dev/null 2>&1 || [ -x /usr/bin/obs ]
}

# Post-install proof for the OBS half of the manifest. $1 is the archive's
# "package=version" list, read from the .debs themselves. Each package must be
# installed at the archive's version, not merely installed, and the binary is a
# separate check: a package can be registered with `obs` gone, and `obs` is
# what actually gets launched.
obs_install_verified() {
    local pair pkg ver
    for pair in $1; do
        pkg="${pair%%=*}"
        ver="${pair#*=}"
        if ! dpkg_package_at_version "$pkg" "$ver"; then
            log_error "[OBS-NDI] Verify failed: $pkg is not installed at $ver (dpkg: $(dpkg-query -W -f='${Status} ${Version}' "$pkg" 2>/dev/null || echo absent))"
            return 1
        fi
    done
    if ! dpkg_package_installed obs-studio; then
        log_error "[OBS-NDI] Verify failed: obs-studio not installed (dpkg status: $(dpkg-query -W -f='${Status}' obs-studio 2>/dev/null || echo absent))"
        return 1
    fi
    if ! obs_binary_present; then
        log_error "[OBS-NDI] Verify failed: obs-studio registered but no obs binary found"
        return 1
    fi
    return 0
}

# The OBS half's dpkg work: `dpkg -i` the archive's .debs, then `apt-get -f`
# for their base-repo dependencies. Both run under the root-side bound from
# dpkg_transaction_timeout(). Returns like install_obs_ndi_archive(); a dpkg
# error is logged, not returned, because the `apt-get -f` after it is also its
# recovery path, and the caller's version check decides.
install_obs_debs() {
    # The download took time, and another apt run can have taken the lock
    # since. Normally an instant no-op.
    if ! wait_for_dpkg_lock; then
        log "[OBS-NDI] Deferring OBS install to next tick, dpkg became busy"
        return 2
    fi

    # run_logged, not `| tee`: this script is `set +e` with no `pipefail`, so
    # `if sudo dpkg -i ... | tee` tests tee's status (~always 0). That is how
    # a dpkg which never ran at all — it lost the frontend lock to
    # unattended-upgrades on a freshly imaged device — got logged as
    # "[SUCCESS] OBS archive installed" while OBS stayed absent. setsid and -k
    # for the reasons in run_bounded_apt_get(); dpkg itself has no lock wait.
    local obs_tmo dpkg_rc outcome
    dpkg_transaction_timeout
    obs_tmo="$DPKG_TRANSACTION_TIMEOUT"
    if [ "$obs_tmo" -eq 0 ]; then
        log "[OBS-NDI] Too little headroom for the OBS transaction; next tick (remaining=${WATCHDOG_HEADROOM_SECONDS}s)"
        return 2
    fi
    run_logged sudo DEBIAN_FRONTEND=noninteractive setsid --wait \
        timeout -k "$APT_KILL_GRACE_SECONDS" "$obs_tmo" dpkg -i "$@"
    dpkg_rc=$?
    dpkg_bound_outcome "$dpkg_rc" "$obs_tmo" "OBS dpkg"
    outcome=$?
    [ "$outcome" -ne 0 ] && return "$outcome"
    [ "$dpkg_rc" -ne 0 ] && log_error "OBS dpkg reported errors, attempting apt dependency fix"

    # Pull in any missing base-repo dependencies. Also the recovery path for
    # the dpkg failure above, so it runs either way. With no headroom left,
    # defer: the next tick re-enters with full headroom (and
    # prepare_apt_environment() runs `apt-get -f install` on a dpkg left
    # mid-transaction), so nothing is stranded.
    local fix_tmo fix_rc
    dpkg_transaction_timeout
    fix_tmo="$DPKG_TRANSACTION_TIMEOUT"
    if [ "$fix_tmo" -eq 0 ]; then
        log "[OBS-NDI] No headroom left for the dependency fix; deferring, next tick completes it (remaining=${WATCHDOG_HEADROOM_SECONDS}s)"
        return 2
    fi
    run_bounded_apt_get "$fix_tmo" install -f -y
    fix_rc=$?
    dpkg_bound_outcome "$fix_rc" "$fix_tmo" "Dependency fix"
    outcome=$?
    [ "$outcome" -ne 0 ] && return "$outcome"
    [ "$fix_rc" -ne 0 ] && log_error "apt-get install -f failed after OBS dpkg"
    return 0
}

# Install the OBS + NDI packages named by the manifest. Exit codes match
# _publishd_update(): 0 success (proven, not inferred), 1 failure, 2 deferred.
# 2 means "come back next tick" and arms no backoff. It covers dpkg being busy,
# too little watchdog headroom to start a transaction, and a transaction cut off
# by a bound that headroom had clamped. The last one has mutated the system, but
# the next tick starts with full headroom; a transaction that overruns the full
# DPKG_TRANSACTION_MAX returns 1 instead, so it cannot repeat every tick.
install_obs_ndi_archive() {
    local version_json="$1"

    # Every lock wait below draws from one shared budget for this invocation.
    DPKG_LOCK_WAIT_SPENT=0

    # --- Install OBS archive ---
    local obs_archive
    obs_archive=$(jq -r '.obs.archive' "$version_json")

    if [ -n "$obs_archive" ] && [ "$obs_archive" != "null" ]; then
        # An archive cached for a version the manifest has moved past is never
        # reused, so drop it instead of leaving ~87MB in disk-backed /tmp.
        find /tmp -maxdepth 1 -type f -name 'obs-studio-*.tar.gz' ! -name "$obs_archive" -delete 2>/dev/null

        # Both deferral gates run BEFORE the ~87MB download, so a deferral costs
        # no network and no disk. They return 2, which deliberately arms no
        # backoff, so anything they gate repeats every tick (five minutes) — and
        # a device that consistently arrives here late would otherwise download
        # and extract the archive, throw it away, and do it again next tick,
        # forever. /tmp is disk-backed until the Phase 3 tmpfs work lands.
        #
        # Don't open a dpkg transaction we may not get to finish. The floor
        # covers the lock wait plus one full transaction. It gates on watchdog
        # headroom like repair_mesa_package_family(), but proceeds when the
        # headroom cannot be read (below).
        #
        # Floor sized against measurements, because a floor set too high would
        # defer the install on every tick and never install OBS at all: a
        # steady-state tick reaches this point ~5s in (~595s of headroom), and
        # even a first-boot run doing full apt work got here ~230s in (~370s).
        # An unreadable headroom leaves WATCHDOG_HEADROOM_SECONDS empty; proceed
        # in that case rather than deferring forever on a broken uptime read.
        if ! watchdog_headroom_available $(( DPKG_LOCK_WAIT_SECONDS + DPKG_TRANSACTION_MAX )) \
            && [ -n "${WATCHDOG_HEADROOM_SECONDS:-}" ]; then
            log "[OBS-NDI] Watchdog headroom too low for an OBS install; next tick (remaining=${WATCHDOG_HEADROOM_SECONDS}s)"
            return 2
        fi

        if ! wait_for_dpkg_lock; then
            log "[OBS-NDI] Deferring OBS install to next tick, dpkg is busy"
            return 2
        fi

        log "[OBS-NDI] Downloading OBS archive: $obs_archive"
        local obs_tmp="/tmp/obs-install"
        rm -rf "$obs_tmp"
        mkdir -p "$obs_tmp"

        # Reuse an archive left behind by a previous tick's deferral, so a
        # deferral below the download costs nothing on the retry either. The
        # filename encodes the version, so a name match is a version match;
        # it is still validated before being trusted.
        if [ -s "/tmp/$obs_archive" ] && tar -tzf "/tmp/$obs_archive" > /dev/null 2>&1; then
            log "[OBS-NDI] Reusing OBS archive already on disk: $obs_archive"
        elif ! curl --connect-timeout 20 --max-time 180 -L -o "/tmp/$obs_archive" "${GCS_OBS}/${obs_archive}?$(date +%s)" -f --retry 5; then
            log_error "Failed to download OBS archive: $obs_archive"
            rm -rf "$obs_tmp" "/tmp/$obs_archive"
            return 1
        fi

        if ! run_logged tar -xzf "/tmp/$obs_archive" -C "$obs_tmp"; then
            log_error "Failed to extract OBS archive: $obs_archive"
            rm -rf "$obs_tmp" "/tmp/$obs_archive"
            return 1
        fi

        # Resolve the .deb list ourselves. `dpkg -i "$obs_tmp"/*.deb` on an empty
        # directory passes the literal glob through to dpkg, which used to be
        # indistinguishable from a real install.
        # Not mapfile: it is a bash 4 builtin and the fixtures run on macOS bash 3.2.
        local obs_debs=() obs_debs_text deb
        obs_debs_text="$(find "$obs_tmp" -maxdepth 2 -type f -name '*.deb' | sort)"
        if [ -n "$obs_debs_text" ]; then
            while IFS= read -r deb; do
                obs_debs+=("$deb")
            done <<< "$obs_debs_text"
        fi
        if [ "${#obs_debs[@]}" -eq 0 ]; then
            log_error "OBS archive contained no .deb packages: $obs_archive"
            rm -rf "$obs_tmp" "/tmp/$obs_archive"
            return 1
        fi

        # Each package's name and version, read out of the .debs, so the verify
        # below proves the archive's versions landed and not merely that some
        # obs-studio is installed.
        local obs_want="" pkg ver
        for deb in "${obs_debs[@]}"; do
            pkg=$(dpkg-deb -f "$deb" Package 2>/dev/null)
            ver=$(dpkg-deb -f "$deb" Version 2>/dev/null)
            if [ -z "$pkg" ] || [ -z "$ver" ]; then
                log_error "Not a readable .deb in the OBS archive, refusing to install: ${deb##*/}"
                rm -rf "$obs_tmp" "/tmp/$obs_archive"
                return 1
            fi
            obs_want="${obs_want:+$obs_want }$pkg=$ver"
        done

        # The binary check matters: a package can be registered at the target
        # version with `obs` gone, and only `dpkg -i` puts it back. Skipping on
        # the version records alone fails the verify below, arms the 1h backoff,
        # and takes the same skip on every retry.
        if obs_debs_at_target "$obs_want" && obs_binary_present; then
            # A re-entry after an NDI deferral, or a manifest bump that left the
            # OBS packages alone: dpkg has nothing to do.
            log "[OBS-NDI] OBS packages already at the archive's versions; skipping dpkg"
        else
            local obs_rc
            install_obs_debs "${obs_debs[@]}"
            obs_rc=$?
            if [ "$obs_rc" -ne 0 ]; then
                # Archive kept deliberately: the retry reuses it instead of
                # re-fetching ~87MB.
                rm -rf "$obs_tmp"
                return "$obs_rc"
            fi
        fi

        # Extract dir goes now; the archive stays until the whole function
        # succeeds. An NDI deferral below leaves the manifest unpromoted, so the
        # next tick re-enters the OBS half, where the archive is cached and the
        # version check above skips dpkg.
        rm -rf "$obs_tmp"

        # Never report success on inference. The caller promotes the server
        # manifest to the local one on our exit status, and a wrong 0 wedges the
        # device permanently: local == server forever, so it never retries.
        if ! obs_install_verified "$obs_want"; then
            log_error "OBS install did not take — leaving local version manifest untouched so the next tick retries"
            return 1
        fi
        log "[SUCCESS] OBS archive installed"
    fi

    # --- Install NDI packages ---
    local ndi_count
    ndi_count=$(jq '.ndi.packages | length' "$version_json")

    local i filename pkgname pkgver ndi_tmo ndi_rc outcome
    for i in $(seq 0 $((ndi_count - 1))); do
        filename=$(jq -r ".ndi.packages[$i]" "$version_json")

        log "[OBS-NDI] Downloading NDI package: $filename"
        if ! curl --connect-timeout 20 --max-time 120 -L -o "/tmp/$filename" "${GCS_NDI}/${filename}" -f --retry 5; then
            log_error "Failed to download $filename"
            rm -f "/tmp/$filename"
            return 1
        fi

        # Read the package name and version out of the .deb before installing
        # it, so the verify below names the same thing dpkg registers rather
        # than guessing from the filename (obs-ndi-4.10.1-linux-x86_64.deb ->
        # obs-ndi), and proves this version landed.
        pkgname=$(dpkg-deb -f "/tmp/$filename" Package 2>/dev/null)
        pkgver=$(dpkg-deb -f "/tmp/$filename" Version 2>/dev/null)
        if [ -z "$pkgname" ] || [ -z "$pkgver" ]; then
            log_error "Not a readable .deb, refusing to install: $filename"
            rm -f "/tmp/$filename"
            return 1
        fi

        if dpkg_package_at_version "$pkgname" "$pkgver"; then
            log_debug "[OBS-NDI] $pkgname already at $pkgver; skipping"
            rm -f "/tmp/$filename"
            continue
        fi

        if ! wait_for_dpkg_lock; then
            log "[OBS-NDI] Deferring NDI install to next tick, dpkg is busy"
            rm -f "/tmp/$filename"
            return 2
        fi

        # run_bounded_apt_get logs through run_logged: the old `| tee ||
        # log_error` reported tee's status, so a failed NDI install left no
        # trace in the log at all.
        dpkg_transaction_timeout
        ndi_tmo="$DPKG_TRANSACTION_TIMEOUT"
        if [ "$ndi_tmo" -eq 0 ]; then
            log "[OBS-NDI] Too little headroom to install $pkgname; next tick (remaining=${WATCHDOG_HEADROOM_SECONDS}s)"
            rm -f "/tmp/$filename"
            return 2
        fi
        run_bounded_apt_get "$ndi_tmo" install -y "/tmp/$filename"
        ndi_rc=$?
        rm -f "/tmp/$filename"
        dpkg_bound_outcome "$ndi_rc" "$ndi_tmo" "$pkgname install"
        outcome=$?
        [ "$outcome" -ne 0 ] && return "$outcome"
        if [ "$ndi_rc" -ne 0 ]; then
            log_error "Failed to install $filename"
            return 1
        fi

        if ! dpkg_package_at_version "$pkgname" "$pkgver"; then
            log_error "[OBS-NDI] Verify failed: $pkgname is not installed at $pkgver after $filename (dpkg: $(dpkg-query -W -f='${Status} ${Version}' "$pkgname" 2>/dev/null || echo absent))"
            return 1
        fi
        log_debug "[OBS-NDI] Verified $pkgname $pkgver installed"
    done

    # Everything installed and verified: the cached archive has no further use.
    [ -n "$obs_archive" ] && [ "$obs_archive" != "null" ] && rm -f "/tmp/$obs_archive"
    log "[SUCCESS] OBS + NDI installation completed"
    return 0
}

deploy_obs_plugins() {
    local obs_plugins_location="/usr/share/obs/obs-plugins/frontend-tools/scripts"
    local filter_filename="filter-evo-unfish-LDCv6.lua"

    if wget --timeout=20 --tries=2 -O "$filter_filename" \
        "${GCS_OBS_PLUGINS}/evobox_obs-plugins_filter-fish-lens_v6-LDC.lua" 2>/dev/null; then
        if sudo mv "$filter_filename" "${obs_plugins_location}/${filter_filename}"; then
            log_debug "[SUCCESS] OBS plugins downloaded and deployed"
        else
            log_error "Failed to move OBS plugin to destination"
        fi
    else
        log_error "Failed to download OBS plugins"
    fi
}

# Sidecar recording the pinned archive URL that is currently installed. Present
# only while ~/.evo-beta holds a valid pin; removed when the pin is cleared.
readonly DAEMON_PIN_SIDECAR="$EVOSPORTS_ROOT/evobox-daemon-pinned-url"

# Only archives under this exact host+bucket prefix may be pinned via ~/.evo-beta.
readonly DAEMON_PIN_URL_PREFIX="https://storage.googleapis.com/releases-evosports/"
# The selected daemon release metadata and archive URL for the current update
# decision. The manifest path is temporary and is cleared after each decision.
DAEMON_RELEASE_MANIFEST=""
DAEMON_RELEASE_URL=""

# Backoff sidecar for install attempts that stop a HEALTHY daemon before
# downloading. The receipt is only advanced on success, so an archive that
# cannot be fetched would otherwise re-enter the same branch every minute:
# stop the unit, spend up to ~10 minutes of curl timeouts, fail, restart. One
# line: "<target> <next-attempt-epoch> <delay-seconds>". The target is the
# identity being installed, so a newly published release always gets an
# immediate attempt. Corrupt-tree recovery deliberately does not consult this:
# there is no healthy daemon left to protect and delaying only keeps the device
# dark for longer.
readonly DAEMON_RETRY_SIDECAR="$EVOSPORTS_ROOT/evobox-daemon-retry"
readonly DAEMON_RETRY_MIN_DELAY=300
readonly DAEMON_RETRY_MAX_DELAY=3600

daemon_retry_allowed() {
    local target="$1"
    [ -f "$DAEMON_RETRY_SIDECAR" ] || return 0

    local stored_target stored_next stored_delay
    read -r stored_target stored_next stored_delay < "$DAEMON_RETRY_SIDECAR" 2>/dev/null

    # A different identity is a different decision, and a malformed sidecar must
    # never be able to suppress installs. Both drop the record and attempt now.
    if [ "$stored_target" != "$target" ]; then
        rm -f "$DAEMON_RETRY_SIDECAR"
        return 0
    fi
    case "$stored_next" in
        ''|*[!0-9]*)
            rm -f "$DAEMON_RETRY_SIDECAR"
            return 0
            ;;
    esac

    local now
    now="$(date +%s)"
    if [ "$now" -ge "$stored_next" ]; then
        return 0
    fi

    log_debug "[daemon-version] Install of $target backed off for $((stored_next - now))s after a failed attempt"
    return 1
}

daemon_retry_record_failure() {
    local target="$1"
    local stored_target="" stored_next="" stored_delay=""
    if [ -f "$DAEMON_RETRY_SIDECAR" ]; then
        read -r stored_target stored_next stored_delay < "$DAEMON_RETRY_SIDECAR" 2>/dev/null
    fi

    local delay="$DAEMON_RETRY_MIN_DELAY"
    if [ "$stored_target" = "$target" ]; then
        case "$stored_delay" in
            ''|*[!0-9]*) ;;
            *) delay=$((stored_delay * 2)) ;;
        esac
    fi
    [ "$delay" -gt "$DAEMON_RETRY_MAX_DELAY" ] && delay="$DAEMON_RETRY_MAX_DELAY"

    printf '%s %s %s\n' "$target" "$(( $(date +%s) + delay ))" "$delay" \
        > "$DAEMON_RETRY_SIDECAR" || \
        log_error "[daemon-version] Failed to record the install retry backoff"
    log "[daemon-version] Install of $target failed — next attempt in ${delay}s"
}

daemon_retry_clear() {
    [ -f "$DAEMON_RETRY_SIDECAR" ] || return 0
    rm -f "$DAEMON_RETRY_SIDECAR"
}

fetch_daemon_release() {
    if [ -n "${DAEMON_RELEASE_MANIFEST:-}" ]; then
        rm -f "$DAEMON_RELEASE_MANIFEST"
    fi
    DAEMON_RELEASE_MANIFEST=""
    DAEMON_RELEASE_URL=""

    local channels=()
    if [ -f "$HOME/.evo-beta" ]; then
        channels=("beta" "production")
    else
        channels=("production")
    fi

    local channel manifest_name archive_name manifest_url archive_url
    local manifest_path version
    for channel in "${channels[@]}"; do
        if [ "$channel" = "beta" ]; then
            manifest_name="evobox-daemon-version-beta.json"
            archive_name="evo-obs-daemon-beta.tar.gz"
        else
            manifest_name="evobox-daemon-version.json"
            archive_name="evo-obs-daemon-main.tar.gz"
        fi

        manifest_url="${GCS_BASE}/${manifest_name}"
        archive_url="${GCS_BASE}/${archive_name}"
        if ! manifest_path="$(mktemp)"; then
            log_error "[daemon-release] Failed to create temporary $channel manifest"
            continue
        fi

        if ! curl -f --connect-timeout 20 --max-time 30 --retry 2 \
            -o "$manifest_path" "${manifest_url}?$(date +%s)" 2>/dev/null; then
            log "[daemon-release] Failed to fetch $channel manifest"
            rm -f "$manifest_path"
            continue
        fi

        if ! jq -e '
            type == "object" and
            (.version | (type == "string" and length > 0)) and
            ((has("commitId") | not) or
                (.commitId | (type == "string" and length > 0)))
        ' "$manifest_path" >/dev/null 2>&1; then
            log "[daemon-release] Invalid $channel manifest"
            rm -f "$manifest_path"
            continue
        fi

        version="$(jq -r '.version' "$manifest_path" 2>/dev/null)"
        case "$channel:$version" in
            beta:*-beta)
                ;;
            beta:*)
                log "[daemon-release] Beta manifest version has no -beta suffix"
                rm -f "$manifest_path"
                continue
                ;;
            production:*-beta)
                log "[daemon-release] Production manifest has a -beta suffix"
                rm -f "$manifest_path"
                continue
                ;;
            production:*)
                ;;
        esac

        DAEMON_RELEASE_MANIFEST="$manifest_path"
        DAEMON_RELEASE_URL="$archive_url"
        log_debug "[daemon-release] Selected $channel release: $version"
        return 0
    done

    log_error "[daemon-release] No valid daemon release manifest available"
    return 1
}

# Resolve a pinned daemon archive URL from ~/.evo-beta into the global
# PINNED_DAEMON_URL. A "pin" is the first non-empty, whitespace-trimmed line of
# the flag file, and only counts if it is an https URL under the trusted release
# host with no shell metacharacters. Sets PINNED_DAEMON_URL to "" for: no flag,
# empty/whitespace flag (plain beta channel), or an untrusted/malformed value
# (logged and rejected). Written as a global setter — not stdout-echo — so the
# log lines below don't get captured by a $() caller.
resolve_pinned_daemon_url() {
    PINNED_DAEMON_URL=""
    local flag="$HOME/.evo-beta"
    [ -f "$flag" ] || return 0

    local line
    line="$(grep -m1 -v '^[[:space:]]*$' "$flag" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
    [ -n "$line" ] || return 0

    case "$line" in
        "$DAEMON_PIN_URL_PREFIX"*) ;;
        *)
            log_error "[download_evobox_daemon] .evo-beta URL not under trusted release host — ignoring pin, using beta channel: $line"
            return 0
            ;;
    esac

    # The value flows into curl; refuse anything with shell metacharacters or
    # whitespace. URLs never legitimately contain these.
    case "$line" in
        *[' '\'\"\$\`\;\|\&\<\>\(\)]*)
            log_error "[download_evobox_daemon] .evo-beta URL contains illegal characters — ignoring pin, using beta channel: $line"
            return 0
            ;;
    esac

    PINNED_DAEMON_URL="$line"
}

#-------------------------------------------------------------------------------
# Device identity (evo.json) — #67
#-------------------------------------------------------------------------------
# evo.json is the only record of the deviceId a daemon registered under. A
# daemon that starts without a usable one registers a new evo-N, and its table
# stays on the old id, so the table goes dark (0176 on 2026-09-08, Roadhouse
# 0037 on 2026-10-25). The old preserve/restore copied the file with plain `cp`
# into a temporary that was deleted on success, restored it only when the live
# file was absent, and dropped a 0-byte one, so a reboot inside an update window
# lost the id for good.
#
# The durable copy under EVO_IDENTITY_DIR now holds the id across ticks and
# reboots, and ensure_daemon_identity() is the only writer of either file.

# True when FILE holds exactly one object matching EVO_IDENTITY_JQ.
identity_file_ok() {
    [ -s "$1" ] || return 1
    jq -se "length == 1 and (.[0] | $EVO_IDENTITY_JQ)" "$1" >/dev/null 2>&1 || return 1
}

# The deviceId of a file identity_file_ok() already accepted.
identity_device_id() {
    jq -sr '.[0].deviceId' "$1" 2>/dev/null
}

# `sync FILE` (coreutils >= 8.24) flushes just that file; anything older takes
# a whole-filesystem sync instead of failing the write.
identity_sync() {
    sync "$@" 2>/dev/null || sync
}

# Args: $1 = role, $2 = event, $3 = detail
identity_history() {
    mkdir -p "$EVO_IDENTITY_DIR" 2>/dev/null
    printf '%s %s %s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" "$2" "$3" \
        >> "$EVO_IDENTITY_DIR/history.log" 2>/dev/null || true
}

# Copy the identity in SRC to DEST so that DEST is either the old file or the
# complete new one, and the new one is on disk before this returns: temp file in
# DEST's directory, re-validated, synced, renamed over, directory synced.
# Args: $1 = src, $2 = dest
write_identity_durable() {
    local src="$1" dest="$2" dir tmp
    dir="$(dirname "$dest")"
    tmp="$dir/.$(basename "$dest").tmp.$$"
    mkdir -p "$dir" || return 1
    if ! ( umask 077; jq -sc '.[0]' "$src" > "$tmp" ) \
        || ! identity_file_ok "$tmp" \
        || ! identity_sync "$tmp" \
        || ! chmod 644 "$tmp" \
        || ! mv -f "$tmp" "$dest"; then
        rm -f "$tmp"
        return 1
    fi
    identity_sync "$dir"
}

# FILE is a usable identity for this role: valid, and for the second daemon not
# main's id (the second tree is built from a copy of main's, evo.json included).
# Args: $1 = file, $2 = main's deviceId or ""
identity_ok_for_role() {
    identity_file_ok "$1" || return 1
    [ -z "$2" ] || [ "$(identity_device_id "$1")" != "$2" ]
}

# Bring one daemon's live evo.json and its durable copy into agreement.
#
#   live              backup             action
#   valid             same id            nothing
#   valid             missing/invalid    write backup from live
#   valid             different id       live wins, history + warning webhook
#   missing           valid              restore live, warning webhook
#   empty/invalid     valid              move live aside, restore, warning
#   missing           missing            seed both from a valid legacy
#                                        .evo.json.preserved-*, else nothing
#                                        (first install registers)
#
# Once a durable copy exists the legacy file is deleted, so it cannot bring an
# old id back after a deliberate re-identity.
#   empty/invalid     missing            unit inactive: move live aside,
#                                        critical webhook, daemon re-registers
#                                        (keeps the 0142/0143 no-wedge rule)
#
# Returns 1 only when a write fails, so download_evobox_daemon() aborts before
# it wipes anything. A missing daemon directory is not an error: the restore
# happens after extraction.
#
# The second argument "after-install" marks the restore that follows every
# extraction. The archive ships no evo.json, so a missing live file is expected
# there and is logged without a webhook; anywhere else it is an incident.
# Args: $1 = main|second, $2 = "" or after-install
ensure_daemon_identity() {
    local role="$1" mode="${2:-}" dir unit legacy main_id=""
    case "$role" in
        main)   dir="$EVOSPORTS_MAIN_DAEMON";   unit="$DAEMON_UNIT_MAIN"
                legacy="$EVOSPORTS_ROOT/.evo.json.preserved-main" ;;
        second) dir="$EVOSPORTS_SECOND_DAEMON"; unit="$DAEMON_UNIT_SECOND"
                legacy="$EVOSPORTS_ROOT/.evo.json.preserved-second" ;;
        *) log_error "[identity] unknown daemon role '$role'"; return 1 ;;
    esac
    local live="$dir/evo.json" backup="$EVO_IDENTITY_DIR/$role.json"

    if [ "$role" = "second" ]; then
        if identity_file_ok "$EVO_IDENTITY_DIR/main.json"; then
            main_id="$(identity_device_id "$EVO_IDENTITY_DIR/main.json")"
        elif identity_file_ok "$EVOSPORTS_MAIN_DAEMON/evo.json"; then
            main_id="$(identity_device_id "$EVOSPORTS_MAIN_DAEMON/evo.json")"
        fi
    fi

    local backup_ok=false backup_id=""
    if identity_ok_for_role "$backup" "$main_id"; then
        backup_ok=true
        backup_id="$(identity_device_id "$backup")"
        # The durable copy supersedes the old code's preserved file. Left in
        # place, it would bring an old id back after a deliberate re-identity.
        rm -f "$legacy"
    fi

    # --- live is usable -------------------------------------------------------
    if identity_ok_for_role "$live" "$main_id"; then
        local live_id
        live_id="$(identity_device_id "$live")"
        [ "$live_id" = "$backup_id" ] && return 0
        if ! write_identity_durable "$live" "$backup"; then
            log_error "[identity] Failed to write $backup for $live_id"
            return 1
        fi
        if [ "$backup_ok" = "true" ]; then
            identity_history "$role" adopted "$backup_id -> $live_id"
            log "[identity] $role evo.json changed $backup_id -> $live_id; backup follows live"
            notify_webhook "The $role daemon's evo.json now holds $live_id; the saved identity was $backup_id. If $live_id was minted by an unintended re-registration, restore with: sudo systemctl stop $unit && printf '{\"deviceId\":\"$backup_id\"}' | tee $live $backup >/dev/null && sudo systemctl start $unit" \
                "EvoBox Device Identity" "warning"
        else
            identity_history "$role" saved "$live_id"
            log "[identity] Saved $role identity $live_id to $backup"
        fi
        rm -f "$legacy"
        return 0
    fi

    # --- live is missing --------------------------------------------------------
    if [ ! -e "$live" ] && [ ! -L "$live" ]; then
        if [ "$backup_ok" != "true" ]; then
            identity_ok_for_role "$legacy" "$main_id" || return 0
            if ! write_identity_durable "$legacy" "$backup"; then
                log_error "[identity] Failed to seed $backup from $legacy"
                return 1
            fi
            backup_id="$(identity_device_id "$backup")"
            identity_history "$role" seeded "$backup_id from $(basename "$legacy")"
            log "[identity] Seeded $role identity $backup_id from $legacy"
            rm -f "$legacy"
        fi
        [ -d "$dir" ] || return 0
        if ! write_identity_durable "$backup" "$live"; then
            log_error "[identity] Failed to restore $live ($backup_id)"
            return 1
        fi
        if [ "$mode" = "after-install" ]; then
            log "[identity] Restored $role evo.json after install: $backup_id"
            return 0
        fi
        identity_history "$role" restored "$backup_id (live missing)"
        log "[identity] Restored missing $role evo.json from backup: $backup_id"
        notify_webhook "The $role daemon's evo.json was missing; restored $backup_id from the saved identity before the daemon could register a new id." \
            "EvoBox Device Identity" "warning"
        return 0
    fi

    # --- live is present but empty, truncated or otherwise unusable -------------
    local aside
    aside="$EVO_IDENTITY_DIR/$role.invalid-$(date -u +%Y%m%dT%H%M%SZ)"
    if [ "$backup_ok" = "true" ]; then
        mkdir -p "$EVO_IDENTITY_DIR" && mv -f "$live" "$aside" 2>/dev/null
        if ! write_identity_durable "$backup" "$live"; then
            log_error "[identity] Failed to restore $live ($backup_id)"
            return 1
        fi
        identity_history "$role" restored "$backup_id (live invalid, kept as $(basename "$aside"))"
        log "[identity] Replaced invalid $role evo.json with backup $backup_id"
        notify_webhook "The $role daemon's evo.json was empty or invalid; restored $backup_id from the saved identity. The bad file is kept at $aside." \
            "EvoBox Device Identity" "warning"
        return 0
    fi

    if sudo systemctl is-active --quiet "$unit"; then
        log_error "[identity] $live is invalid and no backup exists; $unit is running, leaving it"
        return 0
    fi
    { mkdir -p "$EVO_IDENTITY_DIR" && mv -f "$live" "$aside" 2>/dev/null; } || rm -f "$live"
    identity_history "$role" lost "invalid evo.json, no backup"
    log_error "[identity] $role evo.json is empty or invalid and no backup exists — deviceId lost, the daemon will re-register"
    notify_webhook "Identity lost: the $role daemon's evo.json is empty or invalid and no saved identity exists. The daemon will register a new deviceId; reassign its table or restore the old id by hand." \
        "EvoBox Device Identity" "critical"
    return 0
}

reconcile_daemon_identities() {
    local rc=0
    ensure_daemon_identity main || rc=1
    if [ "$SECOND_DAEMON" = "true" ]; then
        ensure_daemon_identity second || rc=1
    fi
    return "$rc"
}

download_evobox_daemon() {
    log "Downloading daemon..."

    local daemon_url="${1:-}"
    if [ -z "$daemon_url" ]; then
        if [ -n "${DAEMON_RELEASE_MANIFEST:-}" ]; then
            rm -f "$DAEMON_RELEASE_MANIFEST"
        fi
        DAEMON_RELEASE_MANIFEST=""
        DAEMON_RELEASE_URL=""
        resolve_pinned_daemon_url
        if [ -n "$PINNED_DAEMON_URL" ]; then
            daemon_url="$PINNED_DAEMON_URL"
            log "[download_evobox_daemon] Pinned URL detected in .evo-beta, downloading pinned daemon: $daemon_url"
        else
            if ! fetch_daemon_release; then
                return 1
            fi
            daemon_url="$DAEMON_RELEASE_URL"
            if ! rm -f "$DAEMON_RELEASE_MANIFEST"; then
                log_error "[download_evobox_daemon] Failed to remove temporary release manifest"
                DAEMON_RELEASE_MANIFEST=""
                DAEMON_RELEASE_URL=""
                return 1
            fi
            DAEMON_RELEASE_MANIFEST=""
            DAEMON_RELEASE_URL=""
            log "[download_evobox_daemon] Resolved daemon archive: $daemon_url"
        fi
    else
        log "[download_evobox_daemon] Using explicit daemon archive: $daemon_url"
    fi


    # Every restore below reads the durable copy, so bring it up to date before
    # anything is downloaded or wiped. A failed write aborts here, while the
    # installed trees are still intact.
    if ! ensure_daemon_identity main; then
        log_error "Failed to save main device identity — aborting install to protect deviceId"
        return 1
    fi
    if [ "$SECOND_DAEMON" = "true" ] && ! ensure_daemon_identity second; then
        log_error "Failed to save second device identity — aborting install to protect deviceId"
        return 1
    fi

    # --fail: without it an HTTP error body is written out as the tarball.
    if ! curl --fail --connect-timeout 20 --max-time 180 --retry 3 -o evo-obs-daemon-main.tar.gz -L "${daemon_url}?$(date +%s)"; then
        log_error "Failed to download daemon archive"
        return 1
    fi
    log "[download_evobox_daemon] Daemon archive downloaded"

    # --- MAIN DAEMON: wipe dir, extract fresh, restore evo.json from backup ---
    # Safe to wipe: the identity is in EVO_IDENTITY_DIR, outside this tree.
    if [ -d "$EVOSPORTS_MAIN_DAEMON" ]; then
        if ! rm -rf "$EVOSPORTS_MAIN_DAEMON"; then
            log_error "Failed to wipe $EVOSPORTS_MAIN_DAEMON — restoring evo.json from backup"
            ensure_daemon_identity main
            rm -f ./evo-obs-daemon-main.tar.gz
            return 1
        fi
        log "[download_evobox_daemon] Wiped stale main daemon directory"
    fi

    # run_logged, not `| tee`: this script is `set +e` with no `pipefail`, so a
    # plain `if ! tar ... | tee` tests tee's status and reports a failed or
    # partial extraction as a success.
    if ! run_logged tar xzf evo-obs-daemon-main.tar.gz -C "$EVOSPORTS_ROOT"; then
        log_error "Failed to extract daemon archive — restoring evo.json from backup"
        mkdir -p "$EVOSPORTS_MAIN_DAEMON"
        ensure_daemon_identity main
        rm -f ./evo-obs-daemon-main.tar.gz
        return 1
    fi
    rm ./evo-obs-daemon-main.tar.gz
    log "[download_evobox_daemon] Daemon archive unzipped"

    # The archive ships no evo.json; put the saved one back before the daemon
    # can start on this tree.
    if ! ensure_daemon_identity main after-install; then
        log_error "Failed to restore main evo.json — the saved copy remains in $EVO_IDENTITY_DIR"
        return 1
    fi

    pushd "$EVOSPORTS_MAIN_DAEMON" > /dev/null || { log_error "Failed to change to daemon directory"; return 1; }
    # Daemon refreshes (this function is called on version-mismatch) can race
    # ahead of NVM's Node provisioning — e.g., NVM was just reinstalled but
    # `nvm install $NODE_VERSION` hasn't yet completed in this shell.
    # ensure_node_installed makes the prerequisite explicit here so a fresh
    # nvm + version-bumped daemon don't collide.
    ensure_node_installed || log_error "Failed to ensure Node $NODE_VERSION installed"
    nvm use "$NODE_VERSION" || log_error "Failed to switch Node version"
    sudo chown -R evobox:evobox "$EVOSPORTS_ROOT" || log_error "Failed to chown evosports directory"
    log "[download_evobox_daemon] Daemon archive installed"
    popd > /dev/null || log_error "Failed to return from daemon directory"

    # --- SECOND DAEMON: wipe, copy main, strip main's evo.json, then restore
    #     the second daemon's own saved id so the two never share one. ---
    if [ "$SECOND_DAEMON" = "true" ]; then
        if [ -d "$EVOSPORTS_SECOND_DAEMON" ]; then
            if ! rm -rf "$EVOSPORTS_SECOND_DAEMON"; then
                log_error "Failed to wipe $EVOSPORTS_SECOND_DAEMON"
                return 1
            fi
            log "[download_evobox_daemon] Wiped stale second daemon directory"
        fi

        if ! mkdir -p "$EVOSPORTS_SECOND_DAEMON"; then
            log_error "Failed to mkdir $EVOSPORTS_SECOND_DAEMON"
            return 1
        fi

        if ! cp -R "$EVOSPORTS_MAIN_DAEMON"/. "$EVOSPORTS_SECOND_DAEMON/"; then
            log_error "Failed to copy main daemon to second location"
            return 1
        fi

        # CRITICAL: strip the copy of main's evo.json so the second daemon
        # never shares a deviceId with main. A reboot before this line leaves
        # main's id in the second tree; the runner refuses to start on that and
        # the next tick's reconcile replaces it.
        rm -f "$EVOSPORTS_SECOND_DAEMON/evo.json"

        if ! ensure_daemon_identity second after-install; then
            log_error "Failed to restore second evo.json — the saved copy remains in $EVO_IDENTITY_DIR"
            return 1
        fi
        [ -e "$EVOSPORTS_SECOND_DAEMON/evo.json" ] || \
            log "[download_evobox_daemon] Second daemon has no saved identity — will self-generate on startup"

        sudo chown -R evobox:evobox "$EVOSPORTS_SECOND_DAEMON" || \
            log_error "Failed to chown second daemon directory"
    fi

    return 0
}

download_obs_scenes() {
    local scenes_dir="$HOME/scenes"
    mkdir -p "$scenes_dir" || { log_error "Failed to create scenes directory"; return 1; }

    local scenes=(
        "evosports_scenes-pip.json"
        "evosports_scenes.json"
        "evosports_scenes-mobile.json"
    )

    for scene in "${scenes[@]}"; do
        if [ ! -f "${scenes_dir}/${scene}" ]; then
            if curl --connect-timeout 20 --max-time 30 --retry 2 -o "${scenes_dir}/${scene}" "${GCS_SCENES}/${scene}" 2>/dev/null; then
                log "[SUCCESS] Downloaded scene: $scene"
            else
                log_error "Failed to download scene: $scene"
            fi
        fi
    done
}

download_media_files() {
    if ! fresh_due "media_files"; then
        log_debug "[MEDIA] Skipped (cached, last successful fetch <12h ago)"
        return 0
    fi

    if curl --connect-timeout 20 --max-time 30 --retry 2 -o download_media.py "${GCS_MEDIA}/download_media.py" 2>/dev/null; then
        log_debug "[SUCCESS] Downloaded download_media.py"
    else
        log_error "Failed to download download_media.py"
        return 1
    fi

    python3 -c "import requests" 2>/dev/null || pip3 install requests 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG" || log_error "Failed to install requests package"

    if python3 download_media.py >/dev/null 2>&1; then
        log_debug "[SUCCESS] Media files downloaded"
        # Only mark fresh on a clean end-to-end success — a failed media
        # script run leaves the stamp untouched so the next tick retries.
        fresh_mark "media_files"
    else
        log_error "Failed to download media files"
    fi
}

download_virtualmic_script() {
    local file="/etc/pulse/default.pa.d/VirtualMic.pa"
    local content="load-module module-null-sink sink_name=OBSMonitor sink_properties=device.description=OBSMonitor\nload-module module-remap-source source_name=VirtualMic master=OBSMonitor.monitor source_properties=device.description=VirtualMic\nset-default-source VirtualMic"

    if [ ! -f "$file" ]; then
        echo -e "$content" | sudo tee "$file" > /dev/null
        log "VirtualMic settings saved to $file."
    else
        log_debug "VirtualMic settings already exist in $file."
    fi
}

download_evo_utils() {
    local evo_utils_dir="$HOME/evo-utils"
    local should_download=false

    if [ ! -d "$evo_utils_dir" ]; then
        should_download=true
        log "evo-utils directory not found, will download"
    elif [ -n "$(find "$evo_utils_dir" -maxdepth 0 -mtime +0)" ]; then
        should_download=true
        log "evo-utils directory is older than 24 hours, will download"
    fi

    if [ "$should_download" = true ]; then
        if curl --connect-timeout 20 --max-time 60 --retry 2 -o evo-utils.tar.gz "${GCS_UTILS}/evo-utils.tar.gz" 2>/dev/null; then
            # run_logged, not `| tee`: without pipefail the pipe reports tee's
            # status, so a failed extraction was logged as a success.
            if run_logged tar -xzf evo-utils.tar.gz; then
                rm evo-utils.tar.gz
                touch "$evo_utils_dir"
                log "[SUCCESS] evo-utils downloaded and extracted"
            else
                log_error "Failed to extract evo-utils"
                rm -f evo-utils.tar.gz
            fi
        else
            log_error "Failed to download evo-utils"
        fi
    else
        log_debug "evo-utils is up to date, skipping download"
    fi

    # Install zowie-utils Python requirements once (bump version string to re-run)
    local zowie_pip_flagfile="$HOME/.zowie_pip_requirements_v2"
    if [ ! -f "$zowie_pip_flagfile" ]; then
        log "Installing zowie-utils Python requirements..."
        if ! command -v python3 &>/dev/null; then
            run_apt_update_if_needed
            sudo apt install -y python3 python3-pip 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"
        elif ! command -v pip3 &>/dev/null; then
            run_apt_update_if_needed
            sudo apt install -y python3-pip 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"
        fi
        local req_file="$HOME/evo-utils/zowie-utils/requirements.txt"
        if [ -f "$req_file" ]; then
            pip3 install -r "$req_file" 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG" && \
                touch "$zowie_pip_flagfile" && \
                log "[SUCCESS] zowie-utils requirements installed"
        else
            log "[WARN] zowie-utils requirements.txt not found, skipping pip install"
        fi
    fi
}

download_and_run_telemetry() {
    # A cutover marker is never removed or bypassed, including during rollback.
    if [ -e "$EVO_CACHE_DIR/observability-cutover-v1.json" ]; then
        log_debug "[TELEMETRY] Disabled by local observability cutover"
        return 0
    fi
    local telemetry_script_url="${GCS_MONITORING}/evosports-telemetry.sh"
    local telemetry_script="$EVOSPORTS_ROOT/evosports-telemetry.sh"
    local last_run_flag="$EVOSPORTS_ROOT/.telemetry_last_run"

    # Download the telemetry script if it doesn't exist or is older than 24 hours.
    # Script content changes rarely, so polling GCS every 5 min is wasteful.
    if [[ ! -f "$telemetry_script" ]] || [[ $(find "$telemetry_script" -mmin +1440 -print) ]]; then
        log_debug "[TELEMETRY] Downloading telemetry script from $telemetry_script_url"
        curl --connect-timeout 20 --max-time 30 --retry 2 -s -o "$telemetry_script" "$telemetry_script_url"

        if [[ $? -ne 0 || ! -s "$telemetry_script" ]]; then
            log_error "[TELEMETRY] Failed to download telemetry script"
            return 1
        fi

        chmod +x "$telemetry_script"
        log_debug "[TELEMETRY] Telemetry script downloaded successfully"
    fi

    # Throttle execution to at most once per 20 minutes. Each install tick is
    # 5 min now, so without this guard we would ship metrics 3× more often
    # than needed. Missing flag = never run = run now.
    if [[ -f "$last_run_flag" ]] && [[ -z $(find "$last_run_flag" -mmin +20 -print) ]]; then
        log_debug "[TELEMETRY] Skipped — last run <20 min ago"
        return 0
    fi

    # Run the telemetry script
    if [[ -x "$telemetry_script" ]]; then
        log_debug "[TELEMETRY] Running telemetry script"
        "$telemetry_script" >> "$EVOSPORTS_INSTALL_LOG" 2>&1

        if [[ $? -eq 0 ]]; then
            touch "$last_run_flag"
            log "[TELEMETRY] Telemetry update sent"
        else
            log_error "[TELEMETRY] Telemetry script execution failed"
        fi
    else
        log_error "[TELEMETRY] Telemetry script not executable or doesn't exist"
        return 1
    fi

    return 0
}

#===============================================================================
# INSTALLATION FUNCTIONS
#===============================================================================

install_intel_driver() {
    if [ -f /usr/share/keyrings/intel-graphics.gpg ]; then
        log "[INFO] Intel GPU key already present — skipping import"
    elif wget --timeout=20 --tries=2 -qO - https://repositories.intel.com/gpu/intel-graphics.key 2>/dev/null | \
        sudo gpg --dearmor --output /usr/share/keyrings/intel-graphics.gpg 2>/dev/null; then
        log "[SUCCESS] Intel GPU key added"
    else
        log_error "Failed to add Intel GPU key"
        return 1
    fi

    local intel_repo_line='deb [arch=amd64,i386 signed-by=/usr/share/keyrings/intel-graphics.gpg] https://repositories.intel.com/gpu/ubuntu jammy client'
    local intel_repo_file=/etc/apt/sources.list.d/intel-gpu-jammy.list
    if [ -f "$intel_repo_file" ] && grep -qF "$intel_repo_line" "$intel_repo_file"; then
        log "[INFO] Intel GPU repository already configured — skipping"
    else
        if echo "$intel_repo_line" | sudo tee "$intel_repo_file" > /dev/null; then
            log "[SUCCESS] Intel GPU repository added"
        else
            log_error "Failed to add Intel GPU repository"
            return 1
        fi
    fi

    sudo apt update || log_error "apt update failed after adding Intel repository"

    if sudo apt install -y \
        intel-opencl-icd intel-level-zero-gpu level-zero \
        intel-media-va-driver-non-free libmfx1 libmfxgen1 libvpl2 \
        libegl-mesa0 libegl1-mesa libegl1-mesa-dev libgbm1 libgl1-mesa-dev libgl1-mesa-dri \
        libglapi-mesa libgles2-mesa-dev libglx-mesa0 libigdgmm12 libxatracker2 mesa-va-drivers \
        mesa-vdpau-drivers mesa-vulkan-drivers va-driver-all vainfo hwinfo clinfo 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
        log "[SUCCESS] Intel drivers installed"
    else
        log_error "Failed to install Intel drivers"
    fi
}

install_splashtop_host() {
    local splashtop_url="${GCS_BASE}/Splashtop_Streamer_Ubuntu_amd64.deb"

    if wget --timeout=60 --tries=2 -O /tmp/splashtop.deb "$splashtop_url" 2>/dev/null; then
        log "[SUCCESS] Splashtop package downloaded"
    else
        log_error "Failed to download Splashtop package"
        return 1
    fi

    sudo apt update || log_error "apt update failed before Splashtop installation"

    if sudo apt install -y /tmp/splashtop.deb 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
        rm /tmp/splashtop.deb
        if splashtop-streamer deploy "$SPLASHTOP_DEPLOYMENT_ID" 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] Splashtop Host has been installed."
        else
            log_error "Failed to deploy Splashtop with deployment ID"
        fi
    else
        log_error "Failed to install Splashtop package"
        rm -f /tmp/splashtop.deb
    fi
}

install_teamviewer_host() {
    local teamviewer_url="https://download.teamviewer.com/download/linux/teamviewer-host_amd64.deb"

    if wget --timeout=60 --tries=2 -O teamviewer-host.deb "$teamviewer_url" 2>/dev/null; then
        log "[SUCCESS] TeamViewer package downloaded"
    else
        log_error "Failed to download TeamViewer package"
        return 1
    fi

    if sudo apt install ./teamviewer-host.deb 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
        rm teamviewer-host.deb
        if teamviewer --daemon start 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] TeamViewer Host has been installed."
        else
            log_error "Failed to start TeamViewer daemon"
        fi
    else
        log_error "Failed to install TeamViewer package"
        rm -f teamviewer-host.deb
    fi
}

get_tailscale_desired_tags() {
    if [ -f "$HOME/.evo-beta-deployment" ]; then
        echo "tag:evobox,tag:beta-deployment"
    else
        echo "tag:evobox,tag:prod-deployment"
    fi
}

# Print the BackendState of a `tailscale status --json` document, or return 1.
#
# `jq -s` (slurp) is what makes this a COMPLETE parse. Plain `jq .BackendState`
# answers from the first document it manages to read and ignores whatever
# follows, so valid bytes at the front with trailing garbage, or two
# concatenated documents, would be judged on a prefix — and the answer decides
# whether this device re-registers itself. Exactly one top-level object with a
# non-empty STRING BackendState qualifies; jq's own exit status is the only
# thing consulted here, the CLI's is the caller's to check.
_tailscale_backend_state() {
    local state
    state=$(printf '%s' "$1" | jq -ser '
        if (length == 1
            and (.[0] | type) == "object"
            and (.[0].BackendState | type) == "string"
            and ((.[0].BackendState | length) > 0))
        then .[0].BackendState
        else empty
        end' 2>/dev/null) || return 1
    [ -n "$state" ] || return 1
    printf '%s\n' "$state"
}

install_tailscale() {
    if ! check_command "tailscale"; then
        log "[TAILSCALE] Installing..."
        # `set +e` without pipefail: the old `if curl | sh | tee` form tested
        # tee's status, so a failed download or a failed installer still logged
        # "[SUCCESS]" and fell through to a CLI that does not exist. Snapshot
        # PIPESTATUS immediately and judge curl and sh on their own results.
        local -a install_rc=()
        curl --connect-timeout 20 --max-time 60 --retry 2 -fsSL https://tailscale.com/install.sh | sh 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"
        install_rc=("${PIPESTATUS[@]}")
        if [ "${install_rc[0]}" -ne 0 ]; then
            log_error "[TAILSCALE] Installer download failed (curl exit ${install_rc[0]})"
            return 1
        fi
        if [ "${install_rc[1]}" -ne 0 ]; then
            log_error "[TAILSCALE] Installer script failed (exit ${install_rc[1]})"
            return 1
        fi
        if ! check_command "tailscale"; then
            log_error "[TAILSCALE] Installer reported success but the CLI is missing"
            return 1
        fi
        log "[SUCCESS] Tailscale installed"
    fi

    local desired_tags
    desired_tags=$(get_tailscale_desired_tags)

    # Registration is driven by BackendState, and only two states may touch this
    # node's identity. The old code treated every non-Running state — including
    # a transient network blip, a failed status command, or unparseable JSON —
    # as "authenticate with the auth key", and that re-registers the node as a
    # NEW machine: the old record goes offline, the new one collides on hostname
    # and gets a "-1" suffix plus a fresh Tailscale IP. So the command result
    # and the parsed JSON are checked separately (a successful jq must not mask
    # a failed CLI), and anything unrecognised is a no-op for this tick: no up,
    # no logout, no tailscaled restart, no state wipe.
    local status_json status_rc ts_state state_rc up_rc
    status_json=$(tailscale status --json 2>/dev/null)
    status_rc=$?
    if [ "$status_rc" -ne 0 ]; then
        log_error "[TAILSCALE] status command failed (exit $status_rc); skipping registration this tick"
        return 1
    fi
    ts_state=$(_tailscale_backend_state "$status_json")
    state_rc=$?
    if [ "$state_rc" -ne 0 ] || [ -z "$ts_state" ]; then
        log_error "[TAILSCALE] status JSON is not a single object with a usable BackendState; skipping registration this tick"
        return 1
    fi

    case "$ts_state" in
        Running)
            log_debug "[TAILSCALE] Backend Running; existing registration kept"
            ;;
        NeedsLogin)
            # The one state that genuinely needs a login. Bounded so a stuck
            # control-plane connection cannot hold the tick to the watchdog.
            log "[TAILSCALE] Backend NeedsLogin; registering with auth key"
            sudo tailscale up \
                --auth-key="$TAILSCALE_AUTH_CREDENTIAL" \
                --advertise-tags="$desired_tags" \
                --posture-checking \
                --timeout=30s 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"
            up_rc=${PIPESTATUS[0]}
            if [ "$up_rc" -ne 0 ]; then
                log_error "[TAILSCALE] Login failed (exit $up_rc); retrying next tick"
                return 1
            fi
            log "[SUCCESS] Tailscale authenticated"
            ;;
        Stopped)
            # Stored settings only: no auth key, no tags, no --reset. This
            # resumes the existing node instead of minting a new one. If the CLI
            # demands the non-default flags back, record the failure and let the
            # next tick retry rather than guessing at a preference set.
            log "[TAILSCALE] Backend Stopped; resuming with stored settings"
            sudo tailscale up --timeout=30s 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"
            up_rc=${PIPESTATUS[0]}
            if [ "$up_rc" -ne 0 ]; then
                log_error "[TAILSCALE] Resume failed (exit $up_rc); leaving stored settings untouched"
                return 1
            fi
            log "[SUCCESS] Tailscale resumed from stored settings"
            ;;
        NeedsMachineAuth)
            # An operator must approve the device in the admin console; no
            # amount of re-registration works around it.
            log_error "[TAILSCALE] Backend NeedsMachineAuth; device approval required"
            observe_tailscale_alert TAILSCALE_AUTH_BLOCKED failed "state=NeedsMachineAuth" "status"
            return 1
            ;;
        *)
            log_error "[TAILSCALE] Backend state $ts_state is not actionable; skipping registration this tick"
            return 1
            ;;
    esac

    # Re-read after an `up` so preferences are only written against a state we
    # actually observed, never against the state we hoped `up` produced.
    if [ "$ts_state" != "Running" ]; then
        status_json=$(tailscale status --json 2>/dev/null)
        status_rc=$?
        ts_state=""
        # Same completeness rule as the entry read: an `up` that produced a
        # half-written status document proves nothing about the backend.
        if [ "$status_rc" -eq 0 ]; then
            ts_state=$(_tailscale_backend_state "$status_json") || ts_state=""
        fi
        if [ "$ts_state" != "Running" ]; then
            log_error "[TAILSCALE] Backend is ${ts_state:-unreadable} after up; deferring posture preferences"
            return 1
        fi
    fi

    # An observed Running backend closes the *status-sourced* auth-blocked
    # alert. A device API path that is still returning 401/403 keeps its own
    # source failing, so the event stays open until that path recovers too.
    observe_tailscale_alert TAILSCALE_AUTH_BLOCKED healthy "state=Running" "status"

    # Enable posture checking if not already enabled (for existing devices).
    #
    # The CLI result and the parsed JSON are judged apart, and the document has
    # to be whole: `tailscale debug prefs | jq -r .PostureChecking` reports the
    # pipeline's last exit status, so a CLI that failed after printing a
    # parseable `false` (or printed two documents, or a valid object followed
    # by garbage) would still answer "off" and drive a `tailscale set` on top of
    # an admin-set value, every five minutes.
    local prefs_raw prefs_rc posture_enabled=""
    prefs_raw=$(tailscale debug prefs 2>/dev/null)
    prefs_rc=$?
    if [ "$prefs_rc" -eq 0 ]; then
        posture_enabled=$(printf '%s' "$prefs_raw" | jq -ser '
            if (length == 1
                and (.[0] | type) == "object"
                and (.[0].PostureChecking | type) == "boolean")
            then (.[0].PostureChecking | tostring)
            else empty
            end' 2>/dev/null) || posture_enabled=""
    else
        log_error "[TAILSCALE] tailscale debug prefs failed (rc=${prefs_rc}); leaving preferences untouched"
    fi
    case "$posture_enabled" in
        true)
            log_debug "[TAILSCALE] Posture checking already enabled"
            ;;
        false)
            log "[TAILSCALE] Enabling posture checking..."
            run_logged sudo tailscale set --posture-checking \
                || log_error "[TAILSCALE] Failed to enable posture checking"
            ;;
        *)
            # An unreadable preference is not evidence that it is off; writing
            # on a guess would fight an admin-set value every five minutes.
            log_error "[TAILSCALE] Could not read PostureChecking preference; leaving preferences untouched"
            ;;
    esac
}

# Response buffers for the Tailscale device API, and the ONE place they are
# removed.
#
# Every API body this device reads lands in a temp file. The normal returns
# already delete theirs, but a tick killed by the 600s watchdog (SIGTERM) does
# not run any of them, and these functions run 288 times a day: the leftovers
# accumulate in /tmp until a reboot. They also hold a device record, so they
# are created 0600.
#
# The fix is deliberately NOT a trap inside these functions. `trap ... EXIT` is
# process-global with a single slot: setting one here would silently discard
# main()'s watchdog reaper, leaving a watchdog subshell alive to SIGTERM an
# unrelated process ten minutes later. Saving and restoring the caller's trap
# string is the other classic answer and is worse — it is unreadable and it
# races with itself on nesting. So buffers are simply REGISTERED here and
# removed by the one cleanup function main() already installs
# (_evo_install_cleanup), which covers the normal exit and, via the two signal
# traps that turn a kill into an ordinary exit, the watchdog's SIGTERM too.
_EVO_TEMP_BUFFERS=()

# Create a registered 0600 buffer and publish its path in _TS_BUFFER_PATH.
# Returns 1 if none could be made.
#
# The path is handed back through a global, NOT printed. `f=$(_buffer_new)`
# would run the whole function in a command-substitution subshell, where the
# registration below lands in a copy of the array that dies with it — the
# buffer would be created and never registered, which is precisely the leak
# this exists to prevent.
_TS_BUFFER_PATH=""
_tailscale_buffer_new() {
    _TS_BUFFER_PATH=""
    local file
    file=$(mktemp "${TMPDIR:-/tmp}/evo-ts-name.XXXXXX" 2>/dev/null) || return 1
    [ -n "$file" ] || return 1
    chmod 600 "$file" 2>/dev/null
    _EVO_TEMP_BUFFERS[${#_EVO_TEMP_BUFFERS[@]}]="$file"
    _TS_BUFFER_PATH="$file"
    return 0
}

# Remove one registered buffer as soon as its owner is finished with it, so a
# long tick does not hold every body it has read. Always returns 0.
_tailscale_buffer_release() {
    local want="$1" file
    local -a keep=()
    [ -n "$want" ] && rm -f "$want" 2>/dev/null
    for file in "${_EVO_TEMP_BUFFERS[@]}"; do
        [ -n "$file" ] || continue
        [ "$file" = "$want" ] && continue
        keep[${#keep[@]}]="$file"
    done
    _EVO_TEMP_BUFFERS=()
    for file in "${keep[@]}"; do
        _EVO_TEMP_BUFFERS[${#_EVO_TEMP_BUFFERS[@]}]="$file"
    done
    return 0
}

# Remove every buffer still registered. Always returns 0: it runs from an exit
# path and must never change the script's exit status.
_evo_cleanup_temp_buffers() {
    local file
    for file in "${_EVO_TEMP_BUFFERS[@]}"; do
        [ -n "$file" ] && rm -f "$file" 2>/dev/null
    done
    _EVO_TEMP_BUFFERS=()
    return 0
}

# Single entry point for this device's Tailscale device API calls.
#
#   _tailscale_api_request METHOD RELATIVE_PATH BODY OUTPUT_FILE
#
# RELATIVE_PATH is restricted to the endpoints this program generates for its
# OWN node record — device/<id>, device/<id>/name, device/<id>/tags, with an
# optional ?fields=all — resolved against a fixed API base, so a malformed or
# attacker-influenced node ID can never redirect the request to another host or
# another API surface. The caller URI-encodes the ID (jq @uri).
#
# Response body -> OUTPUT_FILE. stdout carries ONLY the HTTP status (empty when
# curl never got one); logs go to stderr so stdout stays machine-readable. The
# return value reflects curl TRANSPORT success only, so callers must check both:
# transport OK + HTTP code. A transport timeout does NOT mean the mutation was
# not applied, which is why name/delete carry no curl --retry — the next tick
# re-reads remote state instead of blindly re-sending. GET and tag POST keep the
# pre-existing retry behaviour (idempotent, smooths transient 429/5xx).
#
# The OAuth client secret and the minted Bearer token are fed on stdin
# (--data-urlencode "@-" / -K -) so neither lands in curl's argv where any local
# user could read it via ps/procfs. The token lives only in this call's memory:
# never a receipt, never a log line.
_tailscale_api_request() {
    local method="$1"
    local relative_path="$2"
    local body="$3"
    local output_file="$4"

    local api_base="https://api.tailscale.com/api/v2"

    case "$method" in
        GET|POST|DELETE) ;;
        *)
            log_error "[TAILSCALE] Rejected API method '${method}'" >&2
            return 1
            ;;
    esac

    if ! [[ "$relative_path" =~ ^device/[A-Za-z0-9._~%-]+(/name|/tags)?(\?fields=all)?$ ]]; then
        log_error "[TAILSCALE] Rejected API path '${relative_path}'" >&2
        return 1
    fi

    if [ -z "$output_file" ]; then
        log_error "[TAILSCALE] API request needs an output file" >&2
        return 1
    fi
    if ! : > "$output_file" 2>/dev/null; then
        log_error "[TAILSCALE] Cannot write API output file ${output_file}" >&2
        return 1
    fi

    if [ -z "$TAILSCALE_OAUTH_SECRET" ]; then
        log_error "[TAILSCALE] No OAuth client secret available for API request" >&2
        return 1
    fi

    # grant_type is non-sensitive so it stays on argv; the documented
    # client_credentials form guards against a future API tightening.
    #
    # The status code is appended to the body by curl's own -w format instead of
    # being captured with -o: the response carries the minted bearer token, and
    # writing it to a file would put a live credential on disk. Body and code
    # are split in memory and the body is dropped immediately afterwards.
    local token_response token_rc token token_code token_body
    token_response=$(printf '%s' "$TAILSCALE_OAUTH_SECRET" \
        | curl -s --connect-timeout 20 --max-time 30 --retry 2 \
            -w '\n%{http_code}' \
            -d "grant_type=client_credentials" \
            --data-urlencode "client_secret@-" \
            "${api_base}/oauth/token" 2>/dev/null)
    token_rc=$?
    token_code="${token_response##*$'\n'}"
    token_body="${token_response%$'\n'*}"
    token_response=""
    [[ "$token_code" =~ ^[0-9]{3}$ ]] || token_code=""
    if [ "$token_rc" -ne 0 ]; then
        log_error "[TAILSCALE] OAuth token exchange transport failure (curl ${token_rc})" >&2
        return 1
    fi
    # An authorization failure minting the token is the same operator-actionable
    # condition as a 401/403 on the device call itself, so it is reported
    # through the documented stdout status contract rather than being flattened
    # into a generic failure the caller cannot distinguish.
    case "$token_code" in
        401|403)
            token_body=""
            printf '%s' "$token_code"
            log_error "[TAILSCALE] OAuth token exchange rejected (HTTP ${token_code})" >&2
            return 0
            ;;
    esac
    # Only ONE complete JSON object carrying a non-empty access_token STRING is
    # a token response. This is a single `jq -s` (slurp) gate because the
    # alternatives all fail open:
    #   * plain `jq .access_token` treats the body as a STREAM, so two
    #     concatenated documents print two lines and command substitution glues
    #     them into one bogus credential;
    #   * `jq -r` would flatten a number, object, array or `true` into
    #     argv-looking text;
    #   * a value containing CR or LF becomes extra lines in the `-K -` config
    #     below, i.e. attacker-chosen curl options.
    # Slurping makes a concatenated response length 2 (rejected), an array or
    # scalar fail the type test, and a valid prefix followed by garbage fail to
    # parse at all. Anything but the one good shape leaves $token empty and the
    # device request is never made.
    token=$(printf '%s' "$token_body" | jq -sr '
        if length == 1 then .[0] else empty end
        | select(type == "object")
        | select((.access_token | type) == "string")
        | select((.access_token | length) > 0)
        | select((.access_token | test("[\r\n]")) | not)
        | .access_token' 2>/dev/null)
    token_body=""
    if [ "$token_code" != "200" ] || [ -z "$token" ]; then
        # No status is printed: nothing was sent to the device endpoint, and the
        # stdout contract is "the HTTP status of the device call". Forwarding the
        # token exchange's own 200 here would read as a successful device call.
        token=""
        log_error "[TAILSCALE] OAuth token exchange returned no usable access token (HTTP ${token_code:-none})" >&2
        return 1
    fi

    local -a curl_args=(
        -s -o "$output_file" -w '%{http_code}'
        --connect-timeout 20 --max-time 30
        -X "$method" -K -
    )
    case "${method} ${relative_path}" in
        GET\ *|POST\ */tags) curl_args+=(--retry 2) ;;
    esac
    if [ -n "$body" ]; then
        curl_args+=(-H "Content-Type: application/json" --data-binary "$body")
    fi

    local http_code request_rc
    http_code=$(printf 'header = "Authorization: Bearer %s"\n' "$token" \
        | curl "${curl_args[@]}" "${api_base}/${relative_path}" 2>/dev/null)
    request_rc=$?
    token=""

    printf '%s' "$http_code"

    if [ "$request_rc" -ne 0 ]; then
        log_error "[TAILSCALE] API ${method} ${relative_path} transport failure (curl ${request_rc})" >&2
        return 1
    fi
    return 0
}

# Print this device's OWN node id from a `tailscale status --json` document, or
# nothing. Every caller here feeds the result into an API path that can delete
# or rename a device record, so the document is judged structurally, not by
# `jq -r '.Self.ID // empty'`: that lenient form also prints a number, a
# boolean, or jq's rendering of an object/array, and any of those would become
# the device id in a mutating request against a record this device never
# confirmed as its own. A Running backend with a non-empty STRING id is the
# only shape that qualifies.
_tailscale_status_self_id() {
    printf '%s' "$1" | jq -ser '
        if length == 1 then .[0] else empty end
        | select(type == "object")
        | select((.BackendState | type) == "string" and .BackendState == "Running")
        | select((.Self | type) == "object")
        | select((.Self.ID | type) == "string" and (.Self.ID | length) > 0)
        | .Self.ID' 2>/dev/null
}

# Change this device's tags IN PLACE via the Tailscale API (POST device/{id}/tags),
# preserving the device record, node identity, machine name, and Tailscale IP.
#
# Contrast with `tailscale up --force-reauth`, which re-registers the node as a
# NEW machine: the old record goes offline and the new registration collides on
# hostname, getting a "-1" suffix (e.g. evobox-oem-0015-1) plus a fresh IP — which
# also breaks the pinned sshd ListenAddress until the next install run. Verified
# on evobox-oem-0015: repeated API retags stay on one nodeId/name/IP, while a
# single --force-reauth immediately spawned a "-1" node.
#
# Uses the shared _tailscale_api_request() helper (OAuth client secret ->
# short-lived API token, both kept off curl's argv). Returns 0 only on HTTP 200.
_retag_tailscale_via_api() {
    local desired_csv="$1"   # e.g. "tag:evobox,tag:beta-deployment"

    # The CLI result and the parsed JSON are judged separately: `set +e` with no
    # pipefail means a jq that happily prints nothing would otherwise hide a
    # failed `tailscale status`. Only a Running backend with its own node id may
    # be retagged — retagging a node id read from a stale or half-initialized
    # status is a write against a record that may not be this device.
    local status_json status_rc backend node_id
    status_json=$(tailscale status --json 2>/dev/null)
    status_rc=$?
    if [ "$status_rc" -ne 0 ] || [ -z "$status_json" ]; then
        log_error "[TAILSCALE] status command failed (exit ${status_rc}); skipping API retag"
        return 1
    fi
    if ! printf '%s' "$status_json" | jq -e 'type == "object"' >/dev/null 2>&1; then
        log_error "[TAILSCALE] status returned unparseable JSON; skipping API retag"
        return 1
    fi
    backend=$(printf '%s' "$status_json" | jq -r '
        if (.BackendState | type) == "string" then .BackendState else "" end' 2>/dev/null)
    if [ "$backend" != "Running" ]; then
        log_error "[TAILSCALE] Backend is ${backend:-unknown}, not Running; skipping API retag"
        return 1
    fi
    node_id=$(_tailscale_status_self_id "$status_json")
    if [ -z "$node_id" ]; then
        log_error "[TAILSCALE] Could not determine node ID; skipping API retag"
        return 1
    fi

    # URI-encode the ID before it becomes part of the request path.
    local node_id_enc
    node_id_enc=$(printf '%s' "$node_id" | jq -rR '@uri' 2>/dev/null)
    if [ -z "$node_id_enc" ]; then
        log_error "[TAILSCALE] Could not encode node ID; skipping API retag"
        return 1
    fi

    # Comma-separated tags -> JSON array: ["tag:evobox","tag:beta-deployment"]
    local tags_json
    tags_json=$(printf '%s' "$desired_csv" | jq -R -c 'split(",")' 2>/dev/null)
    if [ -z "$tags_json" ]; then
        log_error "[TAILSCALE] Could not build tags payload; skipping API retag"
        return 1
    fi

    local response_file
    if ! _tailscale_buffer_new; then
        log_error "[TAILSCALE] Could not create temp file for API retag"
        return 1
    fi
    response_file="$_TS_BUFFER_PATH"

    local api_path="device/${node_id_enc}/tags"
    local http_code request_rc
    http_code=$(_tailscale_api_request \
        "POST" "$api_path" "{\"tags\":${tags_json}}" "$response_file")
    request_rc=$?
    _tailscale_buffer_release "$response_file"

    # Auth observations are scoped to this exact method/path: a 200 here says
    # nothing about the name-repair calls, and vice versa.
    local alert_source="api:POST ${api_path}"
    if [ "$request_rc" -eq 0 ]; then
        case "$http_code" in
            200)
                observe_tailscale_alert TAILSCALE_AUTH_BLOCKED healthy \
                    "api=retag http=200" "$alert_source"
                return 0
                ;;
            401|403)
                observe_tailscale_alert TAILSCALE_AUTH_BLOCKED failed \
                    "api=retag http=${http_code}" "$alert_source"
                ;;
        esac
    fi
    log_error "[TAILSCALE] API retag failed (HTTP ${http_code:-none}) for node ${node_id}"
    return 1
}

update_tailscale_tags() {
    if ! check_command "tailscale"; then
        log_error "[TAILSCALE] Not installed, skipping tag update"
        return 1
    fi

    local desired_tags
    desired_tags=$(get_tailscale_desired_tags)

    # Two-tier gate over the retag path, deliberately independent of
    # `tailscale status` (which returns stale/empty tags mid-transition and used
    # to trigger spurious re-runs — and, via the old --force-reauth path, repeated
    # node re-registrations):
    #   1. Content: the flag stores the last tags we applied, so a channel switch
    #      (prod<->beta) is detected as a flag mismatch and applied immediately.
    #   2. Periodic reconcile: even when the desired set is unchanged, re-assert
    #      the tags once per EVO_GCS_FRESHNESS_TTL so out-of-band drift (admin
    #      console edit, ACL/posture change, or a stale flag baked into a
    #      provisioning image) self-heals instead of sticking forever. Re-asserting
    #      is a cheap idempotent API POST. fresh_due also honors
    #      $EVO_FORCE_REFRESH_FLAG, so `touch ~/.evo-force-refresh` forces a
    #      re-assert on the next tick, same as every other gated operation.
    local flag="$EVO_CACHE_DIR/tailscale-tags.applied"
    local reconcile_op="tailscale-tags-reconcile"
    local last_applied=""
    [ -f "$flag" ] && last_applied=$(cat "$flag" 2>/dev/null)

    # A tag POST has no read-only equivalent: the only thing that can settle a
    # 401/403 on device/<id>/tags is another tag POST. So the TTL gate may not
    # silence this path while its authorization is unsettled — neither while
    # the failure is still open (the operator is waiting for it to clear) nor
    # while its recovery is announced but undelivered (a relapse in that window
    # would otherwise go unseen and the queued "Recovered" would be a lie).
    local owed_sources owed_retag=false
    owed_sources=$(_tailscale_alert_unsettled_sources)
    case "$owed_sources" in
        *"api:POST device/"*"/tags"*) owed_retag=true ;;
    esac

    if [ "$last_applied" = "$desired_tags" ] && ! fresh_due "$reconcile_op" \
        && [ "$owed_retag" != true ]; then
        log_debug "[TAILSCALE] Desired tags unchanged ($desired_tags) and within reconcile TTL; skipping"
        return 0
    fi

    if [ "$last_applied" != "$desired_tags" ]; then
        log "[TAILSCALE] Desired tags changed (${last_applied:-none} -> $desired_tags); updating in place"
    elif [ "$owed_retag" = true ]; then
        log "[TAILSCALE] Tag authorization is unsettled; re-asserting tags ($desired_tags) to settle it"
    else
        log "[TAILSCALE] Reconciling tags ($desired_tags) after TTL/force-refresh; re-asserting in place"
    fi

    # In-place API retag only (keeps nodeId, machine name, and Tailscale IP).
    # There is deliberately no re-auth fallback: `tailscale up --force-reauth`
    # re-registers the node as a new machine, so an unreachable or unauthorized
    # API — a 401, a 503, a timeout — was by itself enough to rename the device
    # to a "-1" suffix and move its IP. A failed retag leaves the current tags
    # in place and returns; the five-minute tick retries.
    if ! _retag_tailscale_via_api "$desired_tags"; then
        log_error "[TAILSCALE] API retag failed; keeping current tags, retrying next tick"
        return 1
    fi
    log "[SUCCESS] Tailscale tags updated in place via API"

    # Record the reconcile stamp + applied tag set only on the success path so a
    # failure retries on the next tick (fresh_mark's success-only semantics).
    # fresh_mark runs first because it creates $EVO_CACHE_DIR the flag write needs.
    fresh_mark "$reconcile_op"
    printf '%s\n' "$desired_tags" > "$flag"

    local updated_tags
    updated_tags=$(tailscale status --json 2>/dev/null | jq '.Self.Tags' 2>/dev/null)
    log "[TAILSCALE] Current tags: $updated_tags"
}

#===============================================================================
# TAILSCALE MACHINE-NAME RECONCILIATION (issue #33)
#===============================================================================
# A node that re-registers instead of re-authenticating collides with its own
# stale record and lands on a "-1" machine name (evobox-oem-0015-1). Tailscale
# never restores the original name once the collision clears, so every
# MagicDNS-based path to the device stays wrong until someone opens the Admin
# Console.
#
# This block repairs that, but only where the device can PROVE which stale
# record is its own: the old node id must have been observed AND recorded by
# this very device on an earlier tick, and the control plane must still agree
# about the current node. A "-1" suffix is not proof of identity, so it never by
# itself authorizes a DELETE. Anything ambiguous — an unknown collision, a
# rewritten receipt, a machine-id change, an API error — is left exactly as it
# is and reported once through observe_tailscale_alert NAME_REPAIR_SKIPPED for
# an operator to finish manually. No local Tailscale state is ever touched: this
# code never runs `tailscale up`, `down`, `logout`, or restarts tailscaled, so a
# healthy SSH/OBS session can never be interrupted by a naming problem.
#
# Receipt: $HOME/.evo-tailscale-identity.json (0600, atomic, changed-only)
#   {"version":1,"machine_id":"...","canonical_name":"evobox-oem-0015",
#    "node_ids":["n-old","n-current"],"consumed_node_ids":["n-old"],
#    "pending_repair":null}
# pending_repair binds an earned eligibility to one current node id so that a
# tick killed by the watchdog between "old record deleted" and "renamed" can
# resume instead of starting over with no history left to prove anything.
#
# consumed_node_ids is the other half of that: the ids this device has already
# spent on a completed repair. They stay in node_ids forever (the history is
# what proves a record was ever ours), but a spent id must never authorize a
# SECOND delete — a later, unrelated collision would otherwise be "proven" by
# a node id whose record this device deleted long ago and can no longer vouch
# for. Version stays 1: a receipt written before this field simply loads it as
# empty, which is exactly the pre-existing behaviour.
#
# Each device API call is allowed 30s by curl, and a single step of the repair
# can chain several of them (an OAuth token exchange plus its retried GET is
# already ~90s worst case), so the whole repair yields once this much of the
# 600s watchdog budget is left. 300s is deliberately conservative: it covers
# that chain and still leaves the VNC configuration and the alert flush that
# run after this function inside the same tick. Deferring is always safe — the
# pending repair is already on disk and the next tick resumes from it.
readonly TAILSCALE_NAME_API_HEADROOM_SECONDS=300

# Freshness op for the ONE state this function cannot act on: the name is not
# canonical and no stale record this device can prove exists, so the repair is
# an operator's job in the Admin Console. That verdict is already paged
# (NAME_REPAIR_SKIPPED) and nothing the device does changes it, yet re-deriving
# it costs an OAuth token exchange plus a device GET every five minutes — 576
# API calls a day, forever, on exactly the population this feature exists to
# find. The stamp bounds that to the usual 12h cadence; ~/.evo-force-refresh
# still reopens it on demand, same as every other gated operation.
readonly TAILSCALE_NAME_SKIP_OP="tailscale-name-repair-skipped"

# _tailscale_name_label VALUE DNS_SUFFIX
#   Normalize a Tailscale machine name to its bare DNS label on stdout, or
#   return 1 when VALUE is not a name this device may reason about.
#
#   Accepts a single label ("evobox-oem-0015") or an FQDN that ends in exactly
#   ".DNS_SUFFIX" with one label in front ("evobox-oem-0015.tail8e5b73.ts.net",
#   trailing dot optional). A name under a *different* suffix is rejected rather
#   than truncated at the first dot: same first label in another tailnet is a
#   different machine, and treating it as ours would authorize deleting it.
_tailscale_name_label() {
    local value="$1" suffix="$2"

    [ -n "$value" ] || return 1
    value="${value%.}"          # at most one trailing root dot
    # `tr`, not ${value,,}: macOS ships bash 3.2 and the test fixtures run there.
    value=$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]')
    [ -n "$value" ] || return 1

    case "$value" in
        *.*)
            [ -n "$suffix" ] || return 1
            suffix="${suffix%.}"
            suffix=$(printf '%s' "$suffix" | tr '[:upper:]' '[:lower:]')
            [ -n "$suffix" ] || return 1
            # Must end in ".<suffix>"; the strip has to actually change it.
            [ "$value" != "${value%".$suffix"}" ] || return 1
            value="${value%".$suffix"}"
            ;;
    esac

    # Exactly one label must remain, and it must be a legal DNS/Linux label.
    case "$value" in
        ""|*.*) return 1 ;;
    esac
    [ "${#value}" -le 63 ] || return 1
    [[ "$value" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$ ]] || return 1

    printf '%s\n' "$value"
}

# Normalize a machine name for WHOLE-NAME comparison: ASCII-lowercased, with at
# most one trailing root dot removed. Nothing else is touched — no suffix is
# added, none is stripped — so a bare label and the fully-qualified name that
# happens to start with it stay different strings. Returns 1 for an empty
# value, which the callers treat as "not comparable" rather than "equal".
#
# This is deliberately NOT _tailscale_name_label(): that helper answers "is this
# our label, under our suffix", which a bare `.name` from the API also satisfies
# — and a bare name proves nothing about which tailnet the record lives in.
_tailscale_fqdn_normalize() {
    local value="${1%.}"
    [ -n "$value" ] || return 1
    printf '%s' "$value" | tr 'A-Z' 'a-z'
}

# Print a JSON array of the (string) arguments. Empty argv -> [].
_tailscale_json_string_array() {
    if [ "$#" -eq 0 ]; then
        printf '[]'
        return 0
    fi
    printf '%s\n' "$@" | jq -Rsc 'split("\n") | map(select(length > 0))'
}

# Load and strictly validate the identity receipt into
# _TS_ID_* / _TS_NODE_IDS / _TS_CONSUMED_IDS / _TS_PENDING_OLD. Returns 1 on any
# structural problem; the caller must then leave the file alone and skip the
# whole repair rather than rebuild a receipt it cannot trust.
#
# consumed_node_ids may be absent (every receipt written before this field
# exists, including the ones already on beta devices) and then loads as empty.
# When present it is held to the same standard as the rest: unique non-empty
# strings, all of them already part of node_ids, and never the node a pending
# repair is being performed FOR. A consumed id that is not in the history it
# claims to come from, or that names the current node, is a receipt this device
# cannot reason about, so the whole file is rejected rather than partly used.
#
# A pending_repair is an *authorization to DELETE*, so it is validated far more
# strictly than a cache would be. It must name at least one stale id, must not
# repeat one, must not name the node it is repairing, and every id must already
# be part of this device's own recorded history. An empty or forged pending
# block therefore cannot smuggle a delete past the eligibility rules, and it is
# never silently repaired: the whole receipt is rejected and nothing is mutated.
_tailscale_identity_load() {
    local file="$1"

    _TS_ID_MACHINE_ID=""
    _TS_ID_CANONICAL=""
    _TS_ID_PENDING_CURRENT=""
    _TS_ID_PENDING_CANONICAL=""
    _TS_ID_PENDING_OBSERVED=""
    _TS_NODE_IDS=()
    _TS_CONSUMED_IDS=()
    _TS_PENDING_OLD=()

    # One complete object, extracted once, and every value below comes from
    # that same object. Re-reading the raw file per field would let a second
    # concatenated document supply the pending old ids that authorize a DELETE
    # while the first one passed validation.
    local doc
    doc=$(_tailscale_json_single_object "$file") || return 1

    printf '%s' "$doc" | jq -e '
        type == "object"
        and .version == 1
        and (.machine_id | type == "string" and length > 0)
        and (.canonical_name | type == "string" and length > 0)
        and (.node_ids | type == "array")
        and all(.node_ids[]; type == "string" and length > 0)
        and ((.node_ids | unique | length) == (.node_ids | length))
        and (
            (has("consumed_node_ids") | not)
            or (
                (.consumed_node_ids | type == "array")
                and all(.consumed_node_ids[]; type == "string" and length > 0)
                and ((.consumed_node_ids | unique | length) == (.consumed_node_ids | length))
                and ((.node_ids) as $known
                     | all(.consumed_node_ids[]; . as $c | ($known | index($c)) != null))
                and (
                    .pending_repair == null
                    or ((.pending_repair.current_node_id) as $cur
                        | all(.consumed_node_ids[]; . != $cur))
                )
            )
        )
        and (
            .pending_repair == null
            or (
                (.pending_repair | type == "object")
                and (.pending_repair.current_node_id | type == "string" and length > 0)
                and (.pending_repair.canonical_name | type == "string" and length > 0)
                and (.pending_repair.observed_name | type == "string" and length > 0)
                and (.pending_repair.observed_name != .pending_repair.canonical_name)
                and (.pending_repair.old_node_ids | type == "array")
                and all(.pending_repair.old_node_ids[]; type == "string" and length > 0)
                and ((.pending_repair.old_node_ids | length) > 0)
                and ((.pending_repair.old_node_ids | unique | length)
                     == (.pending_repair.old_node_ids | length))
                and ((.pending_repair.current_node_id) as $cur
                     | all(.pending_repair.old_node_ids[]; . != $cur))
                and ((.node_ids) as $known
                     | all(.pending_repair.old_node_ids[]; . as $o | ($known | index($o)) != null))
            )
        )
    ' >/dev/null 2>&1 || return 1

    local scalars
    scalars=$(printf '%s' "$doc" | jq -r '[.machine_id, .canonical_name,
                      (.pending_repair.current_node_id // ""),
                      (.pending_repair.canonical_name // ""),
                      (.pending_repair.observed_name // "")] | @tsv' 2>/dev/null) || return 1
    IFS=$'\t' read -r _TS_ID_MACHINE_ID _TS_ID_CANONICAL \
        _TS_ID_PENDING_CURRENT _TS_ID_PENDING_CANONICAL _TS_ID_PENDING_OBSERVED <<< "$scalars"
    [ -n "$_TS_ID_MACHINE_ID" ] && [ -n "$_TS_ID_CANONICAL" ] || return 1

    # observed_name is the name the authorization was earned against, and every
    # later tick re-derives its decision by comparing the name in force with it.
    # A value that is not a legal label in its own canonical form could never be
    # produced by that comparison, so the receipt is rejected rather than
    # carried forward as an authorization nothing can invalidate.
    if [ -n "$_TS_ID_PENDING_CURRENT" ]; then
        local observed_label
        observed_label=$(_tailscale_name_label "$_TS_ID_PENDING_OBSERVED" "") || return 1
        [ "$observed_label" = "$_TS_ID_PENDING_OBSERVED" ] || return 1
    fi

    # Read loops, not mapfile: mapfile is a bash 4 builtin and the fixtures run
    # on macOS bash 3.2 (see mise.toml).
    local entry
    while IFS= read -r entry; do
        [ -n "$entry" ] && _TS_NODE_IDS[${#_TS_NODE_IDS[@]}]="$entry"
    done < <(printf '%s' "$doc" | jq -r '.node_ids[]' 2>/dev/null)
    while IFS= read -r entry; do
        [ -n "$entry" ] && _TS_CONSUMED_IDS[${#_TS_CONSUMED_IDS[@]}]="$entry"
    done < <(printf '%s' "$doc" | jq -r '(.consumed_node_ids // [])[]' 2>/dev/null)
    while IFS= read -r entry; do
        [ -n "$entry" ] && _TS_PENDING_OLD[${#_TS_PENDING_OLD[@]}]="$entry"
    done < <(printf '%s' "$doc" | jq -r '(.pending_repair.old_node_ids // [])[]' 2>/dev/null)
    return 0
}

# Render the receipt from _TS_NODE_IDS/_TS_CONSUMED_IDS/_TS_PENDING_OLD plus the
# given scalars and persist it 0600 via same-directory temp + rename. Writes
# only when the content actually changes: a healthy device must not burn an eMMC
# write every 5 minutes. The first changed write on a device whose receipt
# predates consumed_node_ids adds the field; nothing else about the document
# moves, and the version stays 1.
#
# The consumed list is re-validated here, not just on read: it is assembled in
# memory during a repair, and a list that is not a subset of the recorded
# history (or that names the node being repaired) would be re-read next tick as
# a receipt this device must reject outright — losing the pending repair with
# it. Fail closed instead, so the previous good receipt survives.
_tailscale_identity_save() {
    local machine_id="$1" canonical="$2" pending_current="$3" pending_canonical="$4"
    local pending_observed="$5"
    local file="$HOME/.evo-tailscale-identity.json"
    local ids_json consumed_json old_json pending_json rendered current="" tmp
    local id other known seen=""

    ids_json=$(_tailscale_json_string_array "${_TS_NODE_IDS[@]}") || return 1
    for id in "${_TS_CONSUMED_IDS[@]}"; do
        if [ -z "$id" ] || [ "$id" = "$pending_current" ]; then
            log_error "[TS-NAME] Refusing to persist an unusable consumed node id"
            return 1
        fi
        case "|${seen}|" in
            *"|${id}|"*)
                log_error "[TS-NAME] Refusing to persist a duplicated consumed node id"
                return 1
                ;;
        esac
        seen="${seen}|${id}"
        known=false
        for other in "${_TS_NODE_IDS[@]}"; do
            [ "$other" = "$id" ] && { known=true; break; }
        done
        if [ "$known" != true ]; then
            log_error "[TS-NAME] Refusing to persist a consumed node id that is not part of this device's history"
            return 1
        fi
    done
    consumed_json=$(_tailscale_json_string_array "${_TS_CONSUMED_IDS[@]}") || return 1
    if [ -n "$pending_current" ]; then
        # A pending repair without the name it was earned against cannot be
        # re-validated next tick, so it is never written in the first place.
        if [ -z "$pending_observed" ]; then
            log_error "[TS-NAME] Refusing to persist a pending repair with no observed name"
            return 1
        fi
        old_json=$(_tailscale_json_string_array "${_TS_PENDING_OLD[@]}") || return 1
        pending_json=$(jq -nc --arg c "$pending_current" --arg n "$pending_canonical" \
            --arg ob "$pending_observed" --argjson o "$old_json" \
            '{current_node_id: $c, canonical_name: $n, observed_name: $ob, old_node_ids: $o}' 2>/dev/null) || return 1
    else
        pending_json="null"
    fi

    rendered=$(jq -nc --arg mid "$machine_id" --arg canon "$canonical" \
        --argjson ids "$ids_json" --argjson consumed "$consumed_json" \
        --argjson pending "$pending_json" \
        '{version: 1, machine_id: $mid, canonical_name: $canon,
          node_ids: $ids, consumed_node_ids: $consumed,
          pending_repair: $pending}' 2>/dev/null) || return 1
    [ -n "$rendered" ] || return 1

    [ -f "$file" ] && current=$(cat "$file" 2>/dev/null)
    if [ "$current" = "$rendered" ]; then
        return 0
    fi

    tmp=$(mktemp "${file}.XXXXXX" 2>/dev/null) || {
        log_error "[TS-NAME] Cannot create identity receipt temp file"
        return 1
    }
    if ! chmod 600 "$tmp" 2>/dev/null || ! printf '%s' "$rendered" > "$tmp" || ! mv -f "$tmp" "$file"; then
        rm -f "$tmp" 2>/dev/null
        log_error "[TS-NAME] Failed to persist identity receipt"
        return 1
    fi
    return 0
}

# True when this node id has already been spent on a completed repair.
_tailscale_id_is_consumed() {
    local want="$1" id
    for id in "${_TS_CONSUMED_IDS[@]}"; do
        [ "$id" = "$want" ] && return 0
    done
    return 1
}

# Record that a stale record named by the pending repair is confirmed gone, and
# persist that fact BEFORE the repair moves on.
#
# This is the commit point of a delete. Until it is on disk, the only durable
# trace of the retirement is the id sitting in node_ids — which is exactly what
# would let some later, unrelated collision "prove" itself with a record this
# device deleted and can no longer inspect. So a write that fails is fatal to
# the tick: the pending repair is deliberately left in place, nothing is
# renamed, and the next tick re-reads the record (a 404 it can confirm as often
# as it likes, since confirming absence mutates nothing) and tries the save
# again before continuing.
_tailscale_consume_pending_id() {
    local machine_id="$1" canonical="$2" old_id="$3"
    local pending_current="$4" pending_canonical="$5" pending_observed="$6"

    _tailscale_id_is_consumed "$old_id" && return 0
    local -a previous=()
    local id
    for id in "${_TS_CONSUMED_IDS[@]}"; do
        previous[${#previous[@]}]="$id"
    done
    _TS_CONSUMED_IDS[${#_TS_CONSUMED_IDS[@]}]="$old_id"
    if ! _tailscale_identity_save "$machine_id" "$canonical" \
        "$pending_current" "$pending_canonical" "$pending_observed"; then
        # Roll the in-memory list back, so nothing later in this tick behaves as
        # if the completion were durable.
        _TS_CONSUMED_IDS=()
        for id in "${previous[@]}"; do
            _TS_CONSUMED_IDS[${#_TS_CONSUMED_IDS[@]}]="$id"
        done
        log_error "[TS-NAME] Could not record ${old_id} as retired; keeping the pending repair and renaming nothing"
        return 1
    fi
    return 0
}

# True when the healthy shortcut must NOT be taken: an alert for one of the two
# events this function can clear is unsettled (so the recovery notification is
# owed a fresh read-only confirmation), or the alert state is unreadable.
#
# Unsettled is wider than "active". An event that this device has already
# observed healthy but whose RECOVERY IS STILL QUEUED — the send failed, or
# the watchdog headroom ran out before the flush — is a page the operator can
# still see. Taking the shortcut then means nothing re-reads the condition for
# as long as the delivery keeps failing, and the eventual message says
# "Recovered" on the strength of one observation that may be hours stale. So
# the node blocks the shortcut until it is gone from the ledger, which happens
# only after every announced destination has actually been told.
#
# It reads whichever ledger this run owns (_tailscale_alert_state_path), so a
# rehearsal is judged against its own open alerts: an alert raised under the
# override still forces the read-only confirmation that produces its recovery,
# and production's ledger is neither read nor relied on.
_tailscale_alerts_block_shortcut() {
    local file doc
    file=$(_tailscale_alert_state_path)
    [ -f "$file" ] || return 1
    # A ledger that is not one complete, schema-valid version-1 object is
    # unreadable, and "unreadable" blocks the shortcut: the open alerts it may
    # be hiding are exactly the ones that owe a read-only confirmation before
    # recovery.
    doc=$(_tailscale_alert_state_document "$file") || return 0
    printf '%s' "$doc" | jq -e '
        def unsettled:
            (.active == true)
            or (([ (.deliveries // {}) | .[] | select(.announced == true) ] | length) > 0);
        ((.events.NAME_REPAIR_SKIPPED // {}) | unsettled | not)
        and ((.events.TAILSCALE_AUTH_BLOCKED // {}) | unsettled | not)' \
        >/dev/null 2>&1 && return 1
    return 0
}

# True when the ledger this run owns records EVENT as currently open. Used only
# as evidence that a decision has ALREADY been reached and paged; an unreadable
# or absent ledger answers "no", so every gate built on it fails towards doing
# the work rather than towards silence.
_tailscale_alert_event_is_open() {
    local file doc
    file=$(_tailscale_alert_state_path)
    [ -f "$file" ] || return 1
    doc=$(_tailscale_alert_state_document "$file") || return 1
    printf '%s' "$doc" | jq -e --arg e "$1" \
        '(.events[$e].active // false) == true' >/dev/null 2>&1
}

# Relative API path for a node id, with the id percent-encoded by jq. The path
# is always built here, never from an API response.
_tailscale_device_path() {
    local encoded
    encoded=$(jq -rn --arg v "$1" '$v|@uri' 2>/dev/null) || return 1
    [ -n "$encoded" ] || return 1
    printf 'device/%s' "$encoded"
}

# _tailscale_name_api METHOD PATH BODY OUTFILE CONTEXT
#   Thin wrapper over the shared _tailscale_api_request contract. Returns 0 when
#   the HTTP transport completed (the status then lands in _TS_API_CODE for the
#   caller to branch on) and 1 when it did not — a timeout is NOT proof that the
#   request did not execute, so callers treat it as "unknown, re-read next tick".
#   Authorization failures are the one class a device cannot fix itself, so they
#   raise TAILSCALE_AUTH_BLOCKED here, scoped to the DEVICE RECORD the call was
#   about rather than to the literal method: a 401 on DELETE device/<id> and a
#   401 on GET device/<id> are the same refusal by the same credential against
#   the same object, and POST device/<id>/name is that object too. All three
#   are therefore recorded under "api:GET device/<id>", the one call that can
#   later prove the refusal is over WITHOUT repeating a mutation. Tag writes
#   keep their own POST source (see _retag_tailscale_via_api): a retag has no
#   read-only equivalent, so only a successful retag closes it.
#
#   Every call is also gated on watchdog headroom. A device with a long history
#   issues one GET per recorded id plus up to three calls per stale record, each
#   allowed 30s, so an unbounded run could walk into the 600s watchdog and be
#   killed between a DELETE and its rename. Running out of headroom is treated
#   exactly like a lost response: nothing is sent, the caller keeps the pending
#   repair, and the next tick resumes.
_tailscale_name_api() {
    local method="$1" path="$2" body="$3" outfile="$4" context="$5"
    local raw rc line source

    _TS_API_CODE=""
    if ! watchdog_headroom_available "$TAILSCALE_NAME_API_HEADROOM_SECONDS"; then
        log "[TS-NAME] ${context}: only ${WATCHDOG_HEADROOM_SECONDS:-unreadable}s of watchdog headroom left; deferring to the next tick"
        return 1
    fi

    : > "$outfile" 2>/dev/null
    raw=$(_tailscale_api_request "$method" "$path" "$body" "$outfile")
    rc=$?
    # Tolerate a helper that also logs on stdout: the status is the last line
    # that is exactly three digits.
    while IFS= read -r line; do
        [[ "$line" =~ ^[0-9]{3}$ ]] && _TS_API_CODE="$line"
    done <<< "$raw"

    if [ "$rc" -ne 0 ]; then
        log_error "[TS-NAME] ${context}: API transport failed (HTTP ${_TS_API_CODE:-none}); will re-read next tick"
        return 1
    fi
    # The query string is not part of the identity of the endpoint: a GET with
    # and without ?fields=all is the same authorization question. Nor is the
    # method, for the calls this helper makes: they all act on one device
    # record, so they share that record's read-only source and a later GET can
    # settle them.
    local base_path="${path%%\?*}" auth_path=""
    if [[ "$base_path" =~ ^device/[A-Za-z0-9._~%-]+$ ]] \
        && { [ "$method" = "GET" ] || [ "$method" = "DELETE" ]; }; then
        auth_path="$base_path"
    elif [ "$method" = "POST" ] && [[ "$base_path" =~ ^device/[A-Za-z0-9._~%-]+/name$ ]]; then
        auth_path="${base_path%/name}"
    fi
    if [ -n "$auth_path" ]; then
        source="api:GET ${auth_path}"
    else
        # An endpoint shape this helper does not model: keep it literal rather
        # than claim some read-only path can answer for it.
        source="api:${method} ${base_path}"
    fi
    case "$_TS_API_CODE" in
        200)
            observe_tailscale_alert "TAILSCALE_AUTH_BLOCKED" "healthy" "api=${context} http=200" "$source"
            ;;
        404)
            # Only a GET may settle authorization with a 404. The control plane
            # answered the question ("no such device"), which it cannot do for
            # a credential it refused — and for a record this device has just
            # deleted, that answer is the only evidence that will ever exist.
            # A 404 from a DELETE is left alone: it is a mutation's own result,
            # and mutations are never replayed to gather evidence.
            if [ "$method" = "GET" ]; then
                observe_tailscale_alert "TAILSCALE_AUTH_BLOCKED" "healthy" "api=${context} http=404" "$source"
            fi
            ;;
        401|403)
            observe_tailscale_alert "TAILSCALE_AUTH_BLOCKED" "failed" "api=${context} http=${_TS_API_CODE}" "$source"
            log_error "[TS-NAME] ${context}: HTTP ${_TS_API_CODE} — OAuth client lacks devices:core or the device is unauthorized"
            ;;
    esac

    # Every GET body is read field by field to decide whether a record may be
    # deleted, whether the rename landed, and what goes into the receipt, so it
    # has to be one complete object BEFORE any of that starts. Left as a raw
    # stream, two concatenated records would let the name come from one
    # document and `authorized`/`addresses` from the other. A 404 body is never
    # read, so it is left alone.
    if [ "$method" = "GET" ] && [ "$_TS_API_CODE" = "200" ]; then
        local single
        if ! single=$(_tailscale_json_single_object "$outfile") \
            || ! printf '%s\n' "$single" > "$outfile"; then
            log_error "[TS-NAME] ${context}: HTTP 200 body is not a single complete JSON object; treating it as unread"
            : > "$outfile" 2>/dev/null
            _TS_API_CODE=""
            return 1
        fi
    fi
    return 0
}

# Re-run the read-only lookups whose authorization failure is still open, so a
# device that is otherwise healthy can actually close TAILSCALE_AUTH_BLOCKED.
#
# Recovery is scoped to the path that produced the failure: a 401 on a
# historical node's GET stays open until THAT GET answers 200, however healthy
# the rest of this tick looked. Without this, a device whose name an operator
# fixed by hand would never issue that lookup again (the history search only
# runs while the name is wrong), and the page would stay open forever.
#
# Only GET device/<id> sources are replayed. A POST or DELETE source is a
# mutation and is never repeated to gather evidence, and the id is re-checked
# against the shape _tailscale_device_path() produces before it is used, so a
# ledger that has been edited cannot steer a request at another endpoint.
# $2 is the current node's path, already looked up by the caller this tick.
_tailscale_recheck_blocked_auth_paths() {
    local body_file="$1" skip_path="$2" path

    while IFS= read -r path; do
        [ -n "$path" ] || continue
        [[ "$path" =~ ^device/[A-Za-z0-9._~%-]+$ ]] || {
            log_debug "[TS-NAME] Ignoring unusable blocked-auth source path"
            continue
        }
        [ "$path" = "$skip_path" ] && continue
        _tailscale_name_api GET "${path}?fields=all" "" "$body_file" "recheck authorization ${path}"
    done <<< "$(_tailscale_alert_blocked_get_paths)"
    return 0
}

# The current node must still be the node this device believes it is before any
# local record is extended or any remote mutation is considered. isExternal must
# be present and false: a record shared in from another tailnet is not ours to
# reason about, and an absent, null or non-boolean isExternal is unknown, not
# "false". multipleConnections is different: the live Tailscale API omits the
# key from device records entirely (every tag:evobox record as of 2026-10-22,
# with fields=all), so requiring it would fail every tick on every device that
# has no receipt yet. Identity here rests on the node id, authorization and the
# address intersection; multipleConnections is only consulted when the key is
# present, and then only a boolean false passes: true means the control plane
# sees more than one machine on this node, and a null, object or string value
# is unreadable, so both still fail closed.
# The address comparison is only evidence when BOTH sides of it are real address
# lists. A record whose addresses field is missing, null, an object, a scalar or
# a list holding anything but non-empty strings is an unreadable record, not a
# record that happens not to match, and the same is true of the local list this
# device passes in: an empty or malformed one would make the intersection
# vacuous. Both are checked explicitly so an unusable answer fails closed,
# before any receipt is extended and before any DELETE or rename is authorized.
_tailscale_current_device_ok() {
    local file="$1" node_id="$2" ips_json="$3"

    printf '%s' "$ips_json" | jq -e '
        type == "array" and length > 0
        and all(.[]; type == "string" and length > 0)
    ' >/dev/null 2>&1 || return 1

    jq -e --arg id "$node_id" --argjson want "$ips_json" '
        (.nodeId // "") == $id
        and (.authorized == true)
        and (.isExternal == false)
        and ((has("multipleConnections") | not) or .multipleConnections == false)
        and ((.addresses | type) == "array")
        and ((.addresses | length) > 0)
        and all(.addresses[]; type == "string" and length > 0)
        and any(.addresses[]; . as $a | ($want | index($a)) != null)
    ' "$file" >/dev/null 2>&1
}

# A historical record may only be deleted when the control plane says it is
# disconnected, not shared in from another tailnet, not multiply connected, and
# still carries either the canonical name or a canonical-<n> collision suffix.
# Every field is required explicitly: a missing connectedToControl, isExternal
# or multipleConnections is "unknown", and unknown never authorizes a DELETE.
# The live API omits multipleConnections (see _tailscale_current_device_ok), so
# no DELETE is authorized today: a name collision is left to a human through
# NAME_REPAIR_SKIPPED until a verifiable replacement signal exists.
_tailscale_old_device_eligible() {
    local file="$1" node_id="$2" canonical="$3" dns_suffix="$4"
    local name label numeric

    jq -e --arg id "$node_id" '
        (.nodeId // "") == $id
        and (.isExternal == false)
        and (.connectedToControl == false)
        and (.multipleConnections == false)
    ' "$file" >/dev/null 2>&1 || return 1

    name=$(jq -r '.name // empty' "$file" 2>/dev/null)
    label=$(_tailscale_name_label "$name" "$dns_suffix") || return 1
    [ "$label" = "$canonical" ] && return 0

    numeric="${label#"${canonical}-"}"
    [ "$numeric" != "$label" ] || return 1
    [[ "$numeric" =~ ^[1-9][0-9]*$ ]] || return 1
    return 0
}

# Confirm, from a freshly read status, that this is still the same Running node
# the pending repair was earned for. Prints the current Self.DNSName label on
# success so a caller that is about to rename can also compare it with what the
# control plane reports. Returns 1 whenever that cannot be established.
_tailscale_self_still_current() {
    local expect_id="$1" dns_suffix="$2"
    local status_json status_rc self_id self_dns label

    status_json=$(tailscale status --json 2>/dev/null)
    status_rc=$?
    [ "$status_rc" -eq 0 ] && [ -n "$status_json" ] || return 1
    self_id=$(_tailscale_status_self_id "$status_json")
    [ -n "$self_id" ] && [ "$self_id" = "$expect_id" ] || return 1
    self_dns=$(printf '%s' "$status_json" | jq -r '
        if (.Self.DNSName | type) == "string" then .Self.DNSName else "" end' 2>/dev/null)
    label=$(_tailscale_name_label "$self_dns" "$dns_suffix") || return 1
    [ -n "$label" ] || return 1
    printf '%s\n' "$label"
    return 0
}

# Every id the pending repair authorizes must still be a distinct, recorded,
# non-current node, and the repair must still name the non-canonical name it
# was earned against. The receipt loader enforces both on read; the mutation
# path re-checks them because the in-memory values are also built at runtime,
# and they are what the gates before each DELETE and the rename compare with.
_tailscale_pending_invariants_ok() {
    local self_id="$1" observed="$2" canonical="$3" id other seen known

    [ -n "$observed" ] || return 1
    [ "$observed" != "$canonical" ] || return 1
    [ "${#_TS_PENDING_OLD[@]}" -gt 0 ] || return 1
    seen=""
    for id in "${_TS_PENDING_OLD[@]}"; do
        [ -n "$id" ] || return 1
        [ "$id" = "$self_id" ] && return 1
        case "|${seen}|" in
            *"|${id}|"*) return 1 ;;
        esac
        seen="${seen}|${id}"
        known=false
        for other in "${_TS_NODE_IDS[@]}"; do
            [ "$other" = "$id" ] && { known=true; break; }
        done
        [ "$known" = true ] || return 1
    done
    return 0
}

# Give up a pending repair because the machine name in force changed under it.
#
# Clearing the authorization is not enough: the ids it named are still in this
# device's trusted history, so the very next tick would look them up again,
# find the same abandoned records, re-earn the same eligibility and rename the
# device back -- overriding the operator whose rename caused this in the first
# place. They are therefore dropped from the recorded history too. Two ids are
# always kept: the current node (it is this device, and losing it would force an
# avoidable re-confirmation) and any id already recorded as consumed — that
# record IS the proof the repair is finished, it can never re-earn anything
# (the eligibility search skips consumed ids), and consumed_node_ids is only
# valid as a subset of node_ids.
#
# The receipt is rewritten atomically by _tailscale_identity_save(). If that
# write fails, the on-disk receipt is left exactly as it was and the caller
# still performs no mutation this tick, so the worst case is the old (already
# refused) authorization being re-read next tick, never a delete.
_tailscale_revoke_pending_repair() {
    local machine_id="$1" canonical="$2" self_id="$3"
    local -a keep=()
    local id other stale

    for id in "${_TS_NODE_IDS[@]}"; do
        [ -n "$id" ] || continue
        if [ "$id" != "$self_id" ] && ! _tailscale_id_is_consumed "$id"; then
            stale=false
            for other in "${_TS_PENDING_OLD[@]}"; do
                [ "$other" = "$id" ] && { stale=true; break; }
            done
            [ "$stale" = true ] && continue
        fi
        keep[${#keep[@]}]="$id"
    done

    _TS_NODE_IDS=()
    for id in "${keep[@]}"; do
        _TS_NODE_IDS[${#_TS_NODE_IDS[@]}]="$id"
    done
    _TS_PENDING_OLD=()

    if ! _tailscale_identity_save "$machine_id" "$canonical" "" "" ""; then
        log_error "[TS-NAME] Could not revoke the pending repair; leaving the stored receipt untouched"
        return 1
    fi
    log "[TS-NAME] Revoked the pending repair and dropped the nodes it named from local history"
    return 0
}

# Authoritative re-read of the current device, immediately before a call that
# mutates the tailnet.
#
# `tailscale status` is this device's own view, and MagicDNS propagation makes
# it a LAGGING one: an operator who renames this node in the Admin Console
# mid-repair leaves Self.DNSName reporting the old name for as long as the
# local copy is stale. Deciding a DELETE from that read alone deletes the
# record that stands in the way of a name the operator has already taken over.
# The control plane is the only authority on the name in force, so it is asked
# again here -- with the same single-object, node/auth/address gate the entry
# read uses -- and the answer is compared as a WHOLE name (the observed name
# the authorization was earned against, under this tick's trusted DNS suffix),
# never as a bare label that any tailnet could produce.
#
# Returns 0 when the name the pending repair was earned against is still in
# force, 1 when the control plane could not be read (keep the pending repair
# and defer), and 2 when the name has moved (the caller revokes).
_tailscale_current_name_matches_pending() {
    local body_file="$1" path="$2" self_id="$3" ips_json="$4"
    local dns_suffix="$5" pending_observed="$6" context="$7"
    local api_name api_fqdn want_fqdn

    [ -n "$pending_observed" ] || return 1
    _tailscale_name_api GET "${path}?fields=all" "" "$body_file" "$context" || return 1
    if [ "$_TS_API_CODE" != "200" ]; then
        log_error "[TS-NAME] ${context} returned HTTP ${_TS_API_CODE:-none}; keeping pending repair"
        return 1
    fi
    if ! _tailscale_current_device_ok "$body_file" "$self_id" "$ips_json"; then
        log_error "[TS-NAME] Current device record stopped matching this host; keeping pending repair"
        return 1
    fi
    api_name=$(jq -r '.name // empty' "$body_file" 2>/dev/null)
    api_fqdn=$(_tailscale_fqdn_normalize "$api_name")
    want_fqdn=$(_tailscale_fqdn_normalize "${pending_observed}.${dns_suffix}")
    if [ -z "$api_fqdn" ] || [ -z "$want_fqdn" ] || [ "$api_fqdn" != "$want_fqdn" ]; then
        log_error "[TS-NAME] Control-plane name '${api_name:-none}' is no longer '${pending_observed}.${dns_suffix}'; this repair's premise is gone"
        return 2
    fi
    return 0
}

# Remote half of reconcile_tailscale_name(). Split out purely so the single
# response temp file has one owner and one cleanup point.
# Arrays are passed through the _TS_* globals the local half already populated.
_tailscale_reconcile_remote() {
    local body_file="$1" machine_id="$2" canonical="$3" self_id="$4"
    local dns_suffix="$5" self_label="$6" pending_current="$7" pending_canonical="$8"
    local pending_observed="$9" ips_json="${10}" self_dnsname="${11}"
    local path api_name api_label api_fqdn self_fqdn details

    details="current=${self_label} canonical=${canonical} node=${self_id}"

    path=$(_tailscale_device_path "$self_id") || {
        log_error "[TS-NAME] Could not encode node id; skipping"
        return 1
    }
    _tailscale_name_api GET "${path}?fields=all" "" "$body_file" "get current" || return 1
    if [ "$_TS_API_CODE" != "200" ]; then
        log_error "[TS-NAME] Current device lookup returned HTTP ${_TS_API_CODE:-none}; deferring"
        return 1
    fi
    if ! _tailscale_current_device_ok "$body_file" "$self_id" "$ips_json"; then
        log_error "[TS-NAME] Current device record does not match this host (node/auth/address); deferring"
        return 1
    fi

    # WHOLE-NAME agreement, before this node id is recorded as ours and before
    # any history is searched. Comparing labels (or a label plus a suffix this
    # code appended) accepts a record whose `.name` is a bare "evobox-oem-0015"
    # with no tailnet at all, or one that lives under a different suffix — and
    # that record is what the eligibility search then reasons from. The
    # control plane's name must be exactly this device's Self.DNSName, modulo
    # the trailing root dot and case; anything else fails closed.
    api_name=$(jq -r '.name // empty' "$body_file" 2>/dev/null)
    api_fqdn=$(_tailscale_fqdn_normalize "$api_name")
    self_fqdn=$(_tailscale_fqdn_normalize "$self_dnsname")
    if [ -z "$api_fqdn" ] || [ -z "$self_fqdn" ] || [ "$api_fqdn" != "$self_fqdn" ]; then
        log_error "[TS-NAME] API name '${api_name:-none}' is not this device's full DNSName '${self_dnsname:-none}'; deferring"
        return 1
    fi
    # From here on the name is known to be ours, so the semantic (label)
    # comparisons the repair decisions rest on are made with the usual helper.
    api_label=$(_tailscale_name_label "$api_name" "$dns_suffix")
    if [ -z "$api_label" ] || [ "$api_label" != "$self_label" ]; then
        log_error "[TS-NAME] API name '${api_name:-none}' is not a single label under ${dns_suffix}; deferring"
        return 1
    fi

    # The control plane confirmed this node id belongs to this device, so it is
    # now usable as history on a later tick.
    local known=false id
    for id in "${_TS_NODE_IDS[@]}"; do
        [ "$id" = "$self_id" ] && { known=true; break; }
    done
    [ "$known" = true ] || _TS_NODE_IDS+=("$self_id")

    # --- Already canonical: nothing to repair. ---------------------------------
    if [ "$api_label" = "$canonical" ]; then
        if [ -n "$pending_current" ] && [ "$pending_current" != "$self_id" ]; then
            # The name is right, but the receipt still carries an
            # authorization to delete records on behalf of a DIFFERENT
            # current node id. That is an unresolved inconsistency, not a
            # recovery: it must not be announced as healthy (which would
            # also retire an open alert) and it must not be reused. It is
            # left exactly as it is for review.
            log_error "[TS-NAME] Name is canonical but a stored repair is bound to another node id (${pending_current}); leaving it for manual review"
            return 1
        fi
        # Either there was no pending repair, or it was bound to this node and
        # the canonical name is now in force — which means it is COMPLETE,
        # whether by this device's own rename landing after a lost response or
        # by an operator fixing the name by hand. Either way the flag is
        # cleared and the recorded history is KEPT. A completion is not a
        # revocation: history is the only thing that can ever prove a stale
        # record was ours, and the ids that must never authorize a second
        # delete are tracked precisely by consumed_node_ids, written at each
        # delete's commit point and skipped by the eligibility search.
        # Dropping the rest would punish a device for having finished a
        # repair — a genuinely new collision involving an id this device
        # recorded but never deleted would have no evidence left.
        _TS_PENDING_OLD=()
        _tailscale_identity_save "$machine_id" "$canonical" "" "" "" || return 1
        # The name is healthy, which says nothing about an authorization
        # failure recorded on a DIFFERENT endpoint. Those are re-read here (and
        # only the read-only ones), so an operator who fixed both the name and
        # the OAuth scope gets one recovery for each, each backed by its own
        # 200 — and a still-failing lookup keeps its page open.
        _tailscale_recheck_blocked_auth_paths "$body_file" "$path"
        observe_tailscale_alert "NAME_REPAIR_SKIPPED" "healthy" "$details"
        # The conflict this device was waiting on a human for is over, so the
        # re-check stamp that bounded its polling is dropped: a NEW collision
        # later must be judged once in full before any TTL applies to it again.
        fresh_clear "$TAILSCALE_NAME_SKIP_OP"
        log_debug "[TS-NAME] Machine name is canonical (${canonical})"
        return 0
    fi

    # --- Name mismatch: eligibility first, mutation never before it. -----------
    if [ -n "$pending_current" ]; then
        if [ "$pending_current" != "$self_id" ] || [ "$pending_canonical" != "$canonical" ]; then
            # Not an operator-actionable naming conflict: a receipt this device
            # cannot bind to itself. It is logged and dropped from this tick's
            # work, and deliberately raises no alert of its own.
            log_error "[TS-NAME] Stored repair does not bind this node/name (${pending_current}/${pending_canonical}); refusing to reuse it"
            return 1
        fi
        # The authorization is bound to the exact name it was earned against.
        # A name that has moved since — to the canonical name, to an operator's
        # choice, or to another canonical-<n> collision suffix that merely
        # looks like the one this repair qualified on — means the premise is
        # gone, and the ids it named must not survive into the next tick
        # either. A revocation that cannot be persisted still mutates nothing;
        # the mismatch is re-read from the receipt next tick and retried.
        if [ "$pending_observed" != "$api_label" ]; then
            log_error "[TS-NAME] Stored repair was earned against '${pending_observed}' but the name in force is '${api_label}'; revoking it"
            _tailscale_revoke_pending_repair "$machine_id" "$canonical" "$self_id"
            return 1
        fi
        _tailscale_identity_save "$machine_id" "$canonical" "$pending_current" "$pending_canonical" "$pending_observed" || return 1
    else
        # Only ids this device recorded itself, and only records the control
        # plane still describes as an abandoned copy of us, earn a DELETE.
        #
        # A lookup that did not come back as a definite 200 or 404 leaves this
        # device's history partly unread, and an unread history is not the same
        # as an exhausted one: it can neither authorize a DELETE nor support the
        # claim that no stale node exists. So one unknown result defers the
        # whole decision to the next tick — no mutation, and deliberately no
        # NAME_REPAIR_SKIPPED, which would page a human about a conflict this
        # device has not finished establishing. (401/403 still raises
        # TAILSCALE_AUTH_BLOCKED from _tailscale_name_api: that one IS a human's
        # problem, and it is scoped to the path that produced it.)
        local -a eligible=()
        local old_path unknown_lookup=false
        for id in "${_TS_NODE_IDS[@]}"; do
            [ "$id" = "$self_id" ] && continue
            # An id this device already spent on a completed repair is history,
            # not evidence. Its record was deleted by this program, so whatever
            # answers for that id now — a 404, or a reused id the control plane
            # handed to someone else — says nothing about the collision in
            # front of us, and it must never again authorize a DELETE. Skipping
            # is definitive, so it deliberately does not count as an unread
            # history the way a failed lookup does.
            if _tailscale_id_is_consumed "$id"; then
                log_debug "[TS-NAME] Historical node ${id} was already retired by a completed repair; not reconsidered"
                continue
            fi
            if ! old_path=$(_tailscale_device_path "$id"); then
                log_error "[TS-NAME] Could not encode historical node id; deferring"
                unknown_lookup=true
                continue
            fi
            if ! _tailscale_name_api GET "${old_path}?fields=all" "" "$body_file" "get historical ${id}"; then
                log_error "[TS-NAME] Historical node ${id} lookup did not complete; deferring"
                unknown_lookup=true
                continue
            fi
            case "$_TS_API_CODE" in
                200)
                    if _tailscale_old_device_eligible "$body_file" "$id" "$canonical" "$dns_suffix"; then
                        eligible+=("$id")
                    else
                        log_debug "[TS-NAME] Historical node ${id} no longer qualifies as our stale record"
                    fi
                    ;;
                404)
                    # Gone already: proves nothing about this collision, and it
                    # is NOT a completed repair either — this device never
                    # deleted it and never earned the right to. It stays in the
                    # history, unconsumed, so a later tick that finds it back
                    # (a record restored, an id reused) still has to qualify it
                    # from scratch.
                    log_debug "[TS-NAME] Historical node ${id} no longer exists"
                    ;;
                *)
                    log_error "[TS-NAME] Historical node ${id} lookup returned HTTP ${_TS_API_CODE:-none}; deferring"
                    unknown_lookup=true
                    ;;
            esac
        done

        if [ "$unknown_lookup" = true ]; then
            # Record nothing and claim nothing: the same read is retried in five
            # minutes with the receipt exactly as it was found.
            log_error "[TS-NAME] Could not read this device's full node history; performing no remote change this tick"
            return 1
        fi

        if [ "${#eligible[@]}" -eq 0 ]; then
            # Persist the confirmed current id (if it is new) but change nothing
            # remotely: this is the Admin Console case.
            _tailscale_identity_save "$machine_id" "$canonical" "" "" ""
            log_error "[TS-NAME] Name is '${api_label}' but no provable stale node exists; leaving it to the Admin Console"
            observe_tailscale_alert "NAME_REPAIR_SKIPPED" "failed" "$details"
            # A verdict only a human can change, reached against a fully read
            # history. Stamped so the next ticks re-derive it on the 12h cadence
            # instead of spending two API calls every five minutes; the gate in
            # reconcile_tailscale_name() reads this stamp.
            fresh_mark "$TAILSCALE_NAME_SKIP_OP"
            return 0
        fi

        # Persist eligibility BEFORE touching anything remote, so an interrupted
        # tick resumes instead of losing the proof it just earned.
        pending_current="$self_id"
        pending_canonical="$canonical"
        pending_observed="$api_label"
        _TS_PENDING_OLD=("${eligible[@]}")
        if ! _tailscale_identity_save "$machine_id" "$canonical" "$pending_current" "$pending_canonical" "$pending_observed"; then
            log_error "[TS-NAME] Could not record the pending repair; performing no remote change"
            return 1
        fi
    fi

    # The receipt loader already rejects an empty, duplicated, self-referential
    # or unrecorded old-id list; the same invariants are re-checked here because
    # this list can also have been assembled in memory during this tick, and it
    # is what authorizes the DELETEs below.
    if ! _tailscale_pending_invariants_ok "$pending_current" "$pending_observed" "$canonical"; then
        log_error "[TS-NAME] Pending repair does not name usable stale node ids or the name it was earned against; performing no remote change"
        return 1
    fi

    # --- Retire each stale record, confirming absence rather than trusting 200 --
    local old_id old_path fresh_label recheck_rc
    for old_id in "${_TS_PENDING_OLD[@]}"; do
        # Already retired and recorded as such on an earlier tick (or earlier in
        # this loop): the work is done and durable, so it is not re-read.
        _tailscale_id_is_consumed "$old_id" && continue
        old_path=$(_tailscale_device_path "$old_id") || return 1

        _tailscale_name_api GET "${old_path}?fields=all" "" "$body_file" "get stale ${old_id}" || return 1
        case "$_TS_API_CODE" in
            404)
                # Confirmed absent under an authorization this device earned:
                # that is a completed retirement, whether this tick deleted it
                # or a previous tick's DELETE landed with its response lost.
                # Recording it is the commit point, and it happens BEFORE the
                # rename that would clear the pending repair.
                _tailscale_consume_pending_id "$machine_id" "$canonical" "$old_id" \
                    "$pending_current" "$pending_canonical" "$pending_observed" || return 1
                continue
                ;;
            200) ;;
            *)
                log_error "[TS-NAME] Stale node ${old_id} lookup returned HTTP ${_TS_API_CODE:-none}; keeping pending repair"
                return 1
                ;;
        esac
        if ! _tailscale_old_device_eligible "$body_file" "$old_id" "$canonical" "$dns_suffix"; then
            log_error "[TS-NAME] Stale node ${old_id} came back online or was repurposed; stopping before any rename"
            return 1
        fi

        # Identity is re-established immediately before every destructive call.
        # Several API round trips can pass between the eligibility check and
        # here, and a node that re-registered in that window is a different
        # machine whose records this device may no longer delete.
        # The live NAME is re-checked against the one the AUTHORIZATION was
        # earned against -- the persisted observed_name, not merely the label
        # read at the top of this tick -- for the same reason: if an operator
        # renamed this device in the Admin Console mid-repair, to the canonical
        # name or to anything else, the premise the eligibility was earned
        # under is gone and the operator now owns the name. The authorization
        # is revoked rather than kept (see _tailscale_revoke_pending_repair),
        # and nothing is announced as recovered, because this tick repaired
        # nothing.
        fresh_label=$(_tailscale_self_still_current "$pending_current" "$dns_suffix")
        if [ -z "$fresh_label" ]; then
            log_error "[TS-NAME] Node is no longer the Running node ${pending_current} this repair was earned for; keeping pending repair"
            return 1
        fi
        if [ "$fresh_label" != "$pending_observed" ]; then
            log_error "[TS-NAME] Live machine name changed from '${pending_observed}' to '${fresh_label}' during the repair; stopping before deleting ${old_id}"
            _tailscale_revoke_pending_repair "$machine_id" "$canonical" "$self_id"
            return 1
        fi

        # The local status above is this device's own, possibly stale, copy.
        # The control plane is asked the same question authoritatively, and it
        # is the last read before the delete: a rename that has landed there
        # but not yet in MagicDNS still ends the repair, with the record the
        # operator now needs left alone.
        recheck_rc=0
        _tailscale_current_name_matches_pending "$body_file" "$path" "$self_id" \
            "$ips_json" "$dns_suffix" "$pending_observed" \
            "authoritative recheck before deleting ${old_id}" || recheck_rc=$?
        if [ "$recheck_rc" -eq 2 ]; then
            log_error "[TS-NAME] Control plane shows this device renamed during the repair; stopping before deleting ${old_id}"
            _tailscale_revoke_pending_repair "$machine_id" "$canonical" "$self_id"
            return 1
        fi
        if [ "$recheck_rc" -ne 0 ]; then
            return 1
        fi

        # Last read of all, and the only one the DELETE may rely on. The stale
        # record's eligibility was established before the identity and control
        # plane round trips above, and its response body has since been
        # overwritten by them; between the two reads the node may have
        # reconnected, been renamed, been shared in from another tailnet, or
        # already been removed by an operator. It is therefore re-read here and
        # re-judged by exactly the same rules, so nothing is destroyed on the
        # strength of an answer that is no longer current.
        _tailscale_name_api GET "${old_path}?fields=all" "" "$body_file" \
            "recheck stale ${old_id} before delete" || return 1
        case "$_TS_API_CODE" in
            404)
                # Gone in the window: the retirement is complete without this
                # device deleting anything, and recording it is still the
                # commit point.
                _tailscale_consume_pending_id "$machine_id" "$canonical" "$old_id" \
                    "$pending_current" "$pending_canonical" "$pending_observed" || return 1
                continue
                ;;
            200) ;;
            *)
                log_error "[TS-NAME] Stale node ${old_id} re-read returned HTTP ${_TS_API_CODE:-none}; keeping pending repair"
                return 1
                ;;
        esac
        if ! _tailscale_old_device_eligible "$body_file" "$old_id" "$canonical" "$dns_suffix"; then
            log_error "[TS-NAME] Stale node ${old_id} stopped qualifying in the moment before its delete; stopping before any rename"
            return 1
        fi

        _tailscale_name_api DELETE "$old_path" "" "$body_file" "delete stale ${old_id}" || return 1
        if [ "$_TS_API_CODE" != "200" ]; then
            log_error "[TS-NAME] Delete of ${old_id} returned HTTP ${_TS_API_CODE:-none}; keeping pending repair"
            return 1
        fi
        _tailscale_name_api GET "${old_path}?fields=all" "" "$body_file" "confirm delete ${old_id}" || return 1
        if [ "$_TS_API_CODE" != "404" ]; then
            log_error "[TS-NAME] Node ${old_id} still resolves after delete (HTTP ${_TS_API_CODE:-none}); keeping pending repair"
            return 1
        fi
        # The delete is only finished once the retirement is durable: an id
        # whose record is gone but whose completion was never written would be
        # looked at again by a future collision, with nothing left to inspect.
        _tailscale_consume_pending_id "$machine_id" "$canonical" "$old_id" \
            "$pending_current" "$pending_canonical" "$pending_observed" || return 1
        log "[TS-NAME] Removed stale node record ${old_id}"
    done

    # --- Rename, then verify against the control plane -------------------------
    # Last gate before the only call that overwrites a name someone else may
    # have just set, and the first read after the deletes. The control plane's
    # whole name must still be the one this authorization was earned against
    # (observed_name), and so must the live DNSName. Comparing the two with
    # each other alone cannot tell an operator's rename from control-plane
    # propagation that has not reached MagicDNS yet -- but a name that has
    # moved away from observed_name is an external change either way, and
    # nothing about this device's history authorizes undoing it. So any
    # deviation revokes the authorization and the ids it named instead of
    # carrying them into the next tick; nothing is announced as repaired or
    # recovered, and the next tick decides from the name actually in force.
    recheck_rc=0
    _tailscale_current_name_matches_pending "$body_file" "$path" "$self_id" \
        "$ips_json" "$dns_suffix" "$pending_observed" "re-read current" || recheck_rc=$?
    if [ "$recheck_rc" -eq 2 ]; then
        log_error "[TS-NAME] Control-plane name moved away from '${pending_observed}' after the deletes; abandoning the rename"
        _tailscale_revoke_pending_repair "$machine_id" "$canonical" "$self_id"
        return 1
    fi
    if [ "$recheck_rc" -ne 0 ]; then
        return 1
    fi

    fresh_label=$(_tailscale_self_still_current "$pending_current" "$dns_suffix")
    if [ -z "$fresh_label" ]; then
        log_error "[TS-NAME] Node is no longer the Running node ${pending_current} this repair was earned for; keeping pending repair"
        return 1
    fi
    if [ "$fresh_label" != "$pending_observed" ]; then
        log_error "[TS-NAME] Machine name moved from '${pending_observed}' to '${fresh_label}' during the repair; abandoning the rename"
        _tailscale_revoke_pending_repair "$machine_id" "$canonical" "$self_id"
        return 1
    fi

    # The entry gate already returns early when the name is canonical, and the
    # gate above proves the name has not moved since, so renaming is exactly
    # what is left to do -- there is no "already canonical" case to fall into.
    local rename_body
    rename_body=$(jq -nc --arg n "$canonical" '{name: $n}' 2>/dev/null)
    if [ -z "$rename_body" ]; then
        log_error "[TS-NAME] Could not build the rename body; keeping pending repair"
        return 1
    fi
    _tailscale_name_api POST "${path}/name" "$rename_body" "$body_file" "rename current" || return 1
    if [ "$_TS_API_CODE" != "200" ]; then
        log_error "[TS-NAME] Rename returned HTTP ${_TS_API_CODE:-none}; keeping pending repair"
        return 1
    fi

    _tailscale_name_api GET "${path}?fields=all" "" "$body_file" "verify rename" || return 1
    if [ "$_TS_API_CODE" != "200" ] || ! _tailscale_current_device_ok "$body_file" "$self_id" "$ips_json"; then
        log_error "[TS-NAME] Could not verify the rename; keeping pending repair"
        return 1
    fi
    api_name=$(jq -r '.name // empty' "$body_file" 2>/dev/null)
    api_label=$(_tailscale_name_label "$api_name" "$dns_suffix")
    if [ "$api_label" != "$canonical" ]; then
        log_error "[TS-NAME] Rename reported success but the name is still '${api_label:-unknown}'; keeping pending repair"
        return 1
    fi
    log "[TS-NAME] Machine name restored to ${canonical}"

    _TS_PENDING_OLD=()
    _tailscale_identity_save "$machine_id" "$canonical" "" "" "" || return 1
    observe_tailscale_alert "NAME_REPAIR_SKIPPED" "healthy" "current=${canonical} canonical=${canonical} node=${self_id}"
    return 0
}

reconcile_tailscale_name() {
    local identity_file="$HOME/.evo-tailscale-identity.json"
    local dep
    for dep in tailscale jq curl mktemp; do
        if ! check_command "$dep"; then
            log_debug "[TS-NAME] ${dep} unavailable; skipping name reconciliation"
            return 0
        fi
    done

    # --- Local identity --------------------------------------------------------
    # The machine id only has to be stable enough to notice a reimaged or cloned
    # box; it is not a hardware root of trust and is not treated as one. The path
    # is overridable for tests, same convention as $EVO_UPTIME_PATH.
    #
    # The value read is VALIDATED, never normalized. Stripping the characters
    # that do not belong turned "abc!" into "abc" and "8f1c…5f garbage" into a
    # 39-character string, so two different files could agree with one receipt —
    # and that agreement is what lets the receipt's recorded node ids authorize
    # a DELETE. Only the canonical systemd form qualifies: exactly 32 lowercase
    # hex digits, with nothing but the file's trailing newline around it.
    local machine_id_path="${EVO_MACHINE_ID_PATH:-/etc/machine-id}"
    local machine_id=""
    [ -r "$machine_id_path" ] && machine_id=$(cat "$machine_id_path" 2>/dev/null)
    if ! [[ "$machine_id" =~ ^[0-9a-f]{32}$ ]]; then
        log_error "[TS-NAME] ${machine_id_path} is missing or not a canonical machine-id; skipping name reconciliation"
        return 1
    fi

    local canonical hostname_raw
    hostname_raw=$(hostname -s 2>/dev/null)
    canonical=$(_tailscale_name_label "$hostname_raw" "")
    if [ -z "$canonical" ]; then
        log_error "[TS-NAME] Host name '${hostname_raw:-none}' is not a usable canonical label; skipping"
        return 1
    fi

    # --- Tailscale state (command result and JSON validity checked apart) ------
    local status_json status_rc backend backend_rc self_id self_dnsname
    status_json=$(tailscale status --json 2>/dev/null)
    status_rc=$?
    if [ "$status_rc" -ne 0 ] || [ -z "$status_json" ]; then
        log_debug "[TS-NAME] tailscale status unavailable (rc=${status_rc}); skipping this tick"
        return 1
    fi
    # One complete object or nothing. A lenient parse accepts a valid document
    # followed by trailing bytes or a second document and answers from the
    # first one, and every Self field read below feeds calls that can delete a
    # device record.
    backend=$(_tailscale_backend_state "$status_json")
    backend_rc=$?
    if [ "$backend_rc" -ne 0 ] || [ -z "$backend" ]; then
        log_error "[TS-NAME] tailscale status is not a single object with a usable BackendState; skipping this tick"
        return 1
    fi
    if [ "$backend" != "Running" ]; then
        log_debug "[TS-NAME] Backend state is ${backend:-unknown}; name reconciliation needs a Running node"
        return 0
    fi
    # Strings only: a node id or address of any other JSON type is not evidence
    # about this device, and both feed calls that can delete a device record.
    self_id=$(_tailscale_status_self_id "$status_json")
    self_dnsname=$(printf '%s' "$status_json" | jq -r '
        if (.Self.DNSName | type) == "string" then .Self.DNSName else "" end' 2>/dev/null)
    _TS_SELF_IPS=()
    local ip_entry
    while IFS= read -r ip_entry; do
        [ -n "$ip_entry" ] && _TS_SELF_IPS[${#_TS_SELF_IPS[@]}]="$ip_entry"
    done < <(printf '%s' "$status_json" | jq -r '
        (.Self.TailscaleIPs // []) | if type == "array" then .[] else empty end
        | select(type == "string")' 2>/dev/null)
    if [ -z "$self_id" ] || [ "${#_TS_SELF_IPS[@]}" -eq 0 ]; then
        log_error "[TS-NAME] Running node without a usable Self.ID/IP; skipping this tick"
        return 1
    fi

    # The tailnet suffix is only ever read off our own DNSName. Guessing it would
    # make every name comparison — including the ones that authorize a DELETE —
    # unsound.
    local dnsname_trimmed dns_suffix="" self_label
    dnsname_trimmed="${self_dnsname%.}"
    case "$dnsname_trimmed" in
        *.*) dns_suffix="${dnsname_trimmed#*.}" ;;
    esac
    if [ -z "$dns_suffix" ]; then
        log_error "[TS-NAME] Self.DNSName '${self_dnsname:-none}' carries no tailnet suffix; deferring"
        return 1
    fi
    self_label=$(_tailscale_name_label "$dnsname_trimmed" "$dns_suffix")
    if [ -z "$self_label" ]; then
        log_error "[TS-NAME] Self.DNSName '${self_dnsname}' is not a single label under ${dns_suffix}; deferring"
        return 1
    fi

    # --- Receipt ---------------------------------------------------------------
    _TS_NODE_IDS=()
    _TS_CONSUMED_IDS=()
    _TS_PENDING_OLD=()
    local pending_current="" pending_canonical="" pending_observed="" receipt_present=false
    if [ -f "$identity_file" ]; then
        if ! _tailscale_identity_load "$identity_file"; then
            log_error "[TS-NAME] Identity receipt is invalid; leaving it untouched and making no remote change"
            return 1
        fi
        receipt_present=true
        if [ "$_TS_ID_MACHINE_ID" != "$machine_id" ]; then
            log_error "[TS-NAME] Receipt belongs to a different machine-id; refusing to reuse its history"
            return 1
        fi
        # The stored canonical wins: it is what this device was named before any
        # collision, and re-deriving it from a host name that may itself have
        # been edited would silently move the target.
        canonical=$(_tailscale_name_label "$_TS_ID_CANONICAL" "")
        if [ -z "$canonical" ]; then
            log_error "[TS-NAME] Stored canonical name '${_TS_ID_CANONICAL}' is not a legal label; skipping"
            return 1
        fi
        pending_current="$_TS_ID_PENDING_CURRENT"
        pending_canonical="$_TS_ID_PENDING_CANONICAL"
        pending_observed="$_TS_ID_PENDING_OBSERVED"
    fi

    # Is this node id already recorded as ours? Both shortcuts below rest on
    # that: an id this device has never confirmed with the control plane is new
    # evidence, and new evidence is always worth one GET.
    local id known=false
    for id in "${_TS_NODE_IDS[@]}"; do
        [ "$id" = "$self_id" ] && { known=true; break; }
    done

    # --- Healthy shortcut: no API call, no write -------------------------------
    # Deliberately also gated on the alert state, so a device that previously
    # reported a problem still performs one read-only confirmation before the
    # recovery notification is allowed to fire.
    if [ "$receipt_present" = true ] && [ -z "$pending_current" ] \
        && [ "$self_label" = "$canonical" ] && [ "$known" = true ] \
        && ! _tailscale_alerts_block_shortcut; then
        log_debug "[TS-NAME] Name ${canonical} and node ${self_id} already reconciled"
        return 0
    fi

    # --- Waiting on a human: re-derive that verdict on a TTL, not every tick ---
    # The one state this device cannot act on, and the only one gated here: the
    # name is not canonical, nothing is pending, and an earlier tick already
    # concluded there is no provable stale node and paged NAME_REPAIR_SKIPPED
    # for it. Nothing this device does moves that verdict, and re-deriving it
    # costs an OAuth token exchange plus a device GET every five minutes until
    # an operator acts.
    #
    # Everything that CAN still change is excluded rather than delayed:
    #   * a pending repair is live work and runs every tick;
    #   * an unrecorded node id is unconfirmed history, so it is confirmed now;
    #   * a canonical name is the recovery case, handled by the shortcut above,
    #     which deliberately blocks itself while an alert is unsettled;
    #   * a TAILSCALE_AUTH_BLOCKED source that is still failing, or whose
    #     recovery has not reached every destination that was paged, owes a
    #     read-only probe — the replay that produces the recovery message —
    #     so any unsettled source keeps the full path running;
    #   * an unreadable or missing ledger answers "not open", which opens the
    #     gate: this reduces work only on evidence, never on doubt.
    # ~/.evo-force-refresh bypasses it through fresh_due, and the operator's
    # own fix ends it: the name turns canonical and the shortcut above takes
    # over with its recovery confirmation.
    if [ "$receipt_present" = true ] && [ -z "$pending_current" ] \
        && [ "$known" = true ] && [ "$self_label" != "$canonical" ] \
        && _tailscale_alert_event_is_open "NAME_REPAIR_SKIPPED" \
        && [ -z "$(_tailscale_alert_unsettled_sources)" ] \
        && ! fresh_due "$TAILSCALE_NAME_SKIP_OP"; then
        log_debug "[TS-NAME] Name ${self_label} still needs the Admin Console; within the re-check TTL, no API call this tick"
        return 0
    fi

    local ips_json
    ips_json=$(_tailscale_json_string_array "${_TS_SELF_IPS[@]}")
    if [ -z "$ips_json" ]; then
        log_error "[TS-NAME] Could not encode local Tailscale addresses; skipping"
        return 1
    fi

    local body_file rc=0
    if ! _tailscale_buffer_new; then
        log_error "[TS-NAME] Could not create a response buffer; skipping"
        return 1
    fi
    body_file="$_TS_BUFFER_PATH"
    _tailscale_reconcile_remote "$body_file" "$machine_id" "$canonical" "$self_id" \
        "$dns_suffix" "$self_label" "$pending_current" "$pending_canonical" \
        "$pending_observed" "$ips_json" "$self_dnsname" || rc=$?
    _tailscale_buffer_release "$body_file"
    return "$rc"
}

#===============================================================================
# CONFIGURATION FUNCTIONS
#===============================================================================

create_v4l2loopback_config() {
    local line="v4l2loopback"
    local file="/etc/modules-load.d/modules.conf"

    if ! grep -q "^$line\$" "$file"; then
        echo "$line" | sudo tee "$file" > /dev/null
        log "Added $line to $file."
    else
        log_debug "$line is already in $file."
    fi

    local v4l2_opts_file="/etc/modprobe.d/v4l2loopback.conf"
    local v4l2_opts_content='options v4l2loopback devices=1 video_nr=10 card_label="OBS Virtual Camera" exclusive_caps=1'
    if [ ! -f "$v4l2_opts_file" ] || ! grep -qxF "$v4l2_opts_content" "$v4l2_opts_file"; then
        echo "$v4l2_opts_content" | sudo tee "$v4l2_opts_file" > /dev/null
        log "v4l2loopback.config modified"
    else
        log_debug "v4l2loopback.config already up to date"
    fi

    # Fix DKMS build failure on kernel 6.8+: strlcpy was removed from kernel API
    local dkms_src="/usr/src/v4l2loopback-0.12.7/v4l2loopback.c"
    if [ -f "$dkms_src" ] && grep -q 'strlcpy' "$dkms_src"; then
        sudo sed -i 's/strlcpy/strscpy/g' "$dkms_src"
        sudo dkms remove v4l2loopback/0.12.7 --all 2>/dev/null
        sudo dkms install v4l2loopback/0.12.7 2>/dev/null
        log "Patched v4l2loopback DKMS source (strlcpy→strscpy) and rebuilt"
    fi
}

create_ubuntu_lock_screen_files() {
    local desktop_file_content="[Desktop Entry]
Type=Application
Exec=$HOME/lock-screen.sh
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_US]=Lock Screen
Name=Lock Screen
Comment[en_US]=lock screen after login
Comment=lock screen after login"

    local lock_script_content="#!/bin/sh
sleep 3
gnome-screensaver-command -l"

    mkdir -p "$HOME/.config/autostart"
    echo "$desktop_file_content" > "$HOME/.config/autostart/lock-screen.sh.desktop"
    echo "$lock_script_content" > "$HOME/lock-screen.sh"
    chmod +x "$HOME/lock-screen.sh"
    log "Lock screen files created successfully."
}

create_lubuntu_lock_screen_files() {
    local desktop_file_content="[Desktop Entry]
Type=Application
Exec=$HOME/lock-screen.sh
Hidden=false
NoDisplay=false
X-LXQt-Need-Tray=true
Name[en_US]=Lock Screen
Name=Lock Screen
Comment[en_US]=Lock screen after login
Comment=Lock screen after login"

    local lock_script_content="#!/bin/sh
sleep 1
xscreensaver-command -lock"

    mkdir -p "$HOME/.config/autostart/"
    echo "$desktop_file_content" > "$HOME/.config/autostart/lock-screen.sh.desktop"
    echo "$lock_script_content" > "$HOME/lock-screen.sh"
    chmod +x "$HOME/lock-screen.sh"
    echo "Lock screen files created successfully."
}

create_sudoer_files() {
    sudo bash -c 'echo "evobox ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart SRStreamer.service" > /etc/sudoers.d/evobox-srstreamer'
    sudo chmod 440 /etc/sudoers.d/evobox-srstreamer
}

#===============================================================================
# SYSTEMD DAEMON SUPERVISION
#===============================================================================

# Systemd unit / helper paths
readonly DAEMON_UNIT_MAIN="evo-obs-daemon.service"
readonly DAEMON_UNIT_SECOND="evo-obs-daemon-second.service"
readonly DAEMON_UNIT_MAIN_PATH="/etc/systemd/system/$DAEMON_UNIT_MAIN"
readonly DAEMON_UNIT_SECOND_PATH="/etc/systemd/system/$DAEMON_UNIT_SECOND"
readonly DAEMON_RUNNER_PATH="/usr/local/bin/evo-daemon-run.sh"
readonly DAEMON_ALERT_PATH="/usr/local/bin/evo-daemon-alert.sh"
readonly OBSERVABILITY_UNIT="evobox-observability.service"
readonly OBSERVABILITY_UNIT_PATH="/etc/systemd/system/$OBSERVABILITY_UNIT"
readonly OBSERVABILITY_BINARY="/home/evobox/.local/bin/evobox-observability"
readonly OBSERVABILITY_GCS="https://storage.googleapis.com/releases-evosports/evobox/observability"
readonly OBSERVABILITY_CHECK_TTL=43200
readonly OBSERVABILITY_RETRY_TTL=3600
readonly OBSERVABILITY_STATE_DIR="/home/evobox/.local/state/evobox-observability"
readonly OBSERVABILITY_LOGROTATE_PATH="/etc/logrotate.d/evobox-observability"

# Sustained-downtime alerting: when a daemon unit has been continuously
# not-active for DAEMON_DOWN_THRESHOLD seconds, fire a webhook. This
# complements the per-exit ExecStopPost crash alert — it catches cases
# where the unit is stuck in failed state (burst-limit exhausted), hung
# in activating, or the ExecStopPost alert was rate-limited away.
# Rate-limited to one alert per unit per DAEMON_DOWN_ALERT_COOLDOWN.
readonly DAEMON_DOWN_THRESHOLD=900        # 15 minutes of continuous downtime
readonly DAEMON_DOWN_ALERT_COOLDOWN=3600  # 1 hour between sustained-down alerts per unit

# Write $2 to path $1 only when its SHA-256 differs from what's there.
# $3 is the mode (e.g. 0644, 0755). Returns 0 if file changed, 1 if unchanged,
# 2 on error. Uses sudo so it works for both /usr/local/bin and /etc/systemd.
write_if_sha_changed() {
    local path="$1" content="$2" mode="$3"
    local desired_sha current_sha=""
    desired_sha=$(printf '%s' "$content" | sha256sum | awk '{print $1}')

    if [ -f "$path" ]; then
        current_sha=$(sha256sum "$path" 2>/dev/null | awk '{print $1}')
    fi

    if [ "$desired_sha" = "$current_sha" ]; then
        return 1  # unchanged
    fi

    local tmp
    tmp=$(mktemp) || { log_error "[SYSTEMD] mktemp failed for $path"; return 2; }
    printf '%s' "$content" > "$tmp" || { rm -f "$tmp"; log_error "[SYSTEMD] write to tmp failed"; return 2; }
    if ! sudo install -m "$mode" "$tmp" "$path"; then
        rm -f "$tmp"
        log_error "[SYSTEMD] failed to install $path"
        return 2
    fi
    rm -f "$tmp"
    log "[SYSTEMD] Wrote $path (sha=$desired_sha)"
    return 0
}

# Installs /usr/local/bin/zowie-ndi-probe-check — the scheduled, out-of-process
# NDI health check. It reads THIS EvoBox's assigned cameras from OBS (live over
# the daemon's WebSocket, or the saved scene collection only when OBS is absent)
# and runs a bounded, read-only `zowie-ndi-probe check` per assigned camera, up
# to four attempts with jitter. It keeps the small amount of cross-day state
# that three-day intermittent detection, deduplication and recovery notices
# need, and posts Google Chat / Discord messages itself.
#
# It is BEST-EFFORT and FAILS OPEN: any problem (missing runtime/binary/state,
# lock contention, probe failure or timeout) is logged and the wrapper always
# exits 0, so it can never affect the daemon. It only ever runs `check` — never
# record/watch/discover/setup.
#
# The 04:40 cron schedule lives in the centrally-deployed crontab, not here.
#
# Webhook URLs are handed to the check over fd 3. They never appear in argv, the
# exported environment, the state file, message text or the log.

# A fresh wrapper only counts as current if it is still a regular, evobox-owned,
# 0700 file. A symlink or a group/world-readable copy carries the baked-in
# webhook URLs, so it has to be replaced even inside the freshness window.
_zwp_check_wrapper_private() {
    local path="$1" meta
    [ -L "$path" ] && return 1
    [ -f "$path" ] || return 1
    meta="$(stat -c '%F|%U|%G|%a' "$path" 2>/dev/null)" || return 1
    [ "$meta" = "regular file|evobox|evobox|700" ] || return 1
    return 0
}

# Install the generated wrapper without replacing a running reader's inode:
# stage inside the destination directory, set owner and mode on the staged
# file, syntax-check it, then rename atomically. write_if_sha_changed() cannot
# be used here because its `sudo install` writes over the destination itself,
# which would hand a half-written script to an 04:40 run already in progress.
# Returns 0 installed, 1 already current, 2 error.
_zwp_install_check_wrapper() {
    local content="$1"
    local path="$ZOWIE_NDI_PROBE_CHECK_WRAPPER"
    local desired current="" dir tmp
    desired=$(printf '%s' "$content" | sha256sum | awk '{print $1}')

    if _zwp_check_wrapper_private "$path"; then
        current=$(sha256sum "$path" 2>/dev/null | awk '{print $1}')
        [ "$desired" = "$current" ] && return 1
    fi

    dir="$(dirname "$path")"
    tmp="$(sudo mktemp "$dir/.zowie-ndi-probe-check.XXXXXX")" || {
        log_error "[ZWP-CHECK] mktemp failed in $dir"
        return 2
    }
    if ! printf '%s' "$content" | sudo tee "$tmp" >/dev/null; then
        sudo rm -f "$tmp"
        log_error "[ZWP-CHECK] staging write failed for $path"
        return 2
    fi
    if ! sudo chown evobox:evobox "$tmp" || ! sudo chmod 0700 "$tmp"; then
        sudo rm -f "$tmp"
        log_error "[ZWP-CHECK] staging ownership/mode failed for $path"
        return 2
    fi
    if ! sudo bash -n "$tmp"; then
        sudo rm -f "$tmp"
        log_error "[ZWP-CHECK] generated wrapper failed bash -n; keeping the current $path"
        return 2
    fi
    if ! sudo mv -f "$tmp" "$path"; then
        sudo rm -f "$tmp"
        log_error "[ZWP-CHECK] atomic rename failed for $path"
        return 2
    fi
    log "[ZWP-CHECK] Installed $path (sha=$desired)"
    return 0
}

install_zowie_ndi_probe_check_wrapper() {
    # Auxiliary + best-effort: skip the per-tick here-doc materialization (a
    # temp-file write to eMMC) when the wrapper is already present, private and
    # the 12h freshness window is open. The wrapper body only changes when this
    # installer is redeployed and it only executes once/day at 04:40, so a
    # <=12h propagation delay is harmless. A missing, non-private or stale
    # wrapper still forces immediate re-creation.
    if _zwp_check_wrapper_private "$ZOWIE_NDI_PROBE_CHECK_WRAPPER" \
        && ! fresh_due "zowie_probe_wrapper" "$ZOWIE_NDI_PROBE_CHECK_TTL"; then
        return 0
    fi
    # The pinned runtimes are data, not code: reject anything that is not a
    # release version rather than baking an arbitrary string into a path.
    if ! [[ "$NODE_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        log_error "[ZWP-CHECK] NODE_VERSION '$NODE_VERSION' is not vMAJOR.MINOR.PATCH; wrapper not generated"
        return 0
    fi
    if ! [[ "$NODE_FALLBACK_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        log_error "[ZWP-CHECK] NODE_FALLBACK_VERSION '$NODE_FALLBACK_VERSION' is not vMAJOR.MINOR.PATCH; wrapper not generated"
        return 0
    fi
    # Materialize the wrapper via a here-doc to a temp file, then read it back.
    # NOTE: do NOT use content="$(cat <<'EOF' ... )" — bash 3.2's command-sub
    # parser miscounts the unbalanced ')' in the wrapper's case patterns and
    # breaks parsing. A here-doc redirect (not inside $()) avoids that entirely.
    local runtime_version content tmp
    runtime_version="$(node_runtime_version)"
    tmp="$(mktemp)" || { log_error "[ZWP-CHECK] mktemp failed for wrapper"; return 0; }
    cat > "$tmp" <<'ZWP_WRAPPER_HEAD'
#!/bin/bash
# zowie-ndi-probe-check — scheduled, out-of-process NDI health check.
# Managed by evobox-obs-daemon-install.sh; do not edit on the device.
#
# BEST-EFFORT / FAIL-OPEN: every outcome is logged and this script always exits
# 0 so it can never affect evo-obs-daemon. It only ever runs `check`.
#
# This shell part does nothing but validate its own preconditions and take the
# single-instance lock. The check itself is one embedded Node program, because
# reading the OBS assignment already requires the daemon's obs-websocket-js.

# Deliberately NO `set -e` / `set -u` — never abort mid-run.

ZWP_WRAPPER_HEAD
    printf 'ZWP_CHECK_NODE_DEFAULT="/home/evobox/.config/nvm/versions/node/%s/bin/node"\n' \
        "$runtime_version" >> "$tmp"
    # A device whose NODE_VERSION install failed is still running the fallback;
    # pointing the check at a runtime that is not on disk would turn every NDI
    # health alert off on exactly the devices that are already in trouble.
    printf '[ -x "$ZWP_CHECK_NODE_DEFAULT" ] || ZWP_CHECK_NODE_DEFAULT="/home/evobox/.config/nvm/versions/node/%s/bin/node"\n' \
        "$NODE_FALLBACK_VERSION" >> "$tmp"
    cat >> "$tmp" <<'ZWP_WRAPPER_MID'

# --- Fixed production paths (test-only overrides must be absolute) ------------
NODE_BIN="${ZWP_CHECK_NODE:-$ZWP_CHECK_NODE_DEFAULT}"
DAEMON_DIR="${ZWP_CHECK_DAEMON_DIR:-/home/evobox/evosports/evo-obs-daemon-main}"
OBS_CONFIG_DIR="${ZWP_CHECK_OBS_CONFIG_DIR:-/home/evobox/.config/obs-studio}"
BIN="${ZWP_CHECK_BIN:-/home/evobox/.local/bin/zowie-ndi-probe}"
LOG="${ZWP_CHECK_LOG:-/home/evobox/logs/zowie-ndi-probe-check.log}"
LOCK="${ZWP_CHECK_LOCK:-/tmp/zowie-ndi-probe-check.lock}"
STATE="${ZWP_CHECK_STATE:-/home/evobox/.evo-cache/ndi-probe-alerts.json}"
EVO_JSON="${ZWP_CHECK_EVO_JSON:-/home/evobox/evosports/evo-obs-daemon-main/evo.json}"
WS_URL="${ZWP_CHECK_OBS_WS_URL:-ws://127.0.0.1:4444}"

# Shell backstop around the Node program: 900s budget + 5s for its own shutdown.
RUN_TIMEOUT=905
LOG_MAX_BYTES=1048576

log() {
    local msg="$1" ts size
    ts="$(date -u '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null)"
    mkdir -p "$(dirname "$LOG")" 2>/dev/null
    size="$(stat -c %s "$LOG" 2>/dev/null || echo 0)"
    if [ "${size:-0}" -ge "$LOG_MAX_BYTES" ]; then
        mv -f "$LOG.3" "$LOG.4" 2>/dev/null
        mv -f "$LOG.2" "$LOG.3" 2>/dev/null
        mv -f "$LOG.1" "$LOG.2" 2>/dev/null
        mv -f "$LOG" "$LOG.1" 2>/dev/null
    fi
    printf '%s zowie-ndi-probe-check: %s\n' "$ts" "$(printf '%s' "$msg" | tr -d '\000' | tr '[:cntrl:]' ' ')" \
        >> "$LOG" 2>/dev/null
}

# All override paths must be absolute (cron has a minimal PATH; we never rely
# on relative resolution).
for p in "$NODE_BIN" "$DAEMON_DIR" "$OBS_CONFIG_DIR" "$BIN" "$LOG" "$LOCK" "$STATE" "$EVO_JSON"; do
    case "$p" in
        /*) ;;
        *) log "skip: non-absolute path override ($p)"; exit 0 ;;
    esac
done

# The OBS WebSocket is always this device's own loopback socket. A test override
# may move the port but can never point the check at another host.
case "$WS_URL" in
    ws://127.0.0.1:*|ws://localhost:*|ws://[::1]:*) ;;
    *) log "skip: OBS WebSocket override is not loopback ($WS_URL)"; exit 0 ;;
esac

# A missing runtime or tool is a safe skip, never a camera outage.
if [ ! -x "$NODE_BIN" ]; then
    log "skip: node runtime missing or not executable ($NODE_BIN)"
    exit 0
fi
ZWP_TIMEOUT_BIN="$(command -v timeout 2>/dev/null)"
ZWP_FLOCK_BIN="$(command -v flock 2>/dev/null)"
ZWP_PGREP_BIN="$(command -v pgrep 2>/dev/null)"
for tool in "$ZWP_TIMEOUT_BIN" "$ZWP_FLOCK_BIN" "$ZWP_PGREP_BIN"; do
    if [ -z "$tool" ]; then
        log "skip: missing one of timeout/flock/pgrep"
        exit 0
    fi
done

# Single-instance lock on a DEDICATED fd 9 (never the installer's fd 200).
exec 9>"$LOCK" || { log "skip: cannot open lock $LOCK"; exit 0; }
if ! "$ZWP_FLOCK_BIN" -n 9; then
    log "skip: another check is already running"
    exit 0
fi

# Log and state must be writable before anything is measured: without them a
# fault cannot be deduplicated or reported, and a silent duplicate page is
# worse than a skipped run.
mkdir -p "$(dirname "$LOG")" 2>/dev/null
if ! : >> "$LOG" 2>/dev/null; then
    exit 0
fi
mkdir -p "$(dirname "$STATE")" 2>/dev/null
chmod 700 "$(dirname "$STATE")" 2>/dev/null
if [ ! -w "$(dirname "$STATE")" ]; then
    log "skip: state directory is not writable ($(dirname "$STATE"))"
    exit 0
fi

export ZWP_CHECK_BIN="$BIN"
export ZWP_CHECK_LOG="$LOG"
export ZWP_CHECK_STATE="$STATE"
export ZWP_CHECK_DAEMON_DIR="$DAEMON_DIR"
export ZWP_CHECK_OBS_CONFIG_DIR="$OBS_CONFIG_DIR"
export ZWP_CHECK_EVO_JSON="$EVO_JSON"
export ZWP_CHECK_OBS_WS_URL="$WS_URL"
export ZWP_CHECK_TIMEOUT_BIN="$ZWP_TIMEOUT_BIN"
export ZWP_CHECK_PGREP_BIN="$ZWP_PGREP_BIN"

# Webhook destinations (id|provider|url), baked in at install time so the
# wrapper runs standalone under cron (same pattern as evo-daemon-alert.sh).
# They reach the check on fd 3 only: a `printf` builtin in a subshell, so no
# URL is ever an argument to an executable or an exported variable.
WEBHOOK_DESTINATIONS=(
ZWP_WRAPPER_MID
    render_shell_array_entries "${DAEMON_ALERT_WEBHOOK_DESTINATIONS[@]}" >> "$tmp"
    cat >> "$tmp" <<'ZWP_WRAPPER_TAIL'
)

"$ZWP_TIMEOUT_BIN" -k 5 "$RUN_TIMEOUT" "$NODE_BIN" \
    3< <(printf '%s\n' "${WEBHOOK_DESTINATIONS[@]}") <<'ZWP_CHECK_PROGRAM'
'use strict';
// zowie-ndi-probe-check core — one bounded daily NDI health run.
//
// Reads this EvoBox's assigned cameras from OBS (live, or the saved scene
// collection only when OBS is absent), probes each assigned camera with the
// installed zowie-ndi-probe, keeps the cross-day incident state needed for
// three-day intermittent detection and recovery notices, and delivers Google
// Chat / Discord messages itself. Everything is best-effort: the wrapper always
// exits 0.
//
// Webhook URLs arrive on fd 3 and never appear in argv, the environment, the
// state file, message text or the log.
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const http = require('http');
const https = require('https');
const { spawn, spawnSync } = require('child_process');

// --- Fixed bounds ------------------------------------------------------------
const ATTEMPTS = 4;
// Whole seconds, inclusive, before attempts 2/3/4. Attempt 1 never waits.
const JITTER_RANGES = [null, [5, 10], [10, 20], [20, 40]];
const PULL_SECS = 10;
const CONNECT_TIMEOUT_MS = 15000;
const WATCHDOG_MS = 15000;
const PROBE_TIMEOUT_SECS = 30;
const PROBE_KILL_GRACE_SECS = 5;
const PROBE_CHILD_BOUND_MS = (PROBE_TIMEOUT_SECS + PROBE_KILL_GRACE_SECS) * 1000;
const CTX_DEADLINE_MS = 10000;
const TOTAL_BUDGET_MS = 900000;
const DELIVERY_RESERVE_MS = 60000;
const INTERMITTENT_THRESHOLD = 3;
const DAY_HISTORY_LIMIT = 3;
const RETRY_FLOOR_MS = 3600 * 1000;
const TOMBSTONE_DAYS = 7;
const MAX_STDOUT_BYTES = 256 * 1024;
const MAX_STDERR_BYTES = 4096;
const STDERR_EXCERPT_CHARS = 160;
const STATE_MAX_BYTES = 256 * 1024;
const MAX_CAMERA_RECORDS = 192;
const MAX_CHECKER_RECORDS = 64;
const MAX_NODES = 64;
const MAX_CAMERAS = 64;
const MAX_NAME_LEN = 256;
const MAX_FILE_BYTES = 2 * 1024 * 1024;
const LOG_MAX_BYTES = 1048576;
const LOG_KEEP = 4;
const CHAT_LIMIT = 3000;
const DISCORD_LIMIT = 1900;
const HTTP_CONNECT_MS = 3000;
const HTTP_TOTAL_MS = 10000;
// A delivery step is one POST plus the state writes that bracket it. Starting
// one that cannot finish would record an attempt whose answer is never read.
const DELIVERY_STEP_MS = HTTP_TOTAL_MS + 2000;
const NAME_PREFIXES = 'POVZoom,ZowieCAM,ZowieTek';
const TITLE = 'EvoBox NDI Probe Health';
const TAILNET = 'tail8e5b73.ts.net';
const SCHEMA_VERSION = 2;

const PROBE_BIN = process.env.ZWP_CHECK_BIN || '';
const LOG_PATH = process.env.ZWP_CHECK_LOG || '';
const STATE_PATH = process.env.ZWP_CHECK_STATE || '';
const DAEMON_DIR = process.env.ZWP_CHECK_DAEMON_DIR || '';
const OBS_CONFIG_DIR = process.env.ZWP_CHECK_OBS_CONFIG_DIR || '';
const EVO_JSON = process.env.ZWP_CHECK_EVO_JSON || '';
const TIMEOUT_BIN = process.env.ZWP_CHECK_TIMEOUT_BIN || '/usr/bin/timeout';
const PGREP_BIN = process.env.ZWP_CHECK_PGREP_BIN || '/usr/bin/pgrep';
const WS_URL = process.env.ZWP_CHECK_OBS_WS_URL || '';

const SHORT_HOST = String(os.hostname() || 'unknown-host').split('.')[0] || 'unknown-host';
const RUN_ID = crypto.randomUUID().slice(0, 8);

// Everything this run has in flight, so a signal can cancel it rather than
// orphan a probe that keeps pulling from a camera.
const ACTIVE_CHILDREN = new Set();
const ACTIVE_REQUESTS = new Set();

// --- Monotonic budget --------------------------------------------------------
const monoMs = () => Number(process.hrtime.bigint() / 1000000n);
const RUN_START_MS = monoMs();
const elapsedMs = () => monoMs() - RUN_START_MS;
const remainingMs = () => TOTAL_BUDGET_MS - elapsedMs();
const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });

// --- Logging -----------------------------------------------------------------
const oneLine = (value, max) => String(value === undefined || value === null ? '' : value)
    .replace(/[\u0000-\u001f\u007f]/g, ' ')
    .slice(0, max);

function rotateLog() {
    let size = 0;
    try {
        size = fs.statSync(LOG_PATH).size;
    } catch (e) {
        return;
    }
    if (size < LOG_MAX_BYTES) return;
    for (let i = LOG_KEEP - 1; i >= 1; i -= 1) {
        try {
            fs.renameSync(LOG_PATH + '.' + i, LOG_PATH + '.' + (i + 1));
        } catch (e) { /* a missing generation is normal */ }
    }
    try {
        fs.renameSync(LOG_PATH, LOG_PATH + '.1');
    } catch (e) { /* keep appending to the current file */ }
}

function log(message) {
    const stamp = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
    try {
        fs.mkdirSync(path.dirname(LOG_PATH), { recursive: true });
    } catch (e) { /* the append below reports the real problem */ }
    rotateLog();
    try {
        fs.appendFileSync(LOG_PATH,
            stamp + ' zowie-ndi-probe-check[' + RUN_ID + ']: ' + oneLine(message, 1000) + '\n');
    } catch (e) { /* a lost log line must not abort the run */ }
}

// --- Display sanitising ------------------------------------------------------
// Device-supplied text reaches an operator's chat client. Control characters
// could forge a log row; `@` and `<` are the two mention openers. The opaque
// probe argument is never passed through here.
function display(value, max) {
    return oneLine(value, max === undefined ? 300 : max)
        .replace(/@/g, '@\u200b')
        .replace(/</g, '\u2039');
}

// --- Destinations (fd 3) -----------------------------------------------------
function readFdFully(fd) {
    const chunks = [];
    const buf = Buffer.alloc(65536);
    for (let guard = 0; guard < 4096; guard += 1) {
        let n;
        try {
            n = fs.readSync(fd, buf, 0, buf.length, null);
        } catch (e) {
            if (e && (e.code === 'EAGAIN' || e.code === 'EINTR')) continue;
            if (e && e.code === 'EOF') break;
            throw e;
        }
        if (n === 0) break;
        chunks.push(Buffer.from(buf.slice(0, n)));
    }
    return Buffer.concat(chunks).toString('utf8');
}

function readDestinations() {
    let text;
    try {
        text = readFdFully(3);
    } catch (e) {
        return { ok: false, reason: 'the destination channel could not be read' };
    } finally {
        try { fs.closeSync(3); } catch (e) { /* already gone */ }
    }
    const out = [];
    const seen = new Set();
    for (const raw of text.split('\n')) {
        const line = raw.trim();
        if (line.length === 0) continue;
        const first = line.indexOf('|');
        const second = line.indexOf('|', first + 1);
        if (first <= 0 || second <= first + 1 || second === line.length - 1) {
            return { ok: false, reason: 'a destination entry is not id|provider|url' };
        }
        const id = line.slice(0, first);
        const provider = line.slice(first + 1, second);
        const url = line.slice(second + 1);
        if (!/^[A-Za-z0-9._-]{1,64}$/.test(id)) return { ok: false, reason: 'a destination id is unusable' };
        if (seen.has(id)) return { ok: false, reason: 'destination ids are not unique' };
        if (provider !== 'google_chat' && provider !== 'discord') {
            return { ok: false, reason: 'destination "' + id + '" names an unsupported provider' };
        }
        let parsed;
        try {
            parsed = new URL(url);
        } catch (e) {
            return { ok: false, reason: 'destination "' + id + '" has an unusable URL' };
        }
        if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
            return { ok: false, reason: 'destination "' + id + '" is not HTTP(S)' };
        }
        seen.add(id);
        out.push({ id: id, provider: provider, url: url });
    }
    if (out.length === 0) return { ok: false, reason: 'no destinations are configured' };
    return { ok: true, destinations: out };
}

// --- Calendar ----------------------------------------------------------------
function localDateKey(date) {
    const year = String(date.getFullYear()).padStart(4, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return year + '-' + month + '-' + day;
}

// `n` calendar days before `dateKey`, with UTC date-only arithmetic so a DST
// transition cannot shift or duplicate a date.
function previousLocalDate(dateKey, n) {
    const parts = dateKey.split('-').map(Number);
    const base = Date.UTC(parts[0], parts[1] - 1, parts[2]) - n * 86400000;
    return new Date(base).toISOString().slice(0, 10);
}

// A real calendar date, not merely ten digits in the right places: `2026-02-30`
// would otherwise become a streak entry no later run can ever match.
const isDateKey = (v) => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v)
    && new Date(v + 'T00:00:00Z').toISOString().slice(0, 10) === v;

// Consecutive dates ending today whose failures recovered. A clean day and a
// persistent-only day both break continuity, which is what makes "3 consecutive
// days" mean anything.
function intermittentStreak(days, todayKey) {
    const byDate = new Map(days.map((d) => [d.date, d.transient]));
    let streak = 0;
    for (let back = 0; back < DAY_HISTORY_LIMIT; back += 1) {
        const key = back === 0 ? todayKey : previousLocalDate(todayKey, back);
        if (byDate.get(key) !== true) break;
        streak += 1;
    }
    return streak;
}

// A transient failure latches: a later clean check on the same date must not
// erase it, and a repeated run must not duplicate the date entry.
function recordDayFlag(camera, todayKey, transient) {
    const existing = camera.days.find((d) => d.date === todayKey);
    if (existing) {
        if (transient) existing.transient = true;
    } else {
        camera.days.push({ date: todayKey, transient: transient });
    }
    const window = new Set([todayKey, previousLocalDate(todayKey, 1), previousLocalDate(todayKey, 2)]);
    camera.days = camera.days.filter((d) => window.has(d.date));
    camera.days.sort((a, b) => (a.date < b.date ? -1 : 1));
}

// --- OBS context -------------------------------------------------------------
class CtxError extends Error {
    constructor(ctxCode, message) {
        super(message);
        this.ctxCode = ctxCode;
    }
}

const asciiLower = (s) => s.replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32));
const PREFIXES = NAME_PREFIXES.split(',').map((p) => asciiLower(p.trim())).filter((p) => p.length > 0);

// An opaque NDI name is preserved byte for byte. Only length and control
// characters are rejected, because a control character could forge a log line.
function validName(name) {
    if (typeof name !== 'string') return null;
    if (name.length === 0 || name.length > MAX_NAME_LEN) return null;
    if (/[\u0000-\u001f\u007f]/.test(name)) return null;
    return name;
}
function allowlisted(name) {
    const lowered = asciiLower(name);
    return PREFIXES.some((p) => lowered.indexOf(p) === 0);
}

function newBag() {
    return { cameras: new Map(), ignored: [], nodes: 0 };
}
function countNode(bag) {
    bag.nodes += 1;
    if (bag.nodes > MAX_NODES) {
        throw new CtxError('obs-context-too-large', 'the scene graph has more than ' + MAX_NODES + ' items');
    }
}
function addAssignment(bag, inputName, rawName) {
    const name = validName(rawName);
    if (name === null) {
        throw new CtxError('obs-context-invalid', 'an NDI input carries an unusable source name');
    }
    if (!allowlisted(name)) {
        bag.ignored.push({ inputName: inputName, name: name });
        return;
    }
    let entry = bag.cameras.get(name);
    if (!entry) {
        if (bag.cameras.size >= MAX_CAMERAS) {
            throw new CtxError('obs-context-too-large', 'more than ' + MAX_CAMERAS + ' cameras are assigned');
        }
        entry = new Set();
        bag.cameras.set(name, entry);
    }
    entry.add(inputName);
}

// Identity of the assignment: mode, program scene, camera/input mapping.
// Timestamps and outputActive are excluded — live routing is fresh evidence,
// not camera identity.
function normalize(mode, scene, bag) {
    const cameras = Array.from(bag.cameras.entries())
        .map((pair) => ({ name: pair[0], inputNames: Array.from(pair[1]).sort() }))
        .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
    return { mode: mode, scene: scene, cameras: cameras };
}
const fingerprintOf = (norm) => crypto.createHash('sha256').update(JSON.stringify(norm)).digest('hex');
function docOf(norm, outputActive, bag) {
    return {
        mode: norm.mode,
        scene: norm.scene,
        outputActive: outputActive,
        cameras: norm.cameras,
        ignoredInputs: bag.ignored.slice(0, MAX_CAMERAS),
        fingerprint: fingerprintOf(norm)
    };
}

async function liveSnapshot(obs) {
    const program = await obs.call('GetCurrentProgramScene');
    const scene = validName((program && (program.currentProgramSceneName || program.sceneName)) || '');
    if (scene === null) {
        throw new CtxError('obs-context-invalid', 'OBS did not name a usable current program scene');
    }
    const bag = newBag();
    const settings = new Map();
    const inputSettings = async (inputName) => {
        if (!settings.has(inputName)) {
            const got = await obs.call('GetInputSettings', { inputName: inputName });
            settings.set(inputName, (got && got.inputSettings) || {});
        }
        return settings.get(inputName);
    };
    const walk = async (nodeName, kind, trail) => {
        const stamp = kind + '\u0000' + nodeName;
        if (trail.indexOf(stamp) !== -1) {
            throw new CtxError('obs-context-invalid', 'the scene graph contains a cycle');
        }
        const nextTrail = trail.concat(stamp);
        const request = kind === 'group' ? 'GetGroupSceneItemList' : 'GetSceneItemList';
        const listed = await obs.call(request, { sceneName: nodeName });
        const items = listed && Array.isArray(listed.sceneItems) ? listed.sceneItems : null;
        if (items === null) {
            throw new CtxError('obs-context-invalid', 'OBS returned no item list for a traversed node');
        }
        for (const item of items) {
            countNode(bag);
            if (!item || typeof item !== 'object') {
                throw new CtxError('obs-context-invalid', 'OBS returned an unreadable scene item');
            }
            if (typeof item.sceneItemEnabled !== 'boolean') {
                throw new CtxError('obs-context-invalid', 'a scene item has no usable enabled flag');
            }
            if (!item.sceneItemEnabled) continue;
            const sourceName = validName(item.sourceName);
            if (sourceName === null) {
                throw new CtxError('obs-context-invalid', 'a scene item has an unusable source name');
            }
            if (item.isGroup === true) {
                await walk(sourceName, 'group', nextTrail);
                continue;
            }
            if (item.sourceType === 'OBS_SOURCE_TYPE_SCENE') {
                await walk(sourceName, 'scene', nextTrail);
                continue;
            }
            if (item.inputKind !== 'ndi_source') continue;
            const conf = await inputSettings(sourceName);
            if (typeof conf.ndi_source_name !== 'string' || conf.ndi_source_name.length === 0) {
                throw new CtxError('obs-context-invalid', 'an enabled NDI input has no assigned source');
            }
            addAssignment(bag, sourceName, conf.ndi_source_name);
        }
    };
    await walk(scene, 'scene', []);
    return { scene: scene, bag: bag };
}

function safeDisconnect(obs) {
    try {
        const done = obs.disconnect();
        if (done && typeof done.catch === 'function') done.catch(() => {});
    } catch (e) { /* closing a one-shot socket cannot change the verdict */ }
}

// `left()` returns the milliseconds remaining on the caller's single context
// deadline, so the live and saved steps share one ten-second budget.
async function liveContext(left) {
    let Client;
    try {
        const resolved = require.resolve('obs-websocket-js', { paths: [DAEMON_DIR] });
        const mod = require(resolved);
        Client = mod && (mod.default || mod.OBSWebSocket || mod);
    } catch (e) {
        return { kind: 'dependency', reason: 'obs-websocket-js is unavailable under ' + DAEMON_DIR };
    }
    if (typeof Client !== 'function') {
        return { kind: 'dependency', reason: 'obs-websocket-js did not export a client constructor' };
    }
    let obs;
    try {
        obs = new Client();
    } catch (e) {
        return { kind: 'dependency', reason: 'the OBS client could not be constructed' };
    }
    // The live timer is created here, around the only unbounded step, so expiry
    // can actually abort the socket. A handshake that never answers would
    // otherwise hold a connection to OBS for the rest of the run: the `finally`
    // below cannot run while `connect` is still pending.
    const remaining = left();
    if (remaining <= 0) {
        safeDisconnect(obs);
        return { kind: 'error', code: 'obs-context-unavailable', reason: 'the context deadline was already spent' };
    }
    let timer = null;
    const deadline = new Promise((resolve) => {
        timer = setTimeout(() => {
            safeDisconnect(obs);
            resolve({
                kind: 'error',
                code: 'obs-context-unavailable',
                reason: 'reading the camera assignment exceeded ' + CTX_DEADLINE_MS + ' ms'
            });
        }, remaining);
    });
    const work = (async () => {
        try {
            await obs.connect(WS_URL, undefined, { rpcVersion: 1, eventSubscriptions: 0 });
        } catch (e) {
            safeDisconnect(obs);
            return { kind: 'unreachable', reason: 'the OBS WebSocket did not answer: ' + ((e && e.message) || 'unknown') };
        }
        try {
            // Two complete snapshots inside the same deadline. One pass cannot
            // tell a settled assignment from one being edited underneath it.
            const first = await liveSnapshot(obs);
            const second = await liveSnapshot(obs);
            const before = normalize('live', first.scene, first.bag);
            const after = normalize('live', second.scene, second.bag);
            if (fingerprintOf(before) !== fingerprintOf(after)) {
                return { kind: 'error', code: 'context-changed', reason: 'the camera assignment changed while it was being read' };
            }
            let outputActive = null;
            const status = await obs.call('GetStreamStatus');
            if (status && typeof status.outputActive === 'boolean') outputActive = status.outputActive;
            return { kind: 'ok', doc: docOf(after, outputActive, second.bag) };
        } catch (e) {
            return {
                kind: 'error',
                code: (e instanceof CtxError) ? e.ctxCode : 'obs-context-unavailable',
                reason: (e && e.message) || 'the live assignment could not be read'
            };
        } finally {
            safeDisconnect(obs);
        }
    })();
    const out = await Promise.race([work, deadline]);
    clearTimeout(timer);
    return out;
}

// Only "no matching process" permits the saved configuration. A running or an
// unknown process means the live assignment is simply unavailable.
function obsPresence(budgetMs) {
    const bound = Math.max(1, Math.min(1000, Math.floor(budgetMs)));
    let r;
    try {
        r = spawnSync(PGREP_BIN, ['-x', 'obs'], { stdio: ['ignore', 'ignore', 'ignore'], timeout: bound });
    } catch (e) {
        return 'uncertain';
    }
    if (!r || r.error || r.signal) return 'uncertain';
    if (r.status === 1) return 'absent';
    if (r.status === 0) return 'running';
    return 'uncertain';
}

function iniValue(text, section, key) {
    let inSection = false;
    let value = null;
    for (const raw of text.split(/\r?\n/)) {
        const line = raw.trim();
        if (line.length > 1 && line.charAt(0) === '[' && line.charAt(line.length - 1) === ']') {
            inSection = line.slice(1, -1) === section;
            continue;
        }
        if (!inSection) continue;
        const eq = line.indexOf('=');
        if (eq <= 0) continue;
        if (line.slice(0, eq).trim() !== key) continue;
        value = line.slice(eq + 1).trim();
    }
    return value;
}

function readBounded(file, code) {
    let st;
    try {
        st = fs.lstatSync(file);
    } catch (e) {
        throw new CtxError(code, file + ' could not be inspected');
    }
    if (!st.isFile()) throw new CtxError(code, file + ' is not a regular file');
    if (st.size > MAX_FILE_BYTES) throw new CtxError(code, file + ' is larger than 2 MiB');
    try {
        return fs.readFileSync(file, 'utf8');
    } catch (e) {
        throw new CtxError(code, file + ' could not be read');
    }
}

function savedContext() {
    const code = 'obs-config-unreadable';
    const collection = iniValue(readBounded(path.join(OBS_CONFIG_DIR, 'global.ini'), code), 'Basic', 'SceneCollectionFile');
    if (typeof collection !== 'string' || collection.length === 0 || collection.length > MAX_NAME_LEN
        || collection.indexOf('/') !== -1 || collection.indexOf('\\') !== -1
        || collection.indexOf('..') !== -1 || /[\u0000-\u001f\u007f]/.test(collection)
        || collection === '.') {
        throw new CtxError(code, 'global.ini names no usable scene collection');
    }
    const file = path.join(OBS_CONFIG_DIR, 'basic', 'scenes', collection + '.json');
    let doc;
    try {
        doc = JSON.parse(readBounded(file, code));
    } catch (e) {
        if (e instanceof CtxError) throw e;
        throw new CtxError(code, 'the saved scene collection is not valid JSON');
    }
    if (!doc || typeof doc !== 'object') {
        throw new CtxError(code, 'the saved scene collection is not an object');
    }
    // Saved groups live in their own top-level array, so both have to be
    // indexed or a grouped camera disappears.
    const index = new Map();
    for (const listName of ['sources', 'groups']) {
        const list = doc[listName];
        if (list === undefined || list === null) continue;
        if (!Array.isArray(list)) throw new CtxError(code, 'the saved ' + listName + ' list is not an array');
        for (const entry of list) {
            if (!entry || typeof entry !== 'object') throw new CtxError(code, 'a saved source entry is unreadable');
            const name = validName(entry.name);
            if (name === null) throw new CtxError(code, 'a saved source has an unusable name');
            if (index.has(name)) throw new CtxError(code, 'the saved collection defines duplicate source names');
            index.set(name, entry);
        }
    }
    const sceneName = validName(
        (typeof doc.current_program_scene === 'string' && doc.current_program_scene.length > 0)
            ? doc.current_program_scene
            : (doc.current_program_scene === undefined ? doc.current_scene : doc.current_program_scene)
    );
    if (sceneName === null) throw new CtxError(code, 'the saved collection names no current program scene');
    if (!index.has(sceneName)) throw new CtxError(code, 'the saved current program scene is not defined');

    const bag = newBag();
    const walk = (nodeName, trail) => {
        if (trail.indexOf(nodeName) !== -1) throw new CtxError(code, 'the saved scene graph contains a cycle');
        const nextTrail = trail.concat(nodeName);
        const node = index.get(nodeName);
        const items = node.settings && node.settings.items;
        if (!Array.isArray(items)) throw new CtxError(code, 'a saved scene or group carries no item list');
        for (const item of items) {
            countNode(bag);
            if (!item || typeof item !== 'object') throw new CtxError(code, 'a saved scene item is unreadable');
            if (item.group_item_backup === true) continue;
            if (typeof item.visible !== 'boolean') throw new CtxError(code, 'a saved scene item has no usable visibility');
            if (!item.visible) continue;
            const name = validName(item.name);
            if (name === null) throw new CtxError(code, 'a saved scene item has an unusable name');
            const target = index.get(name);
            if (target === undefined) throw new CtxError(code, 'a saved scene item references an undefined source');
            if (target.id === 'scene' || target.id === 'group') {
                walk(name, nextTrail);
                continue;
            }
            if (target.id !== 'ndi_source') continue;
            const conf = target.settings || {};
            if (typeof conf.ndi_source_name !== 'string' || conf.ndi_source_name.length === 0) {
                throw new CtxError(code, 'a saved NDI input has no assigned source');
            }
            addAssignment(bag, name, conf.ndi_source_name);
        }
    };
    walk(sceneName, []);
    // Saved configuration is not live routing, so output activity is unknown.
    return docOf(normalize('saved', sceneName, bag), null, bag);
}

// One bounded assignment read. Resolves {ok, doc} or {ok:false, code, reason}.
async function readAssignment() {
    // One absolute deadline for the whole read. The live step gets whatever is
    // left and disconnects on expiry; every saved step is checked against the
    // same clock, so the fallback cannot run past it.
    const deadlineAt = monoMs() + CTX_DEADLINE_MS;
    const left = () => deadlineAt - monoMs();
    const expired = () => ({
        ok: false,
        code: 'obs-context-unavailable',
        reason: 'reading the camera assignment exceeded ' + CTX_DEADLINE_MS + ' ms'
    });

    const result = await liveContext(left);
    if (result.kind === 'ok') return { ok: true, doc: result.doc };
    if (result.kind === 'error') return { ok: false, code: result.code, reason: result.reason };
    if (result.kind === 'dependency') return { ok: false, code: 'obs-client-missing', reason: result.reason };

    if (left() <= 0) return expired();
    const before = obsPresence(left());
    if (before !== 'absent') {
        return {
            ok: false,
            code: 'obs-context-unavailable',
            reason: 'OBS is ' + before + ' but its WebSocket did not answer'
        };
    }
    if (left() <= 0) return expired();
    let doc;
    try {
        doc = savedContext();
    } catch (e) {
        return {
            ok: false,
            code: (e instanceof CtxError) ? e.ctxCode : 'obs-config-unreadable',
            reason: (e && e.message) || 'the saved configuration could not be read'
        };
    }
    if (left() <= 0) return expired();
    if (obsPresence(left()) !== 'absent') {
        return { ok: false, code: 'obs-context-unavailable', reason: 'OBS appeared while the saved configuration was being read' };
    }
    return { ok: true, doc: doc };
}

// Map a context failure onto one of the fixed checker categories. Dynamic error
// text never becomes a state key.
function checkerCodeFor(contextCode) {
    if (contextCode === 'obs-client-missing') return 'obs-client-missing';
    if (contextCode === 'obs-context-unavailable') return 'obs-context-unavailable';
    return 'context-invalid';
}

// --- Probe -------------------------------------------------------------------
const HEALTH_EXIT = { HEALTHY: 0, DEGRADED: 1, STALLED: 2, OFFLINE: 3 };

// The probe prints pretty JSON and then a one-line verdict. Parse only the
// leading object, and only after the child completed.
function parseLeadingJson(text) {
    const start = text.indexOf('{');
    if (start === -1) return null;
    let depth = 0;
    let inString = false;
    let escaped = false;
    for (let i = start; i < text.length; i += 1) {
        const c = text.charAt(i);
        if (inString) {
            if (escaped) { escaped = false; continue; }
            if (c === '\\') { escaped = true; continue; }
            if (c === '"') inString = false;
            continue;
        }
        if (c === '"') { inString = true; continue; }
        if (c === '{') depth += 1;
        else if (c === '}') {
            depth -= 1;
            if (depth === 0) {
                try {
                    return JSON.parse(text.slice(start, i + 1));
                } catch (e) {
                    return null;
                }
            }
        }
    }
    return null;
}

const finiteNonNeg = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
const triState = (v) => v === true || v === false || v === null || v === undefined;

// Turn a completed child into either a measured report or a diagnostic. No
// diagnostic is ever proof of an offline camera.
function classifyProbe(status, signal, stdout, stderr, spawnError) {
    const excerpt = oneLine(stderr, STDERR_EXCERPT_CHARS);
    if (spawnError) return { category: 'diagnostic', reasonCode: 'probe-spawn-failed', stderrExcerpt: excerpt };
    if (signal) return { category: 'diagnostic', reasonCode: 'probe-signalled', stderrExcerpt: excerpt };
    if (status === 124 || status === 137) return { category: 'diagnostic', reasonCode: 'probe-timeout', stderrExcerpt: excerpt };
    if (status === 5) return { category: 'ignored', reasonCode: 'probe-ignored-target', stderrExcerpt: excerpt };
    if (status === 4) return { category: 'diagnostic', reasonCode: 'probe-resolution-failed', stderrExcerpt: excerpt };
    if (status !== 0 && status !== 1 && status !== 2 && status !== 3) {
        return { category: 'diagnostic', reasonCode: 'probe-unexpected-exit', stderrExcerpt: excerpt };
    }
    const doc = parseLeadingJson(stdout);
    if (!doc || typeof doc !== 'object') {
        return { category: 'diagnostic', reasonCode: 'probe-output-unparsable', stderrExcerpt: excerpt };
    }
    if (doc.failure) return { category: 'diagnostic', reasonCode: 'probe-reported-failure', stderrExcerpt: excerpt };
    const health = doc.health;
    if (typeof health !== 'string' || !(health in HEALTH_EXIT) || HEALTH_EXIT[health] !== status) {
        return { category: 'diagnostic', reasonCode: 'probe-output-inconsistent', stderrExcerpt: excerpt };
    }
    if (typeof doc.reason_code !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(doc.reason_code)) {
        return { category: 'diagnostic', reasonCode: 'probe-output-inconsistent', stderrExcerpt: excerpt };
    }
    const pull = doc.pull;
    if (!pull || typeof pull !== 'object'
        || !Number.isInteger(pull.frames) || pull.frames < 0
        || !finiteNonNeg(pull.measured_fps) || !finiteNonNeg(pull.seconds)) {
        return { category: 'diagnostic', reasonCode: 'probe-output-inconsistent', stderrExcerpt: excerpt };
    }
    const httpPart = (doc.http && typeof doc.http === 'object') ? doc.http : null;
    if (!httpPart || typeof httpPart.answered !== 'boolean' || !triState(doc.ndi_port_open)) {
        return { category: 'diagnostic', reasonCode: 'probe-output-inconsistent', stderrExcerpt: excerpt };
    }
    return {
        category: health === 'HEALTHY' ? 'healthy' : 'measured-failure',
        health: health,
        reasonCode: doc.reason_code,
        reason: oneLine(doc.reason, 300),
        ndiPortOpen: doc.ndi_port_open === undefined ? null : doc.ndi_port_open,
        httpAnswered: httpPart.answered,
        httpHost: typeof httpPart.host === 'string' ? httpPart.host : null,
        frames: pull.frames,
        measuredFps: pull.measured_fps,
        target: typeof doc.target === 'string' ? doc.target : '',
        stderrExcerpt: excerpt
    };
}

const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
function numericHost(value) {
    if (typeof value !== 'string' || value.length === 0) return null;
    if (IPV4.test(value)) return value;
    if (/^[0-9a-fA-F:]+$/.test(value) && value.indexOf(':') !== -1) return value;
    return null;
}

// `Target::describe()` prints `url-address=<endpoint>` or `ndi-name=<name>`.
// Only the address form yields a reusable endpoint, and only when it is a
// numeric address with a valid port. A name is never parsed as an address.
function reusableEndpoint(report) {
    if (!report || report.category !== 'measured-failure') return null;
    const target = report.target || '';
    if (target.indexOf('url-address=') !== 0) return null;
    const endpoint = target.slice('url-address='.length);
    let host = null;
    let port = null;
    if (endpoint.charAt(0) === '[') {
        const close = endpoint.indexOf(']:');
        if (close === -1) return null;
        host = endpoint.slice(1, close);
        port = endpoint.slice(close + 2);
    } else {
        const colon = endpoint.lastIndexOf(':');
        if (colon <= 0) return null;
        host = endpoint.slice(0, colon);
        port = endpoint.slice(colon + 1);
    }
    if (numericHost(host) === null) return null;
    if (!/^\d{1,5}$/.test(port)) return null;
    const portNum = Number(port);
    if (portNum < 1 || portNum > 65535) return null;
    const camHost = numericHost(report.httpHost);
    if (camHost === null || camHost !== host) return null;
    return { endpoint: endpoint, camHost: camHost };
}

// One bounded probe child. `endpoint` reuses an address this run already
// resolved for the same camera; otherwise the full assigned name is used.
function runProbe(name, endpoint) {
    return new Promise((resolve) => {
        const args = [
            '-k', String(PROBE_KILL_GRACE_SECS), String(PROBE_TIMEOUT_SECS),
            PROBE_BIN, 'check'
        ];
        if (endpoint) {
            args.push('--ndi-url', endpoint.endpoint, '--cam-host', endpoint.camHost);
        } else {
            args.push('--ndi-name', name);
        }
        args.push(
            '--camera-name-prefixes', NAME_PREFIXES,
            '--json',
            '--pull-secs', String(PULL_SECS),
            '--connect-timeout-ms', String(CONNECT_TIMEOUT_MS),
            '--watchdog-ms', String(WATCHDOG_MS)
        );
        const env = Object.assign({}, process.env);
        delete env.ZOWIE_NDI_URL;
        delete env.ZOWIE_NDI_NAME;
        delete env.ZOWIE_CAM_HOST;
        let child;
        try {
            child = spawn(TIMEOUT_BIN, args, { stdio: ['ignore', 'pipe', 'pipe'], env: env });
        } catch (e) {
            resolve(classifyProbe(null, null, '', '', true));
            return;
        }
        ACTIVE_CHILDREN.add(child);
        let out = '';
        let err = '';
        let overflow = false;
        let done = false;
        const finish = (status, signal, spawnError) => {
            if (done) return;
            done = true;
            ACTIVE_CHILDREN.delete(child);
            clearTimeout(guard);
            if (overflow) {
                resolve({ category: 'diagnostic', reasonCode: 'probe-output-too-large', stderrExcerpt: '' });
                return;
            }
            resolve(classifyProbe(status, signal, out, err, spawnError));
        };
        const guard = setTimeout(() => {
            try { child.kill('SIGKILL'); } catch (e) { /* already gone */ }
            finish(null, 'SIGKILL', false);
        }, PROBE_CHILD_BOUND_MS);
        child.stdout.on('data', (chunk) => {
            if (out.length + chunk.length > MAX_STDOUT_BYTES) { overflow = true; return; }
            out += chunk;
        });
        child.stderr.on('data', (chunk) => {
            if (err.length < MAX_STDERR_BYTES) err += chunk;
        });
        child.on('error', () => finish(null, null, true));
        child.on('close', (status, signal) => finish(status, signal, false));
    });
}

// --- Camera check ------------------------------------------------------------
const jitterSeconds = (range) => crypto.randomInt(range[0], range[1] + 1);

// Budget an attempt needs end to end: its context confirmation, its jitter and
// the complete child bound. A probe is never shortened to fit.
const attemptCostMs = (jitter) => CTX_DEADLINE_MS + jitter * 1000 + PROBE_CHILD_BOUND_MS;

async function checkCamera(name, fingerprint) {
    const attempts = [];
    let endpoint = null;
    for (let i = 0; i < ATTEMPTS; i += 1) {
        const range = JITTER_RANGES[i];
        const jitter = range ? jitterSeconds(range) : 0;
        if (remainingMs() - DELIVERY_RESERVE_MS < attemptCostMs(jitter)) {
            log('camera=' + oneLine(name, 120) + ' attempt=' + (i + 1) + ' skipped=insufficient-budget');
            return { outcome: 'incomplete', attempts: attempts };
        }
        if (jitter > 0) {
            log('camera=' + oneLine(name, 120) + ' attempt=' + (i + 1) + ' jitter=' + jitter + 's');
            await sleep(jitter * 1000);
        }
        const confirm = await readAssignment();
        if (!confirm.ok || confirm.doc.fingerprint !== fingerprint) {
            log('camera=' + oneLine(name, 120) + ' attempt=' + (i + 1)
                + ' aborted=context-' + (confirm.ok ? 'changed' : oneLine(confirm.code, 40)));
            return { outcome: 'incomplete', attempts: attempts };
        }
        const report = await runProbe(name, endpoint);
        attempts.push(report);
        log('camera=' + oneLine(name, 120) + ' attempt=' + (i + 1) + '/' + ATTEMPTS
            + ' category=' + report.category
            + ' health=' + (report.health || '-')
            + ' reason=' + oneLine(report.reasonCode, 64)
            + (report.frames === undefined ? '' : ' frames=' + report.frames)
            + (endpoint ? ' via=endpoint' : ' via=name'));
        if (report.category === 'ignored') {
            return { outcome: 'ignored', attempts: attempts };
        }
        if (report.category === 'healthy') {
            return { outcome: i === 0 ? 'healthy' : 'intermittent', attempts: attempts, recoveryAttempt: i + 1 };
        }
        if (endpoint === null) endpoint = reusableEndpoint(report);
    }
    const diagnostic = attempts.some((a) => a.category === 'diagnostic');
    return { outcome: diagnostic ? 'probe-error' : 'persistent', attempts: attempts };
}

// --- Verdict evidence --------------------------------------------------------
const lastFailure = (attempts) => {
    for (let i = attempts.length - 1; i >= 0; i -= 1) {
        if (attempts[i].category === 'measured-failure' || attempts[i].category === 'diagnostic') return attempts[i];
    }
    return null;
};
const anyPositiveReach = (attempts) => attempts.some((a) => a.httpAnswered === true || a.ndiPortOpen === true);

// Four measured OFFLINE reports whose reason code names tested unreachability,
// with no positive reachability anywhere in the run. Anything softer than this
// is the false alarm that paged four production hosts.
function fourOffline(attempts) {
    if (attempts.length !== ATTEMPTS) return false;
    return attempts.every((a) => a.category === 'measured-failure' && a.health === 'OFFLINE'
        && a.reasonCode === 'no-frames-unreachable' && a.ndiPortOpen === false && a.httpAnswered === false);
}

function fieldActionable(result, doc) {
    return result.outcome === 'persistent' && fourOffline(result.attempts)
        && !anyPositiveReach(result.attempts) && doc.mode === 'live' && doc.outputActive === true;
}

const reach = (v) => (v === true ? 'yes' : v === false ? 'no' : null);

function evidenceOf(result, doc, streak) {
    const a = lastFailure(result.attempts) || {};
    const ep = reusableEndpoint(a);
    return {
        attemptsCompleted: result.attempts.length,
        attemptsFailed: result.attempts.filter((x) => x.category !== 'healthy' && x.category !== 'ignored').length,
        mode: doc ? doc.mode : 'unknown',
        outputActive: doc ? doc.outputActive : null,
        endpoint: ep ? ep.endpoint : null,
        health: a.health || null,
        frames: a.frames === undefined ? null : a.frames,
        tcp: reach(a.ndiPortOpen),
        http: reach(a.httpAnswered),
        measuredFps: a.measuredFps === undefined ? null : a.measuredFps,
        stderrExcerpt: a.stderrExcerpt || '',
        recoveryAttempt: result.recoveryAttempt || null,
        streakDays: streak,
        priorReasonCode: null
    };
}

function resultReasonCode(result) {
    const a = lastFailure(result.attempts);
    if (a) return a.reasonCode;
    if (result.outcome === 'incomplete') return 'run-incomplete';
    if (result.outcome === 'ignored') return 'probe-ignored-target';
    return 'frames-flowing';
}

// --- State -------------------------------------------------------------------
const cameraKeyOf = (name) => crypto.createHash('sha256').update(name).digest('hex');

const blankCamera = (name) => ({ name: name, lastObservedDate: null, days: [], incident: null });
const emptyState = () => ({ schemaVersion: SCHEMA_VERSION, lastRunDate: null, cursor: null, cameras: {}, checker: {} });

const isHexKey = (v) => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
const EVENT_TYPES = new Set(['open', 'escalated', 'recovered']);
const SEVERITIES = new Set(['warning', 'error', 'info']);
const INCIDENT_KINDS = new Set(['intermittent', 'persistent', 'probe-error', 'checker']);

const isEpochSeconds = (v) => Number.isInteger(v) && v >= 0 && v <= 4102444800;
const isUuid = (v) => typeof v === 'string'
    && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(v);

// An event key is derived, never free text: it must still name the incident and
// the exact event it was queued for, or an acknowledgement could be credited to
// a different event entirely.
function validEvent(entry, incidentId, field) {
    if (!entry || typeof entry !== 'object') return false;
    if (!EVENT_TYPES.has(entry.type) || !SEVERITIES.has(entry.severity)) return false;
    if (entry.key !== incidentId + ':' + entry.type + ':' + entry.severity) return false;
    if (field === 'pending') {
        return entry.lastAttemptEpoch === null || isEpochSeconds(entry.lastAttemptEpoch);
    }
    return isEpochSeconds(entry.at);
}

function validSlot(value, incidentId) {
    if (!value || typeof value !== 'object') return false;
    if (value.provider !== 'google_chat' && value.provider !== 'discord') return false;
    for (const field of ['pending', 'acked']) {
        if (!Object.prototype.hasOwnProperty.call(value, field)) return false;
        const entry = value[field];
        if (entry === null) continue;
        if (!validEvent(entry, incidentId, field)) return false;
    }
    return true;
}

function validIncident(value, providers) {
    if (value === null) return true;
    if (!value || typeof value !== 'object') return false;
    if (!isUuid(value.id)) return false;
    if (!INCIDENT_KINDS.has(value.kind)) return false;
    if (typeof value.reasonCode !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(value.reasonCode)) return false;
    if (!isDateKey(value.openedDate) || !isDateKey(value.lastFaultDate)) return false;
    if (!(value.closedDate === null || isDateKey(value.closedDate))) return false;
    if (value.lastFaultDate < value.openedDate) return false;
    if (value.closedDate !== null && value.closedDate < value.openedDate) return false;
    if (typeof value.fieldActionableSent !== 'boolean') return false;
    if (!value.destinations || typeof value.destinations !== 'object' || Array.isArray(value.destinations)) return false;
    for (const id of Object.keys(value.destinations)) {
        const slot = value.destinations[id];
        if (!validSlot(slot, value.id)) return false;
        // A slot must name the destination it was written for. An unknown id or
        // a provider that disagrees with the configuration means this history
        // belongs to a different destination set, not to this device's.
        if (providers !== null && providers.get(id) !== slot.provider) return false;
    }
    return true;
}

function validateState(doc, providers) {
    if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return 'the state file is not an object';
    if (doc.schemaVersion !== SCHEMA_VERSION) return 'the state file has schemaVersion ' + String(doc.schemaVersion);
    if (!(doc.lastRunDate === null || isDateKey(doc.lastRunDate))) return 'lastRunDate is unusable';
    if (!(doc.cursor === null || isHexKey(doc.cursor))) return 'cursor is unusable';
    if (!doc.cameras || typeof doc.cameras !== 'object' || Array.isArray(doc.cameras)) return 'the camera map is unusable';
    if (!doc.checker || typeof doc.checker !== 'object' || Array.isArray(doc.checker)) return 'the checker map is unusable';
    const cameraKeys = Object.keys(doc.cameras);
    if (cameraKeys.length > MAX_CAMERA_RECORDS) return 'the state file holds more than ' + MAX_CAMERA_RECORDS + ' cameras';
    for (const key of cameraKeys) {
        if (!isHexKey(key)) return 'a camera key is not a SHA-256 digest';
        const cam = doc.cameras[key];
        if (!cam || typeof cam !== 'object') return 'a camera record is unusable';
        if (validName(cam.name) === null || cameraKeyOf(cam.name) !== key) return 'a camera record does not match its key';
        if (!(cam.lastObservedDate === null || isDateKey(cam.lastObservedDate))) return 'a camera lastObservedDate is unusable';
        if (!Array.isArray(cam.days) || cam.days.length > DAY_HISTORY_LIMIT) return 'a camera day history is unusable';
        for (const day of cam.days) {
            if (!day || typeof day !== 'object' || !isDateKey(day.date) || typeof day.transient !== 'boolean') {
                return 'a camera day entry is unusable';
            }
        }
        if (!validIncident(cam.incident, providers)) return 'a camera incident is unusable';
    }
    const checkerKeys = Object.keys(doc.checker);
    if (checkerKeys.length > MAX_CHECKER_RECORDS) return 'the state file holds more than ' + MAX_CHECKER_RECORDS + ' checker records';
    for (const key of checkerKeys) {
        if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(key)) return 'a checker key is unusable';
        const entry = doc.checker[key];
        if (!entry || typeof entry !== 'object') return 'a checker record is unusable';
        if (!(entry.lastObservedDate === null || isDateKey(entry.lastObservedDate))) return 'a checker lastObservedDate is unusable';
        if (!validIncident(entry.incident, providers)) return 'a checker incident is unusable';
    }
    return null;
}

function loadState(providers) {
    let st;
    try {
        st = fs.lstatSync(STATE_PATH);
    } catch (e) {
        if (e && e.code === 'ENOENT') {
            try {
                fs.mkdirSync(path.dirname(STATE_PATH), { recursive: true, mode: 0o700 });
            } catch (mkdirError) {
                return { error: 'the state directory could not be created' };
            }
            return { state: emptyState() };
        }
        return { error: 'the state file could not be inspected' };
    }
    if (!st.isFile()) return { error: 'the state path is not a regular file' };
    if (st.size > STATE_MAX_BYTES) return { error: 'the state file is larger than ' + STATE_MAX_BYTES + ' bytes' };
    let text;
    try {
        text = fs.readFileSync(STATE_PATH, 'utf8');
    } catch (e) {
        return { error: 'the state file could not be read' };
    }
    let doc;
    try {
        doc = JSON.parse(text);
    } catch (e) {
        return { error: 'the state file is not valid JSON' };
    }
    const problem = validateState(doc, providers);
    if (problem) return { error: problem };
    return { state: doc };
}

// Evict only unassigned records that owe nothing, oldest first. Active
// supervision is never evicted to meet a bound.
function enforceBounds(state, assignedKeys) {
    const owing = (incident) => incident !== null
        && Object.keys(incident.destinations).some((id) => incident.destinations[id].pending !== null);
    for (const [map, limit, isAssigned] of [
        [state.cameras, MAX_CAMERA_RECORDS, (key) => assignedKeys === null || assignedKeys.has(key)],
        [state.checker, MAX_CHECKER_RECORDS, () => false]
    ]) {
        let keys = Object.keys(map);
        if (keys.length <= limit) continue;
        const evictable = keys
            .filter((key) => !isAssigned(key) && !owing(map[key].incident))
            .sort((a, b) => String(map[a].lastObservedDate || '').localeCompare(String(map[b].lastObservedDate || '')));
        for (const key of evictable) {
            if (Object.keys(map).length <= limit) break;
            delete map[key];
        }
        if (Object.keys(map).length > limit) return 'state bounds cannot be met without evicting supervised records';
    }
    return null;
}

function saveState(state, assignedKeys) {
    const problem = enforceBounds(state, assignedKeys);
    if (problem) {
        log('state not saved: ' + problem);
        return false;
    }
    const body = JSON.stringify(state);
    if (Buffer.byteLength(body) > STATE_MAX_BYTES) {
        log('state not saved: the document exceeds ' + STATE_MAX_BYTES + ' bytes');
        return false;
    }
    const tmp = path.join(path.dirname(STATE_PATH),
        '.' + path.basename(STATE_PATH) + '.' + crypto.randomBytes(8).toString('hex') + '.tmp');
    let fd;
    try {
        fs.mkdirSync(path.dirname(STATE_PATH), { recursive: true, mode: 0o700 });
        fd = fs.openSync(tmp, 'wx', 0o600);
        fs.writeSync(fd, body);
        fs.fsyncSync(fd);
        fs.closeSync(fd);
        fd = undefined;
        fs.renameSync(tmp, STATE_PATH);
        return true;
    } catch (e) {
        if (fd !== undefined) { try { fs.closeSync(fd); } catch (closeError) { /* ignore */ } }
        try { fs.unlinkSync(tmp); } catch (unlinkError) { /* ignore */ }
        log('state not saved: ' + oneLine((e && e.message) || 'unknown write failure', 200));
        return false;
    }
}

// --- Transitions -------------------------------------------------------------
const emptySlot = (provider) => ({ provider: provider, pending: null, acked: null });

function enqueue(queue, incident, destination, want, subject, key, name, kind, fa, evidence) {
    const eventKey = incident.id + ':' + want.type + ':' + want.severity;
    const slot = incident.destinations[destination.id] || emptySlot(destination.provider);
    const last = (slot.pending && slot.pending.key === eventKey) ? slot.pending.lastAttemptEpoch : null;
    slot.provider = destination.provider;
    slot.pending = { key: eventKey, type: want.type, severity: want.severity, lastAttemptEpoch: last };
    incident.destinations[destination.id] = slot;
    queue.push({
        destinationId: destination.id,
        provider: destination.provider,
        subject: subject,
        key: key,
        name: name,
        incident: incident,
        eventKey: eventKey,
        type: want.type,
        severity: want.severity,
        kind: kind,
        fieldActionable: fa,
        evidence: evidence
    });
}

// Discord is reserved for work an operator can actually do, so only a freshly
// confirmed field-actionable persistent fault is eligible. Google Chat carries
// every confirmed fault, once per incident and destination.
function faultEnqueue(queue, destinations, incident, prior, fresh, kind, severity, fa, subject, key, name, evidence) {
    for (const destination of destinations) {
        const slot = incident.destinations[destination.id] || emptySlot(destination.provider);
        // What this destination has already been told, and what it still owes.
        const announced = (slot.acked !== null && slot.acked.type !== 'recovered') ? slot.acked : null;
        const held = (slot.pending !== null && slot.pending.type !== 'recovered') ? slot.pending : null;
        let want = null;
        if (destination.provider === 'discord') {
            if (!fa || kind === 'intermittent' || kind === 'checker') want = null;
            else if (fresh) want = { type: 'open', severity: 'error' };
            // An undelivered page keeps its own key so its retry floor still
            // applies: the condition has not changed, only the attempt count.
            else if (held !== null) want = { type: held.type, severity: held.severity };
            // A page that was never actually delivered stays eligible.
            else if (!incident.fieldActionableSent) want = { type: 'escalated', severity: 'error' };
            else if (announced === null) want = { type: 'open', severity: 'error' };
        } else if (fresh) {
            want = { type: 'open', severity: severity };
        } else if (prior !== null && prior.kind === 'intermittent' && kind !== 'intermittent') {
            want = { type: 'escalated', severity: severity };
        } else if (severity === 'error'
            && ((announced !== null && announced.severity !== 'error')
                || (held !== null && held.severity !== 'error'))) {
            // One escalation per destination when a warning becomes actionable.
            want = { type: 'escalated', severity: 'error' };
        } else if (held === null && announced === null) {
            // The previous event was withdrawn; this run confirmed it again.
            want = { type: 'open', severity: severity };
        } else if (held !== null) {
            want = { type: held.type, severity: held.severity };
        }
        if (want) enqueue(queue, incident, destination, want, subject, key, name, kind, fa, evidence);
    }
}

// Recovery is Google Chat only, and only to a destination that actually
// announced the fault. An incident nobody ever heard about produces no recovery.
function recoveryEnqueue(queue, destinations, incident, subject, key, name, evidence) {
    for (const destination of destinations) {
        if (destination.provider !== 'google_chat') continue;
        const slot = incident.destinations[destination.id] || emptySlot(destination.provider);
        let want = null;
        if (slot.acked !== null && slot.acked.type !== 'recovered') want = { type: 'recovered', severity: 'info' };
        else if (slot.pending !== null && slot.pending.type === 'recovered') want = { type: 'recovered', severity: slot.pending.severity };
        if (want) enqueue(queue, incident, destination, want, subject, key, name, 'recovered', false, evidence);
    }
}

function cancelFaults(incident, why, name) {
    if (!incident) return;
    for (const id of Object.keys(incident.destinations)) {
        const slot = incident.destinations[id];
        if (slot.pending !== null && slot.pending.type !== 'recovered') {
            log('withdrawn event=' + slot.pending.key + ' dest=' + id + ' reason=' + why
                + (name ? ' camera=' + oneLine(name, 120) : ''));
            slot.pending = null;
        }
    }
}

function newIncident(kind, reasonCode, today) {
    return {
        id: crypto.randomUUID(),
        kind: kind,
        reasonCode: reasonCode,
        openedDate: today,
        lastFaultDate: today,
        closedDate: null,
        fieldActionableSent: false,
        destinations: {}
    };
}

function collapseIncident(record, today) {
    const incident = record.incident;
    if (!incident || incident.closedDate === null) return;
    const pending = Object.keys(incident.destinations).some((id) => incident.destinations[id].pending !== null);
    if (!pending) {
        record.incident = null;
        return;
    }
    if (incident.closedDate < previousLocalDate(today, TOMBSTONE_DAYS)) {
        log('tombstone expired incident=' + incident.id + ' closed=' + incident.closedDate);
        record.incident = null;
    }
}

// One camera's day history, incident and queued events for this run.
function applyObservation(state, observation, today, destinations, queue) {
    const key = observation.cameraKey;
    const record = state.cameras[key] || blankCamera(observation.name);
    state.cameras[key] = record;
    record.name = observation.name;
    const outcome = observation.result.outcome;

    if (outcome === 'healthy') recordDayFlag(record, today, false);
    else if (outcome === 'intermittent') recordDayFlag(record, today, true);
    else if (outcome === 'persistent' || outcome === 'probe-error') recordDayFlag(record, today, false);
    if (outcome !== 'incomplete') record.lastObservedDate = today;

    const streak = intermittentStreak(record.days, today);
    const fa = observation.fieldActionable;
    const severity = fa ? 'error' : 'warning';
    const reasonCode = observation.reasonCode;
    const evidence = observation.evidence;
    evidence.streakDays = streak;

    let kind = null;
    if (outcome === 'persistent') kind = 'persistent';
    else if (outcome === 'probe-error') kind = 'probe-error';
    else if (outcome === 'intermittent' && streak >= INTERMITTENT_THRESHOLD) kind = 'intermittent';

    const prior = record.incident;
    const endedHealthy = outcome === 'healthy' || outcome === 'intermittent';
    // A run ending on a healthy attempt recovers a persistent or probe-error
    // incident. An intermittent incident needs a clean LATER date, because the
    // failures that opened it happen on days that also end healthy.
    const recovering = prior !== null && prior.closedDate === null && endedHealthy
        && (prior.kind === 'intermittent'
            ? (outcome === 'healthy' && prior.lastFaultDate !== today)
            : true);

    if (recovering) {
        cancelFaults(prior, 'recovery', record.name);
        prior.closedDate = today;
        evidence.priorReasonCode = prior.reasonCode;
        recoveryEnqueue(queue, destinations, prior, 'camera', key, record.name, evidence);
        log('transition camera=' + oneLine(record.name, 120) + ' recovered incident=' + prior.id);
    } else if (kind !== null) {
        const fresh = prior === null || prior.closedDate !== null;
        // Snapshot the pre-promotion kind: the promotion below overwrites it.
        const priorSnapshot = fresh ? null : { kind: prior.kind };
        let incident;
        if (fresh) {
            incident = newIncident(kind, reasonCode, today);
        } else {
            incident = prior;
            incident.kind = kind;
            incident.lastFaultDate = today;
            incident.reasonCode = reasonCode;
        }
        record.incident = incident;
        faultEnqueue(queue, destinations, incident, priorSnapshot, fresh, kind, severity,
            fa, 'camera', key, record.name, evidence);
        log('transition camera=' + oneLine(record.name, 120) + ' ' + (fresh ? 'opened' : 'retained')
            + ' kind=' + kind + ' incident=' + incident.id + ' streak=' + streak);
    } else if (prior !== null && prior.closedDate !== null && endedHealthy) {
        evidence.priorReasonCode = prior.reasonCode;
        recoveryEnqueue(queue, destinations, prior, 'camera', key, record.name, evidence);
    } else {
        // incomplete, ignored and a sub-threshold transient date prove nothing.
        // The incident and every pending event stay exactly as they were: an
        // absent observation is not a recovery.
        log('transition camera=' + oneLine(record.name, 120) + ' held outcome=' + outcome + ' streak=' + streak);
    }
    collapseIncident(record, today);
}

function applyChecker(state, code, failing, today, destinations, queue, evidence) {
    if (!failing && !state.checker[code]) return;
    const record = state.checker[code] || { lastObservedDate: null, incident: null };
    state.checker[code] = record;
    record.lastObservedDate = today;
    const prior = record.incident;
    if (failing) {
        const fresh = prior === null || prior.closedDate !== null;
        const priorSnapshot = fresh ? null : { kind: prior.kind };
        let incident;
        if (fresh) {
            incident = newIncident('checker', code, today);
        } else {
            incident = prior;
            incident.lastFaultDate = today;
        }
        record.incident = incident;
        faultEnqueue(queue, destinations, incident, priorSnapshot, fresh, 'checker', 'warning',
            false, 'checker', code, code, evidence);
        log('transition checker=' + code + ' ' + (fresh ? 'opened' : 'retained') + ' incident=' + incident.id);
    } else if (prior !== null && prior.closedDate === null) {
        cancelFaults(prior, 'recovery', null);
        prior.closedDate = today;
        evidence.priorReasonCode = prior.reasonCode;
        recoveryEnqueue(queue, destinations, prior, 'checker', code, code, evidence);
        log('transition checker=' + code + ' recovered incident=' + prior.id);
    } else if (prior !== null && prior.closedDate !== null) {
        evidence.priorReasonCode = prior.reasonCode;
        recoveryEnqueue(queue, destinations, prior, 'checker', code, code, evidence);
    }
    collapseIncident(record, today);
}

// --- Messages ----------------------------------------------------------------
const LOG_LOCATION = () => 'evobox@' + SHORT_HOST + '.' + TAILNET + ':' + LOG_PATH;

function headerFor(severity) {
    return TITLE + '\nSeverity: ' + severity.toUpperCase() + '\nHost: ' + SHORT_HOST
        + '\nTime: ' + new Date().toISOString().replace(/\.\d{3}Z$/, 'Z') + '\n';
}

function chatEntry(event) {
    const ev = event.evidence;
    const lines = [];
    const subject = event.subject === 'checker'
        ? 'checker ' + event.name
        : 'camera ' + display(event.name, 200);
    lines.push('[' + event.severity.toUpperCase() + '] ' + subject);
    if (event.type === 'recovered') {
        lines.push('  Camera checks recovered after ' + display(ev.priorReasonCode || 'a previous failure', 80) + '.');
        if (ev.recoveryAttempt) lines.push('  Recovered on attempt ' + ev.recoveryAttempt + '/' + ATTEMPTS + '.');
    } else if (event.kind === 'intermittent') {
        lines.push('  Checks failed before recovering on ' + ev.streakDays + ' consecutive days.'
            + (ev.recoveryAttempt ? ' Latest recovery: attempt ' + ev.recoveryAttempt + '/' + ATTEMPTS + '.' : ''));
    } else {
        lines.push('  Attempts: ' + ev.attemptsFailed + ' failed of ' + ev.attemptsCompleted + ' completed'
            + ' (of ' + ATTEMPTS + ' planned)');
    }
    lines.push('  Reason: ' + display(event.incident.reasonCode, 80));
    if (event.subject === 'camera') {
        lines.push('  Assignment source: ' + (ev.mode === 'saved'
            ? 'saved OBS configuration (OBS not running; live routing unknown)'
            : ev.mode === 'live'
                ? ('live OBS' + (ev.outputActive === true ? ', output active'
                    : ev.outputActive === false ? ', output inactive' : ', output unknown'))
                : 'unknown'));
        const bits = [];
        if (ev.endpoint) bits.push('endpoint=' + display(ev.endpoint, 64));
        if (ev.frames !== null) bits.push('frames=' + ev.frames);
        if (ev.tcp !== null) bits.push('tcp=' + ev.tcp);
        if (ev.http !== null) bits.push('http=' + ev.http);
        if (ev.health) bits.push('health=' + display(ev.health, 16));
        // FPS is only shown when it is what explains the verdict.
        if (event.incident.reasonCode === 'low-fps' && ev.measuredFps !== null) {
            bits.push('fps=' + Number(ev.measuredFps).toFixed(1));
        }
        if (bits.length > 0) lines.push('  Evidence: ' + bits.join(' '));
    }
    if (ev.stderrExcerpt) lines.push('  Tool output: ' + display(ev.stderrExcerpt, STDERR_EXCERPT_CHARS));
    lines.push('  Log: ' + LOG_LOCATION());
    return lines.join('\n');
}

function discordEntry(event) {
    return [
        'Camera needs attention',
        'Host: ' + SHORT_HOST,
        'Camera: ' + display(event.name, 200),
        'All ' + ATTEMPTS + ' checks failed and this camera is in the live program scene with the output active.',
        'Action: check the live picture. If it is black or frozen, check the camera power and network cabling.'
            + ' If the picture looks normal, report this alert to engineering and do not restart equipment.'
    ].join('\n');
}

// Pack complete entries only, repeating the header. Field-actionable entries
// sort first so a truncated tail can never drop the operator-actionable one.
function packChunks(events, provider) {
    const limit = provider === 'discord' ? DISCORD_LIMIT : CHAT_LIMIT;
    const ordered = events.slice().sort((a, b) => {
        if (a.fieldActionable !== b.fieldActionable) return a.fieldActionable ? -1 : 1;
        return 0;
    });
    const chunks = [];
    let current = null;
    for (const event of ordered) {
        const severity = event.severity;
        const header = headerFor(severity);
        const body = provider === 'discord' ? discordEntry(event) : chatEntry(event);
        const entry = body;
        if (header.length + entry.length > limit) {
            log('event not deliverable: entry exceeds the ' + provider + ' limit key=' + event.eventKey);
            continue;
        }
        if (current && current.severity === severity
            && current.text.length + 1 + entry.length <= limit) {
            current.text += '\n' + entry;
            current.events.push(event);
            continue;
        }
        current = { severity: severity, header: header, text: header + entry, events: [event] };
        chunks.push(current);
    }
    return chunks;
}

// --- Delivery ----------------------------------------------------------------
function postJson(url, payload) {
    return new Promise((resolve) => {
        let parsed;
        try {
            parsed = new URL(url);
        } catch (e) {
            resolve({ ok: false, why: 'unusable-url' });
            return;
        }
        const body = Buffer.from(JSON.stringify(payload), 'utf8');
        const client = parsed.protocol === 'https:' ? https : http;
        let settled = false;
        const done = (ok, why) => {
            if (settled) return;
            settled = true;
            ACTIVE_REQUESTS.delete(request);
            clearTimeout(connectTimer);
            clearTimeout(totalTimer);
            resolve({ ok: ok, why: why });
        };
        const request = client.request(parsed, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Content-Length': body.length }
        }, (response) => {
            const status = response.statusCode;
            response.resume();
            response.on('end', () => {
                if (status >= 200 && status < 300) done(true, 'status-' + status);
                else done(false, 'status-' + status);
            });
            response.on('error', () => done(false, 'response-error'));
        });
        ACTIVE_REQUESTS.add(request);
        // Two independent bounds. The connect timer runs from request creation
        // and covers name resolution and the TCP/TLS handshake, which is the
        // phase a dead venue uplink stalls in; `request.setTimeout` would only
        // arm socket inactivity once a socket exists, so it cannot bound a
        // hanging DNS lookup at all.
        const connectTimer = setTimeout(() => {
            request.destroy();
            done(false, 'connect-timeout');
        }, HTTP_CONNECT_MS);
        const totalTimer = setTimeout(() => {
            request.destroy();
            done(false, 'total-timeout');
        }, HTTP_TOTAL_MS);
        // For HTTPS the connect phase includes the TLS handshake, so the bound
        // is only released on `secureConnect`; releasing it on the plain TCP
        // `connect` would leave a stalled handshake covered by nothing but the
        // 10s total timer.
        const connectEvent = parsed.protocol === 'https:' ? 'secureConnect' : 'connect';
        request.on('socket', (socket) => {
            const connected = () => clearTimeout(connectTimer);
            if (connectEvent === 'connect' && !socket.connecting) connected();
            else socket.once(connectEvent, connected);
        });
        // Never surface an exception object: it can carry the URL.
        request.on('error', () => done(false, 'transport-error'));
        request.end(body);
    });
}

const payloadFor = (provider, text) => (provider === 'discord'
    ? { content: text, allowed_mentions: { parse: [] } }
    : { text: text });

// Deliver this run's queued events. Evidence and text are built from this
// invocation only, so a stale pending event is never sent with old evidence.
async function deliverPending(state, queue, destinations, assignedKeys, eligibility, nowEpoch) {
    let stop = false;
    for (const destination of destinations) {
        if (stop) break;
        const mine = queue.filter((event) => {
            if (event.destinationId !== destination.id) return false;
            const slot = event.incident.destinations[destination.id];
            if (!slot || slot.pending === null || slot.pending.key !== event.eventKey) return false;
            if (slot.pending.lastAttemptEpoch !== null
                && nowEpoch - slot.pending.lastAttemptEpoch < RETRY_FLOOR_MS / 1000) {
                log('delivery deferred key=' + event.eventKey + ' dest=' + destination.id + ' reason=retry-floor');
                return false;
            }
            const verdict = eligibility(event);
            if (!verdict.ok) {
                log('delivery suppressed key=' + event.eventKey + ' dest=' + destination.id + ' reason=' + verdict.why);
                return false;
            }
            return true;
        });
        if (mine.length === 0) continue;
        for (const chunk of packChunks(mine, destination.provider)) {
            if (stop) break;
            if (remainingMs() < DELIVERY_STEP_MS) {
                log('delivery stopped: the remaining budget cannot complete a POST; '
                    + chunk.events.length + ' event(s) stay pending');
                stop = true;
                break;
            }
            for (const event of chunk.events) {
                event.incident.destinations[destination.id].pending.lastAttemptEpoch = nowEpoch;
            }
            if (!saveState(state, assignedKeys)) {
                log('delivery stopped: the attempt could not be persisted');
                return;
            }
            const result = await postJson(destination.url, payloadFor(destination.provider, chunk.text));
            if (!result.ok) {
                log('delivery failed dest=' + destination.id + ' events=' + chunk.events.length
                    + ' reason=' + result.why + ' (stays pending)');
                continue;
            }
            for (const event of chunk.events) {
                const slot = event.incident.destinations[destination.id];
                slot.acked = { key: event.eventKey, type: event.type, severity: event.severity, at: nowEpoch };
                slot.pending = null;
                if (destination.provider === 'discord' && event.fieldActionable) {
                    event.incident.fieldActionableSent = true;
                }
                log('delivered dest=' + destination.id + ' key=' + event.eventKey + ' type=' + event.type);
            }
            if (!saveState(state, assignedKeys)) {
                log('delivery stopped: an acknowledgement could not be persisted'
                    + ' (at-least-once: this chunk may be re-sent)');
                return;
            }
        }
    }
}

// --- Orchestration -----------------------------------------------------------
function probePresent() {
    try {
        fs.accessSync(PROBE_BIN, fs.constants.X_OK);
        const st = fs.statSync(PROBE_BIN);
        return st.isFile();
    } catch (e) {
        return false;
    }
}

// Retry a prerequisite on the same bounded jitter schedule. Success cancels the
// remaining retries and permits the normal check inside the remaining budget.
async function retryPrerequisite(label, attempt) {
    let last = await attempt();
    let i = 1;
    while (!last.ok && i < ATTEMPTS) {
        const jitter = jitterSeconds(JITTER_RANGES[i]);
        if (remainingMs() - DELIVERY_RESERVE_MS < jitter * 1000 + CTX_DEADLINE_MS) {
            log('prerequisite ' + label + ' retry stopped: insufficient budget');
            break;
        }
        log('prerequisite ' + label + ' retry=' + (i + 1) + '/' + ATTEMPTS + ' jitter=' + jitter + 's');
        await sleep(jitter * 1000);
        last = await attempt();
        i += 1;
    }
    return last;
}

function blankEvidence(mode) {
    return {
        attemptsCompleted: 0, attemptsFailed: 0, mode: mode, outputActive: null, endpoint: null,
        health: null, frames: null, tcp: null, http: null, measuredFps: null, stderrExcerpt: '',
        recoveryAttempt: null, streakDays: 0, priorReasonCode: null
    };
}

// Cameras are visited from the persisted cursor so repeated budget exhaustion
// cannot permanently exclude the later half of a venue.
function rotateOrder(cameras, cursor) {
    const ordered = cameras.slice();
    if (!cursor) return ordered;
    const at = ordered.findIndex((camera) => camera.key === cursor);
    if (at <= 0) return ordered;
    return ordered.slice(at).concat(ordered.slice(0, at));
}

async function main() {
    log('run start host=' + SHORT_HOST + ' budget=' + TOTAL_BUDGET_MS + 'ms');
    const config = readDestinations();
    const destinations = config.ok ? config.destinations : [];
    if (!config.ok) log('configuration invalid: ' + config.reason + ' (delivery suppressed)');
    // An unusable configuration suppresses delivery, but it is not evidence
    // that the state file is wrong: validating slots against an empty id set
    // would condemn a perfectly good history and skip the measurement too.
    const destinationProviders = config.ok
        ? new Map(destinations.map((d) => [d.id, d.provider]))
        : null;

    const loaded = loadState(destinationProviders);
    if (loaded.error) {
        log('state unusable: ' + loaded.error + ' — the existing file is preserved and nothing is sent.'
            + ' Inspect ' + STATE_PATH + ' on the device.');
        return;
    }
    const state = loaded.state;
    const today = localDateKey(new Date());
    const nowEpoch = Math.floor(Date.now() / 1000);
    if (state.lastRunDate !== null && today < state.lastRunDate) {
        log('clock anomaly: local date ' + today + ' precedes the recorded ' + state.lastRunDate
            + ' — history is frozen and nothing is sent until the clock catches up');
        return;
    }

    const queue = [];
    const canSend = destinations.length > 0;

    const probe = await retryPrerequisite('probe', async () => ({ ok: probePresent() }));
    if (!probe.ok) {
        log('prerequisite probe-missing: ' + PROBE_BIN + ' is not an executable file');
        if (canSend) {
            applyChecker(state, 'probe-missing', true, today, destinations, queue, blankEvidence('unknown'));
            state.lastRunDate = today;
            // The assignment is unknown on this path, so no record is evictable.
            await deliverPending(state, queue, destinations, null, () => ({ ok: true }), nowEpoch);
            saveState(state, null);
        }
        log('run done outcome=probe-missing');
        return;
    }

    const context = await retryPrerequisite('context', readAssignment);
    if (!context.ok) {
        const code = checkerCodeFor(context.code);
        log('prerequisite ' + code + ': ' + oneLine(context.reason, 200));
        if (canSend) {
            applyChecker(state, code, true, today, destinations, queue, blankEvidence('unknown'));
            state.lastRunDate = today;
            await deliverPending(state, queue, destinations, null, () => ({ ok: true }), nowEpoch);
            saveState(state, null);
        }
        log('run done outcome=' + code);
        return;
    }

    const doc = context.doc;
    const fingerprint = doc.fingerprint;
    log('context mode=' + doc.mode + ' scene=' + oneLine(doc.scene, 120)
        + ' cameras=' + doc.cameras.length + ' ignored=' + doc.ignoredInputs.length
        + ' outputActive=' + String(doc.outputActive) + ' fingerprint=' + fingerprint.slice(0, 12));
    for (const ignored of doc.ignoredInputs) {
        log('ignored input=' + oneLine(ignored.inputName, 120) + ' name=' + oneLine(ignored.name, 120)
            + ' reason=not-an-allowlisted-camera');
    }
    // A prerequisite recovers only after that exact prerequisite succeeded.
    applyChecker(state, 'probe-missing', false, today, destinations, queue, blankEvidence(doc.mode));
    for (const code of ['obs-client-missing', 'obs-context-unavailable', 'context-invalid']) {
        applyChecker(state, code, false, today, destinations, queue, blankEvidence(doc.mode));
    }

    const assigned = doc.cameras.map((camera) => ({ key: cameraKeyOf(camera.name), name: camera.name }));
    const assignedKeys = new Set(assigned.map((camera) => camera.key));

    // A camera absent from a complete assignment retires without a recovery
    // notice; its bounded day history stays for the streak window.
    for (const key of Object.keys(state.cameras)) {
        if (assignedKeys.has(key)) continue;
        const record = state.cameras[key];
        if (record.incident) {
            cancelFaults(record.incident, 'unassigned', record.name);
            if (record.incident.closedDate === null) record.incident.closedDate = today;
            collapseIncident(record, today);
            log('retired camera=' + oneLine(record.name, 120) + ' reason=not-assigned');
        }
    }

    let probed = 0;
    let incomplete = 0;
    let ignoredCameras = 0;
    let lastIndex = -1;
    const order = rotateOrder(assigned, state.cursor);
    for (let i = 0; i < order.length; i += 1) {
        const camera = order[i];
        const result = await checkCamera(camera.name, fingerprint);
        lastIndex = i;
        if (result.outcome === 'incomplete') {
            incomplete += 1;
            if (result.attempts.length === 0) {
                // Nothing was measured, so leave the cursor on this camera.
                lastIndex = i - 1;
                log('stop: the remaining budget cannot complete another camera');
                break;
            }
        }
        if (result.outcome === 'ignored') ignoredCameras += 1;
        if (result.outcome !== 'incomplete' && result.outcome !== 'ignored') probed += 1;
        const fa = fieldActionable(result, doc);
        applyObservation(state, {
            cameraKey: camera.key,
            name: camera.name,
            result: result,
            reasonCode: resultReasonCode(result),
            fieldActionable: fa,
            // applyObservation recomputes streakDays once the day flag is in.
            evidence: evidenceOf(result, doc, 0)
        }, today, destinations, queue);
    }
    state.cursor = order.length > 0
        ? order[(lastIndex + 1 + order.length) % order.length].key
        : null;
    state.lastRunDate = today;

    // Freshly confirm the assignment once before any fault leaves the box. A
    // changed or unavailable context suppresses stale pending faults.
    let finalDoc = null;
    if (queue.length > 0 && remainingMs() > CTX_DEADLINE_MS) {
        const confirm = await readAssignment();
        if (confirm.ok && confirm.doc.fingerprint === fingerprint) finalDoc = confirm.doc;
        else log('delivery gate: the assignment could not be re-confirmed before sending');
    }

    const eligibility = (event) => {
        if (event.subject === 'checker') return { ok: true };
        if (!finalDoc) return { ok: false, why: 'assignment-unconfirmed' };
        if (!finalDoc.cameras.some((camera) => camera.name === event.name)) {
            return { ok: false, why: 'camera-no-longer-assigned' };
        }
        if (event.provider === 'discord') {
            if (!event.fieldActionable) return { ok: false, why: 'not-field-actionable' };
            if (finalDoc.mode !== 'live') return { ok: false, why: 'saved-mode' };
            if (finalDoc.outputActive !== true) return { ok: false, why: 'output-not-active' };
        }
        return { ok: true };
    };

    if (!saveState(state, assignedKeys)) {
        log('run done outcome=state-write-failed (nothing sent)');
        return;
    }
    if (canSend && queue.length > 0) {
        await deliverPending(state, queue, destinations, assignedKeys, eligibility, nowEpoch);
    } else if (queue.length === 0) {
        log('no deliverable events this run');
    }
    log('run done assigned=' + assigned.length + ' probed=' + probed + ' incomplete=' + incomplete
        + ' ignored=' + ignoredCameras + ' events=' + queue.length + ' elapsed=' + elapsedMs() + 'ms');
}

// The shell backstop is `timeout -k 5 905`, so this process can be signalled
// while a probe child or a POST is in flight. Without this, a TERM would leave
// the GNU `timeout` wrapper and its probe orphaned, still pulling from a camera
// after the run that asked for it is gone.
let shuttingDown = false;
function shutdown(signal) {
    if (shuttingDown) return;
    shuttingDown = true;
    log('shutdown on ' + signal + ': cancelling ' + ACTIVE_CHILDREN.size + ' probe child(ren) and '
        + ACTIVE_REQUESTS.size + ' request(s)');
    for (const request of ACTIVE_REQUESTS) {
        try { request.destroy(); } catch (e) { /* already gone */ }
    }
    const children = Array.from(ACTIVE_CHILDREN);
    for (const child of children) {
        try { child.kill('SIGTERM'); } catch (e) { /* already gone */ }
    }
    if (children.length === 0) {
        process.exit(0);
        return;
    }
    // Bounded escalation: a child that ignores TERM must not outlive this
    // process, and the shell backstop only allows 5s before its own SIGKILL.
    setTimeout(() => {
        for (const child of children) {
            try { child.kill('SIGKILL'); } catch (e) { /* already gone */ }
        }
        process.exit(0);
    }, 2000);
}
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGHUP', () => shutdown('SIGHUP'));

process.on('unhandledRejection', (e) => {
    log('unhandled rejection: ' + oneLine((e && e.message) || 'unknown', 200));
    process.exit(0);
});
process.on('uncaughtException', (e) => {
    log('uncaught exception: ' + oneLine((e && e.message) || 'unknown', 200));
    process.exit(0);
});

main().then(() => process.exit(0), (e) => {
    log('run aborted: ' + oneLine((e && e.message) || 'unknown', 200));
    process.exit(0);
});
ZWP_CHECK_PROGRAM
rc=$?
if [ "$rc" -ne 0 ]; then
    log "abnormal completion: the check exited $rc"
fi
exit 0
ZWP_WRAPPER_TAIL
    content="$(cat "$tmp")"
    rm -f "$tmp"
    local rc=0
    _zwp_install_check_wrapper "$content" || rc=$?
    # rc: 0=installed, 1=already current, 2=error. Stamp fresh unless it
    # errored, so a transient failure retries next tick instead of waiting the
    # full TTL.
    [ "$rc" -ne 2 ] && fresh_mark "zowie_probe_wrapper"
    return 0
}

# Installs /usr/local/bin/evo-daemon-run.sh — the wrapper that sources nvm
# and execs node. Exits 69 if the daemon's index.js is missing so systemd
# enters failed state and the next cron tick re-downloads via
# check_and_update_daemon_version. Exits 78 on an evo.json the daemon would
# answer by registering a new deviceId (#67); the next tick's
# reconcile_daemon_identities restores it. The check is read-only and fails
# open: if jq cannot evaluate the identity filter the daemon starts as before.
install_daemon_runner_script() {
    local runtime_version content identity_dir_q identity_jq_q
    runtime_version="$(node_runtime_version)"
    identity_dir_q="$(printf '%q' "$EVO_IDENTITY_DIR")"
    identity_jq_q="$(printf '%q' "$EVO_IDENTITY_JQ")"
    content='#!/bin/bash
# evo-daemon-run.sh — systemd-invoked launcher for evo-obs-daemon.
# Arg1: "main" or "second"
set -e

export NVM_DIR="${NVM_DIR:-/home/evobox/.config/nvm}"
# shellcheck disable=SC1090
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
# The pinned versions are spliced in from the constants in the install script, so
# the runner, the unit files and install_nvm() can never name different runtimes.
# Fallback order: pinned version, then the previous runtime (still on disk until
# a later release removes it), then whatever nvm.sh already activated from the
# `default` alias. A device whose Node install failed keeps a working daemon.
nvm use "${NODE_VERSION:-'"$runtime_version"'}" >/dev/null 2>&1 \
  || nvm use "'"$NODE_FALLBACK_VERSION"'" >/dev/null 2>&1 \
  || true

case "$1" in
  main)   DAEMON_DIR=/home/evobox/evosports/evo-obs-daemon-main ;;
  second) DAEMON_DIR=/home/evobox/evosports/evo-daemon-second ;;
  *) echo "usage: $0 {main|second}" >&2; exit 64 ;;
esac

if [ ! -f "$DAEMON_DIR/index.js" ]; then
  echo "evo-daemon-run: index.js missing at $DAEMON_DIR — exiting for re-download" >&2
  exit 69
fi

# Device identity (#67). Without a usable evo.json the daemon registers a new
# deviceId, and the table stays assigned to the old one. Refuse to start when
# that would lose a known id; with no evo.json and no saved copy this is a first
# install, so the daemon registers as before. Every jq call sits in a condition
# because this script is set -e.
export EVO_DAEMON_ROLE="$1"
IDENTITY_DIR='"$identity_dir_q"'
IDENTITY_JQ='"$identity_jq_q"'
id_ok() { [ -s "$1" ] && jq -se "length == 1 and (.[0] | $IDENTITY_JQ)" "$1" >/dev/null 2>&1; }
id_of() { jq -sr ".[0].deviceId" "$1" 2>/dev/null || true; }
if printf "{\"deviceId\":\"evo-1\"}" | jq -se "length == 1 and (.[0] | $IDENTITY_JQ)" >/dev/null 2>&1; then
  live="$DAEMON_DIR/evo.json"
  backup="$IDENTITY_DIR/$1.json"
  if [ -e "$live" ] || [ -L "$live" ]; then
    if ! id_ok "$live"; then
      echo "evo-daemon-run: $live is empty or invalid — not starting, so no new deviceId is registered; the next install tick restores it" >&2
      exit 78
    fi
    if [ "$1" = second ]; then
      main_live=/home/evobox/evosports/evo-obs-daemon-main/evo.json
      if id_ok "$main_live" && [ "$(id_of "$live")" = "$(id_of "$main_live")" ]; then
        echo "evo-daemon-run: second evo.json holds main'"'"'s deviceId $(id_of "$live") — not starting; the next install tick restores it" >&2
        exit 78
      fi
    fi
  elif id_ok "$backup"; then
    echo "evo-daemon-run: $live is missing while $backup holds $(id_of "$backup") — not starting; the next install tick restores it" >&2
    exit 78
  fi
fi

cd "$DAEMON_DIR"
exec node index.js
'
    write_if_sha_changed "$DAEMON_RUNNER_PATH" "$content" 0755
    return 0
}

# Installs /usr/local/bin/evo-daemon-alert.sh — ExecStopPost hook for
# daemon units. Skips clean exits (SERVICE_RESULT=success), rate-limits
# to one webhook per unit per 600s via /tmp state file.
install_daemon_alert_script() {
    # Bake the webhook destinations into the alert script so it runs standalone
    # under systemd without sourcing the install script.
    local destinations_literal content_head content_tail content
    destinations_literal=$(render_shell_array_entries "${DAEMON_ALERT_WEBHOOK_DESTINATIONS[@]}")

    content_head='#!/bin/bash
# evo-daemon-alert.sh - called by systemd ExecStopPost on each daemon exit.
# Args: %n SERVICE_RESULT EXIT_CODE EXIT_STATUS
set +e

WEBHOOK_DESTINATIONS=('

    content_tail=')

get_primary_ip() {
  local ip
  ip=$(hostname -I 2>/dev/null | awk "{print \$1}")
  [ -z "$ip" ] && ip="unknown-ip"
  printf "%s" "$ip"
}

format_webhook_text() {
  local title="$1"
  local severity="$2"
  local message="$3"
  local host ip now
  host=$(hostname 2>/dev/null || echo "unknown-host")
  ip=$(get_primary_ip)
  now=$(date -u "+%Y-%m-%dT%H:%M:%SZ")

  printf "%s\nSeverity: %s\nHost: %s\nIP: %s\nTime: %s\n\n%s" \
    "$title" "$severity" "$host" "$ip" "$now" "$message"
}

truncate_discord_content() {
  local content="$1"
  local max_len=1900
  if command -v jq >/dev/null 2>&1; then
    jq -njr --arg content "$content" "\$content | if length <= 1900 then . else .[:1887] + \"\\n\\n[truncated]\" end"
    return $?
  fi
  if [ "${#content}" -le "$max_len" ]; then
    printf "%s" "$content"
    return 0
  fi

  printf "%s\n\n[truncated]" "${content:0:$((max_len - 13))}"
}

build_webhook_payload() {
  local provider="$1"
  local text="$2"
  local safe

  case "$provider" in
    google_chat)
      if command -v jq >/dev/null 2>&1; then
        jq -nc --arg text "$text" "{text: \$text}"
      else
        safe=$(printf "%s" "$text" | tr "\n" " " | sed "s/\\\\/\\\\\\\\/g; s/\"/\\\\\"/g")
        printf "{\"text\":\"%s\"}" "$safe"
      fi
      ;;
    discord)
      text=$(truncate_discord_content "$text"; printf ".")
      text="${text%.}"
      if command -v jq >/dev/null 2>&1; then
        jq -nc --arg content "$text" "{content: \$content}"
      else
        safe=$(printf "%s" "$text" | tr "\n" " " | sed "s/\\\\/\\\\\\\\/g; s/\"/\\\\\"/g")
        printf "{\"content\":\"%s\"}" "$safe"
      fi
      ;;
    *)
      return 64
      ;;
  esac
}

post_webhook_destination() {
  local destination="$1" title="$2" severity="$3" message="$4"
  local name provider url extra text payload escaped_url escaped_payload
  IFS="|" read -r name provider url extra <<< "$destination"
  [ -n "$name" ] && [ -n "$provider" ] && [ -n "$url" ] && [ -z "$extra" ] || return 64
  [[ "$name" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$ ]] || return 64
  case "$provider" in google_chat|discord) ;; *) return 64 ;; esac
  case "$url" in http://*|https://*) ;; *) return 64 ;; esac
  case "$url" in *[[:space:]]*|*\\*|*\"*|*@*|*#*) return 64 ;; esac
  text=$(format_webhook_text "$title" "$severity" "$message"; printf ".")
  text="${text%.}"
  payload=$(build_webhook_payload "$provider" "$text") || return $?
  escaped_url="$url"
  escaped_payload="${payload//\\/\\\\}"
  escaped_payload="${escaped_payload//\"/\\\"}"
  # URL and payload remain in curl config stdin, never argv, environment, stdout,
  # Curl returns the actual destination outcome.
  printf '"'"'url = "%s"\nrequest = "POST"\nheader = "Content-Type: application/json"\ndata = "%s"\nfail\nsilent\nconnect-timeout = 20\nmax-time = 30\nretry = 2\noutput = "/dev/null"\n'"'"' \
    "$escaped_url" "$escaped_payload" | curl --config -
}
post_webhook_destinations() {
  local title="$1" severity="$2" message="$3" status=0 destination
  shift 3
  for destination in "$@"; do
    post_webhook_destination "$destination" "$title" "$severity" "$message" || status=1
  done
  return "$status"
}
destination_names_json() {
  local destination name provider url extra names="" separator="" seen=","
  for destination in "${WEBHOOK_DESTINATIONS[@]}"; do
    IFS="|" read -r name provider url extra <<< "$destination"
    [ -n "$name" ] && [ -n "$provider" ] && [ -n "$url" ] && [ -z "$extra" ] || return 64
    [[ "$name" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$ ]] || return 64
    case "$seen" in *",$name,"*) return 64 ;; esac
    seen="${seen}${name},"
    names="${names}${separator}\"${name}\""
    separator=","
  done
  printf "[%s]" "$names"
}
find_destination() {
  local wanted="$1" destination name provider url extra
  for destination in "${WEBHOOK_DESTINATIONS[@]}"; do
    IFS="|" read -r name provider url extra <<< "$destination"
    [ "$name" = "$wanted" ] && { FOUND_DESTINATION="$destination"; return 0; }
  done
  return 64
}
json_stdin() {
  local request names_json selected title severity message destination status=0
  command -v jq >/dev/null 2>&1 || return 64
  names_json=$(destination_names_json) || return 64
  # Parse stdin before Bash can remove raw NUL bytes or alter JSON syntax.
  request=$(jq -ce -s --argjson allowed "$names_json" "
    . as \$documents |
    (if length != 1 then false else .[0] as \$v |
    (\$v | type == \"object\" and
      ([keys[] | select(. != \"schema_version\" and . != \"title\" and . != \"severity\" and . != \"message\" and . != \"destinations\")] | length == 0) and
      (has(\"schema_version\") and .schema_version == 1) and
      (has(\"title\") and (.title | type == \"string\" and utf8bytelength <= 120)) and
      (has(\"severity\") and (.severity == \"info\" or .severity == \"warning\" or .severity == \"critical\")) and
      (has(\"message\") and (.message | type == \"string\" and utf8bytelength <= 1600)) and
      (if has(\"destinations\") then
        (.destinations | type == \"array\" and length > 0 and length == (unique | length) and
          all(.[]; . as \$name | type == \"string\" and utf8bytelength <= 80 and (\$allowed | index(\$name) != null)))
       else true end))
    end) | if . then \$documents[0] else error(\"invalid notification request\") end
  ") || return 64
  title=$(jq -r ".title + \".\"" <<< "$request") || return 64
  title="${title%.}"
  severity=$(jq -r ".severity" <<< "$request") || return 64
  message=$(jq -r ".message + \".\"" <<< "$request") || return 64
  message="${message%.}"
  selected=$(jq -r ".destinations // empty | .[]" <<< "$request") || return 64
  [ -n "$selected" ] || selected=$(jq -r ".[]" <<< "$names_json") || return 64
  while IFS= read -r destination; do
    [ -n "$destination" ] || continue
    find_destination "$destination" || return 64
    if post_webhook_destination "$FOUND_DESTINATION" "$title" "$severity" "$message"; then
      printf "{\"schema_version\":1,\"destination\":\"%s\",\"status\":\"delivered\"}\\n" "$destination"
    else
      printf "{\"schema_version\":1,\"destination\":\"%s\",\"status\":\"failed\"}\\n" "$destination"
      status=1
    fi
  done <<< "$selected"
  return "$status"
}

if [ "${1:-}" = "--json-stdin" ]; then
  [ "$#" -eq 1 ] || exit 64
  json_stdin
  exit $?
fi
UNIT="${1:-unknown}"
RESULT="${2:-unknown}"
EXIT_CODE="${3:-?}"
EXIT_STATUS="${4:-?}"

# Clean stops (systemctl stop/restart initiated by update flow or nightly
# cron) are success — no alarm.
[ "$RESULT" = "success" ] && exit 0

# Rate-limit: 1 alert per unit per 600s
STATE="/tmp/.evo-alert-${UNIT}.last"
now=$(date +%s)
if [ -f "$STATE" ]; then
  last=$(cat "$STATE" 2>/dev/null || echo 0)
  [ $(( now - last )) -lt 600 ] && exit 0
fi
echo "$now" > "$STATE"

case "$UNIT" in
  *second*)
    EVO_JSON="/home/evobox/evosports/evo-daemon-second/evo.json"
    STDERR_LOG="/home/evobox/logs/daemon2_stderr.log"
    ;;
  *)
    EVO_JSON="/home/evobox/evosports/evo-obs-daemon-main/evo.json"
    STDERR_LOG="/home/evobox/logs/daemon_stderr.log"
    ;;
esac
device_id=$(jq -r .deviceId "$EVO_JSON" 2>/dev/null)
[ -z "$device_id" ] || [ "$device_id" = "null" ] && device_id="unknown"

# The stderr log is the most direct surface of the crash reason (Node.js
# stack traces go here). Grab the last ~1.5KB. Journalctl is the
# systemd-level supervisor view; include a short tail for context.
error_tail=""
if [ -f "$STDERR_LOG" ]; then
  error_tail=$(tail -c 1500 "$STDERR_LOG" 2>/dev/null)
fi
journal_tail=$(journalctl -u "$UNIT" -n 10 --no-pager 2>/dev/null | tail -c 800)

msg=$(printf "Daemon crash detected.\nUnit: %s\nDevice: %s\nResult: %s\nExit: %s/%s\n\nstderr tail:\n%s\n\njournal tail:\n%s" \
  "$UNIT" "$device_id" "$RESULT" "$EXIT_CODE" "$EXIT_STATUS" "$error_tail" "$journal_tail")

post_webhook_destinations "EvoBox Daemon Crash" "critical" "$msg" "${WEBHOOK_DESTINATIONS[@]}" || true
exit 0
'

    content="${content_head}"$'\n'"${destinations_literal}"$'\n'"${content_tail}"
    write_if_sha_changed "$DAEMON_ALERT_PATH" "$content" 0755
    return 0
}
# Only the standalone repository owns observability binaries and releases.
# Verify the exact staged bytes before execution or same-filesystem promotion.
verify_observability_candidate() {
    local candidate="$1" version doctor
    "$candidate" --help >/dev/null 2>&1 || return 1
    version=$("$candidate" version --json 2>/dev/null) || return 1
    printf '%s' "$version" | jq -e -s '
        length == 1 and (.[0] | .schema_version == 1 and .operation.status == "ok"
        and .target_os == "linux" and .target_arch == "x86_64"
        and (.version | type == "string" and length > 0)
        and (.source_sha | type == "string" and test("^[0-9a-f]{40}$")))' >/dev/null || return 1
    doctor=$("$candidate" doctor --offline --json 2>/dev/null) || return 1
    printf '%s' "$doctor" | jq -e -s '
        length == 1 and (.[0] | .schema_version == 1 and .operation.status == "ok"
        and .checks.host_collector_supported == true and .checks.unix_sockets == true)' >/dev/null
}

# The caller resets this change flag before each update/lifecycle transaction.
_observability_update() {
    local channel="$1" checksum_raw expected_hash bin_dir staged
    checksum_raw=$(curl --fail --silent --location --connect-timeout 20 --max-time 30 --retry 2 \
        "$OBSERVABILITY_GCS/evobox-observability-$channel.sha256") || {
        log_error "[OBSERVABILITY] Checksum download failed"; return 1;
    }
    expected_hash="${checksum_raw%%[[:space:]]*}"
    if ! is_sha256 "$expected_hash"; then
        log_error "[OBSERVABILITY] Checksum format is invalid"; return 1
    fi
    if [ -x "$OBSERVABILITY_BINARY" ] && [ "$(sha_of "$OBSERVABILITY_BINARY")" = "$expected_hash" ]; then
        return 0
    fi
    bin_dir=$(dirname "$OBSERVABILITY_BINARY")
    sudo install -d -o evobox -g evobox -m 0755 "$bin_dir" || return 1
    # This prefix cannot match the installed binary. Clear only our abandoned stages.
    rm -f "$bin_dir"/.evobox-observability.* 2>/dev/null
    staged=$(mktemp "$bin_dir/.evobox-observability.XXXXXX") || return 1
    if ! curl --fail --silent --location --connect-timeout 20 --max-time 90 --retry 2 \
        -o "$staged" "$OBSERVABILITY_GCS/evobox-observability-$channel"; then
        rm -f "$staged"; log_error "[OBSERVABILITY] Binary download failed"; return 1
    fi
    if [ "$(sha_of "$staged")" != "$expected_hash" ]; then
        rm -f "$staged"; log_error "[OBSERVABILITY] Binary checksum mismatch"; return 1
    fi
    if ! chmod 0755 "$staged" || ! verify_observability_candidate "$staged"; then
        rm -f "$staged"; log_error "[OBSERVABILITY] Candidate validation failed"; return 1
    fi
    if ! mv -T "$staged" "$OBSERVABILITY_BINARY"; then
        rm -f "$staged"; log_error "[OBSERVABILITY] Atomic install failed"; return 1
    fi
    OBSERVABILITY_BINARY_CHANGED=1
    log "[OBSERVABILITY] Installed $channel channel SHA $expected_hash"
}

# Presence is irreversible for migration: never clear a marker or restore a sender.
mark_observability_cutover() {
    local marker="$EVO_CACHE_DIR/observability-cutover-v1.json" status sha staged utc
    [ -e "$marker" ] && return 0
    [ -f "$EVO_CACHE_DIR/observability.lastrun" ] || return 1
    fresh_backoff_active "observability_attempt" "$OBSERVABILITY_RETRY_TTL" && return 1
    sudo systemctl is-active --quiet "$OBSERVABILITY_UNIT" || return 1
    status=$("$OBSERVABILITY_BINARY" status --json 2>/dev/null) || return 1
    printf '%s' "$status" | jq -e -s '
        length == 1 and (.[0] | .schema_version == 1 and .operation.status == "ok"
        and (.freshness.host_age_ms | type == "number" and . >= 0 and . <= 120000))' >/dev/null || return 1
    verify_observability_candidate "$OBSERVABILITY_BINARY" || return 1
    sha=$(sha_of "$OBSERVABILITY_BINARY")
    is_sha256 "$sha" || return 1
    mkdir -p "$EVO_CACHE_DIR" || return 1
    staged=$(mktemp "$EVO_CACHE_DIR/.observability-cutover-v1.XXXXXX") || return 1
    utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)
    if ! jq -n --arg sha "$sha" --arg utc "$utc" \
        '{schema_version: 1, binary_sha256: $sha, cutover_at: $utc}' > "$staged" \
        || ! chmod 0600 "$staged" || ! mv -T "$staged" "$marker"; then
        rm -f "$staged"; return 1
    fi
    log "[OBSERVABILITY] Local monitor verified; legacy Cloud Monitoring sender disabled"
}

# Cached downloads and failed-update backoff never skip service or cutover checks.
install_observability_monitor() {
    local channel="main" update_failed=0 unit_changed=0 write_result unit logrotate
    [ -f "$HOME/.evo-beta-deployment" ] && channel="beta"
    OBSERVABILITY_BINARY_CHANGED=0
    if fresh_due "observability" "$OBSERVABILITY_CHECK_TTL" \
        && ! fresh_backoff_active "observability_attempt" "$OBSERVABILITY_RETRY_TTL"; then
        if _observability_update "$channel"; then
            fresh_mark "observability"
            fresh_clear "observability_attempt"
        else
            fresh_mark "observability_attempt"
            update_failed=1
        fi
    fi
    [ -x "$OBSERVABILITY_BINARY" ] || return 1
    # The parent is created as evobox first: `install -d` makes missing
    # parents root-owned (see ensure_local_state_owner).
    mkdir -p "${OBSERVABILITY_STATE_DIR%/*}" || return 1
    sudo install -d -o evobox -g evobox -m 0700 "$OBSERVABILITY_STATE_DIR" || return 1
    logrotate="$OBSERVABILITY_STATE_DIR/monitor.log {
    size 2M
    daily
    rotate 3
    compress
    delaycompress
    copytruncate
    missingok
    notifempty
    su evobox evobox
}"
    write_if_sha_changed "$OBSERVABILITY_LOGROTATE_PATH" "$logrotate" 0644
    write_result=$?
    [ "$write_result" -le 1 ] || return 1
    unit='[Unit]
Description=EvoBox local observability monitor
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=300
StartLimitBurst=5

[Service]
Type=simple
User=evobox
Group=evobox
Environment=HOME=/home/evobox
ExecStart=/home/evobox/.local/bin/evobox-observability daemon
Restart=on-failure
RestartSec=10
RuntimeDirectory=evobox-observability
RuntimeDirectoryMode=0700
UMask=0077
Nice=10
IOSchedulingClass=idle
MemoryHigh=48M
MemoryMax=64M
MemorySwapMax=0
CPUQuota=5%
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=/home/evobox/.local/state/evobox-observability
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
StandardOutput=null
StandardError=null

[Install]
WantedBy=multi-user.target'
    write_if_sha_changed "$OBSERVABILITY_UNIT_PATH" "$unit" 0644
    case "$?" in
        0) unit_changed=1 ;;
        1) ;;
        *) log_error "[OBSERVABILITY] Failed to write systemd unit"; return 1 ;;
    esac
    if [ "$unit_changed" -eq 1 ]; then
        sudo systemctl daemon-reload || return 1
    fi
    sudo systemctl enable "$OBSERVABILITY_UNIT" >/dev/null 2>&1 || return 1
    if [ "$OBSERVABILITY_BINARY_CHANGED" -eq 1 ] || [ "$unit_changed" -eq 1 ]; then
        sudo systemctl restart "$OBSERVABILITY_UNIT" || return 1
    elif ! sudo systemctl is-active --quiet "$OBSERVABILITY_UNIT"; then
        sudo systemctl start "$OBSERVABILITY_UNIT" || return 1
    fi
    if [ "$update_failed" -eq 0 ]; then
        if ! mark_observability_cutover; then
            log_debug "[OBSERVABILITY] Cutover waits for active monitor and fresh host sample"
        fi
    fi
    [ "$update_failed" -eq 0 ]
}

# Write the systemd unit files (main always, second conditional on flag).
# Uses content-hash idempotency so daemon-reload only runs on actual change.
install_daemon_systemd_unit() {
    local runtime_version main_unit
    runtime_version="$(node_runtime_version)"
    main_unit='[Unit]
Description=EvoBox OBS Daemon (main)
After=graphical.target network-online.target
Wants=network-online.target
StartLimitIntervalSec=600
StartLimitBurst=5

[Service]
Type=simple
User=evobox
Group=evobox
WorkingDirectory=/home/evobox/evosports/evo-obs-daemon-main
Environment=DISPLAY=:0
Environment=XAUTHORITY=/home/evobox/.Xauthority
Environment=HOME=/home/evobox
Environment=NODE_VERSION='"$runtime_version"'
Environment=NVM_DIR=/home/evobox/.config/nvm
ExecStart=/usr/local/bin/evo-daemon-run.sh main
StandardOutput=append:/home/evobox/logs/daemon_stdout.log
StandardError=append:/home/evobox/logs/daemon_stderr.log
Restart=always
RestartSec=10s
TimeoutStopSec=15s
# KillMode=process: signal only MainPID on stop/restart so detached OBS and
# Chrome child processes survive a daemon restart. The daemon startup path
# already reconciles OBS/Chrome state (see obs-utils.ts openOBS / killChrome).
KillMode=process
# MemorySwapMax=0: keep the cgroup (daemon + OBS + Chrome) out of swap.
# eMMC swap causes frame-pacing hitches in OBS; we would rather OOM than stall.
MemorySwapMax=0
ExecStopPost=/usr/local/bin/evo-daemon-alert.sh %n ${SERVICE_RESULT} ${EXIT_CODE} ${EXIT_STATUS}

[Install]
WantedBy=multi-user.target
'

    local second_unit
    second_unit='[Unit]
Description=EvoBox OBS Daemon (second)
After=graphical.target network-online.target
Wants=network-online.target
StartLimitIntervalSec=600
StartLimitBurst=5

[Service]
Type=simple
User=evobox
Group=evobox
WorkingDirectory=/home/evobox/evosports/evo-daemon-second
Environment=DISPLAY=:0
Environment=XAUTHORITY=/home/evobox/.Xauthority
Environment=HOME=/home/evobox
Environment=NODE_VERSION='"$runtime_version"'
Environment=NVM_DIR=/home/evobox/.config/nvm
ExecStart=/usr/local/bin/evo-daemon-run.sh second
StandardOutput=append:/home/evobox/logs/daemon2_stdout.log
StandardError=append:/home/evobox/logs/daemon2_stderr.log
Restart=always
RestartSec=10s
TimeoutStopSec=15s
# KillMode=process: see main unit — keeps OBS/Chrome alive across restarts.
KillMode=process
# MemorySwapMax=0: see main unit — keep OBS/Chrome off eMMC swap.
MemorySwapMax=0
ExecStopPost=/usr/local/bin/evo-daemon-alert.sh %n ${SERVICE_RESULT} ${EXIT_CODE} ${EXIT_STATUS}

[Install]
WantedBy=multi-user.target
'

    local changed=0
    write_if_sha_changed "$DAEMON_UNIT_MAIN_PATH" "$main_unit" 0644
    case $? in
        0) changed=1 ;;
        2) return 1 ;;
    esac

    if [ "$SECOND_DAEMON" = "true" ]; then
        write_if_sha_changed "$DAEMON_UNIT_SECOND_PATH" "$second_unit" 0644
        case $? in
            0) changed=1 ;;
            2) return 1 ;;
        esac
    else
        # Flag absent: leave unit file on disk, but ensure it's disabled
        # so re-enabling is a single `touch + next tick`.
        if [ -f "$DAEMON_UNIT_SECOND_PATH" ]; then
            if sudo systemctl is-enabled --quiet "$DAEMON_UNIT_SECOND" 2>/dev/null \
               || sudo systemctl is-active --quiet "$DAEMON_UNIT_SECOND" 2>/dev/null; then
                log "[SYSTEMD] secondDaemon flag absent — disabling $DAEMON_UNIT_SECOND"
                sudo systemctl disable --now "$DAEMON_UNIT_SECOND" 2>/dev/null || true
            fi
        fi
    fi

    if [ "$changed" = "1" ]; then
        log "[SYSTEMD] Reloading systemd (unit file changed)"
        sudo systemctl daemon-reload || log_error "[SYSTEMD] daemon-reload failed"
        sudo systemctl enable "$DAEMON_UNIT_MAIN" >/dev/null 2>&1 || log_error "[SYSTEMD] enable $DAEMON_UNIT_MAIN failed"
        if [ "$SECOND_DAEMON" = "true" ]; then
            sudo systemctl enable "$DAEMON_UNIT_SECOND" >/dev/null 2>&1 || log_error "[SYSTEMD] enable $DAEMON_UNIT_SECOND failed"
        fi
    fi
    return 0
}

# One-time migration: kill legacy nohup'd node daemons that were started by
# the old cron-tick launch pattern. Guarded by a flag file so it runs
# exactly once per device. Critical: only kill the legacy process AFTER the
# systemd-managed unit is confirmed active, so a broken systemd install
# cannot brick the device.
migrate_legacy_nohup_daemon() {
    local flag="$HOME/.evo-systemd-migrated-v1"
    [ -f "$flag" ] && return 0

    log "[SYSTEMD:MIGRATE] Migrating legacy nohup daemon to systemd"

    # Step 1: start the new unit.
    sudo systemctl start "$DAEMON_UNIT_MAIN" 2>/dev/null || true
    if [ "$SECOND_DAEMON" = "true" ]; then
        sudo systemctl start "$DAEMON_UNIT_SECOND" 2>/dev/null || true
    fi

    # Step 2: wait up to 15s for main unit to become active.
    local waited=0
    while [ "$waited" -lt 15 ]; do
        if sudo systemctl is-active --quiet "$DAEMON_UNIT_MAIN"; then
            break
        fi
        sleep 1
        waited=$((waited + 1))
    done

    if ! sudo systemctl is-active --quiet "$DAEMON_UNIT_MAIN"; then
        log_error "[SYSTEMD:MIGRATE] $DAEMON_UNIT_MAIN did not become active within 15s — aborting migration, legacy daemon untouched"
        return 1
    fi

    # Step 3: kill any legacy nohup'd node processes. Filter out the
    # systemd-managed one (which runs via evo-daemon-run.sh). The unit's
    # MainPID is the real node, but its CGroup parent is the runner, so
    # we identify systemd-owned PIDs via `systemctl show -p MainPID`.
    local systemd_main_pid systemd_second_pid
    systemd_main_pid=$(sudo systemctl show -p MainPID --value "$DAEMON_UNIT_MAIN" 2>/dev/null)
    systemd_second_pid=$(sudo systemctl show -p MainPID --value "$DAEMON_UNIT_SECOND" 2>/dev/null)

    local legacy_pids
    legacy_pids=$(ps -eo pid,cmd --no-headers \
        | grep -E 'node .*/evo-(obs-daemon-main|daemon-second)/index\.js' \
        | grep -v grep \
        | awk '{print $1}')

    local killed_any=0
    local pid
    for pid in $legacy_pids; do
        if [ "$pid" = "$systemd_main_pid" ] || [ "$pid" = "$systemd_second_pid" ]; then
            continue
        fi
        log "[SYSTEMD:MIGRATE] Killing legacy daemon PID $pid"
        kill -TERM "$pid" 2>/dev/null && killed_any=1
    done

    if [ "$killed_any" = "1" ]; then
        sleep 5
        for pid in $legacy_pids; do
            if [ "$pid" = "$systemd_main_pid" ] || [ "$pid" = "$systemd_second_pid" ]; then
                continue
            fi
            if kill -0 "$pid" 2>/dev/null; then
                log "[SYSTEMD:MIGRATE] SIGTERM did not stop PID $pid — SIGKILL"
                kill -KILL "$pid" 2>/dev/null
            fi
        done
    fi

    touch "$flag"
    log "[SYSTEMD:MIGRATE] Migration complete"
    return 0
}

# Fire a webhook when a daemon unit has been down continuously for longer
# than DAEMON_DOWN_THRESHOLD. Called by ensure_daemon_running_via_systemd
# on each tick where the unit is observed as not-active. First observation
# seeds /tmp/.evo-daemon-down-${unit}; subsequent ticks measure against it
# and fire once downtime crosses the threshold. A separate alert-state
# file enforces DAEMON_DOWN_ALERT_COOLDOWN so a stuck daemon doesn't spam.
notify_daemon_down_if_sustained() {
    local unit="$1"
    local down_state="/tmp/.evo-daemon-down-${unit}"
    local alert_state="/tmp/.evo-daemon-down-alert-${unit}"
    local now first_down downtime last_alert
    now=$(date +%s)

    if [ ! -f "$down_state" ]; then
        echo "$now" > "$down_state"
        return 0
    fi
    first_down=$(cat "$down_state" 2>/dev/null || echo "$now")
    downtime=$(( now - first_down ))
    if [ "$downtime" -lt "$DAEMON_DOWN_THRESHOLD" ]; then
        return 0
    fi
    if [ -f "$alert_state" ]; then
        last_alert=$(cat "$alert_state" 2>/dev/null || echo 0)
        if [ $(( now - last_alert )) -lt "$DAEMON_DOWN_ALERT_COOLDOWN" ]; then
            return 0
        fi
    fi

    local device_id evo_json journal_tail msg
    case "$unit" in
        *second*) evo_json="/home/evobox/evosports/evo-daemon-second/evo.json" ;;
        *)       evo_json="/home/evobox/evosports/evo-obs-daemon-main/evo.json" ;;
    esac
    device_id=$(jq -r .deviceId "$evo_json" 2>/dev/null)
    [ -z "$device_id" ] || [ "$device_id" = "null" ] && device_id="unknown"
    journal_tail=$(journalctl -u "$unit" -n 15 --no-pager 2>/dev/null | tail -c 1200)

    msg=$(printf "Daemon sustained-down detected.\nUnit: %s\nDowntime: %ds\nThreshold: %ds\nDevice: %s\n\njournal tail:\n%s" \
        "$unit" "$downtime" "$DAEMON_DOWN_THRESHOLD" "$device_id" "$journal_tail")
    if post_webhook_destinations "EvoBox Daemon Down" "critical" "$msg" "${DAEMON_ALERT_WEBHOOK_DESTINATIONS[@]}"; then
        log "[DAEMON-DOWN] Sustained-down alert sent: $unit inactive ${downtime}s"
    else
        log_error "[DAEMON-DOWN] Webhook delivery failed: $unit inactive ${downtime}s"
    fi
    echo "$now" > "$alert_state"
}

# Ensure the daemon unit is running. If unit is in failed state (burst
# limit exhausted by repeated crashes), reset it and restart — this is how
# the 5-minute cron cadence provides prolonged backoff after pathological
# crash loops.
ensure_daemon_running_via_systemd() {
    local unit="$1"
    local down_state="/tmp/.evo-daemon-down-${unit}"
    local alert_state="/tmp/.evo-daemon-down-alert-${unit}"

    if sudo systemctl is-failed --quiet "$unit"; then
        notify_daemon_down_if_sustained "$unit"
        log "[SYSTEMD] $unit in failed state, resetting and restarting"
        sudo systemctl reset-failed "$unit" 2>/dev/null || true
        sudo systemctl start "$unit" || log_error "[SYSTEMD] start $unit failed after reset"
        return 0
    fi

    if ! sudo systemctl is-active --quiet "$unit"; then
        notify_daemon_down_if_sustained "$unit"
        log "[SYSTEMD] $unit not active, starting"
        sudo systemctl start "$unit" || log_error "[SYSTEMD] start $unit failed"
    else
        # Daemon healthy — clear sustained-down tracking so the 15-min
        # countdown restarts if it goes down again later.
        [ -f "$down_state" ] && rm -f "$down_state"
        [ -f "$alert_state" ] && rm -f "$alert_state"
        log_debug "[SYSTEMD] $unit already active"
    fi
}

setup_blank_screensaver() {
    if [ ! -f ~/.xscreensaver ]; then
        cat > ~/.xscreensaver <<'EOF'
timeout:        0:00:30
cycle:          0:00:00
lock:           True
lockTimeout:    0:00:00
passwdTimeout:  0:00:30
visualID:       default
installColormap: True
verbose:        False
fade:           False
unfade:         False
fadeSeconds:    0
fadeTicks:      0
dpmsEnabled:    False
dpmsQuickOff:   False
mode:           blank
selected:       114
EOF
    fi
}

disable_wayland_support() {
    if [ -f /etc/gdm3/custom.conf ]; then
        sudo sed -i 's/#WaylandEnable=false/WaylandEnable=false/' /etc/gdm3/custom.conf
    else
        log "Unsupported display manager. Please disable Wayland manually for your specific display manager."
        return 1
    fi
    log "Wayland has been disabled"
}

#-------------------------------------------------------------------------------
# SSH access (issue #33)
#
# SSH must not depend on Tailscale. Pinning sshd to the current Tailscale IPv4
# address made remote access die with the tunnel and forced a full
# `systemctl restart ssh` -- dropping every live session, including the one
# running this installer -- each time that address changed. The managed drop-in
# now carries only PasswordAuthentication, so sshd keeps OpenSSH's wildcard
# listener (loopback, LAN and Tailscale all work) and a healthy sshd is never
# restarted: at most it is reloaded, and only when the kernel says the listener
# has not converged yet.
#-------------------------------------------------------------------------------

# _ssh_listener_state [SOCKET_ACTIVE]
# Prints "<state> <owners>" describing TCP port 22 as the kernel sees it:
#   none | wildcard | pinned | rogue | unknown, plus the comma-joined owning
# process names ("-" when unavailable). Returns 1 for "unknown" so no caller
# ever declares SSH down on the strength of a probe that itself failed.
#
# A listener is only ever "wildcard"/"pinned" when sshd owns it — or systemd,
# and then only when ssh.socket is actually active, because that is the one
# supported arrangement where systemd holds the listening descriptor for sshd.
# Anything else on TCP 22 ("rogue") answers connections but is not SSH: treating
# it as healthy would both hide an outage and let a convergence check pass on
# someone else's socket.
_ssh_listener_state() {
    local socket_active="${1:-false}"
    local out rc addrs owners state="none" owner
    out=$(sudo ss -H -ltnp 2>/dev/null)
    rc=$?
    if [ "$rc" -ne 0 ]; then
        printf 'unknown -\n'
        return 1
    fi

    addrs=$(printf '%s\n' "$out" | awk '$4 ~ /:22$/ {print $4}')
    owners=$(printf '%s\n' "$out" | awk '$4 ~ /:22$/' | grep -oE '\("[^"]+"' | tr -d '("' | sort -u | tr '\n' ',' | sed 's/,$//')
    [ -n "$owners" ] || owners="-"

    if [ -n "$addrs" ]; then
        state="pinned"
        local entry addr
        while IFS= read -r entry; do
            [ -n "$entry" ] || continue
            addr="${entry%:22}"
            case "$addr" in
                "0.0.0.0" | "*" | "[::]" | "::" | "[*]") state="wildcard" ;;
            esac
        done <<<"$addrs"

        # An unreadable owner is unknown, and unknown is not sshd.
        while IFS= read -r owner; do
            [ -n "$owner" ] || continue
            case "$owner" in
                sshd) ;;
                systemd) [ "$socket_active" = true ] || state="rogue" ;;
                *) state="rogue" ;;
            esac
        done <<<"$(printf '%s' "$owners" | tr ',' '\n')"
    fi

    printf '%s %s\n' "$state" "$owners"
    return 0
}

# SHA-256 of text ($1) / of a root-owned file ($1), printed bare. Return 1 --
# and print nothing -- whenever the digest could not be established.
#
# The obvious `sudo sha256sum "$f" | awk '{print $1}'` cannot be used here:
# under `set +e` with no pipefail the pipeline reports awk's status, so a sudo
# that was denied, a missing file or a truncated read all yield an empty string
# that silently compares "different". That difference is what drives rewriting
# the config and reloading sshd, so an unreadable file would provoke a write
# and a reload on every tick. The digest is captured first, judged on its own
# exit status, and then required to actually look like a SHA-256.
_ssh_sha256_of_text() {
    local out rc
    out=$(printf '%s' "$1" | sha256sum)
    rc=$?
    [ "$rc" -eq 0 ] || return 1
    _ssh_sha256_field "$out"
}

_ssh_sha256_of_root_file() {
    local out rc
    out=$(sudo sha256sum "$1" 2>/dev/null)
    rc=$?
    [ "$rc" -eq 0 ] || return 1
    _ssh_sha256_field "$out"
}

# First field of a sha256sum line, accepted only if it is a full 64-hex digest.
_ssh_sha256_field() {
    local digest="${1%% *}"
    [[ "$digest" =~ ^[0-9a-f]{64}$ ]] || return 1
    printf '%s' "$digest"
    return 0
}

# True only when the file just restored at $2 is byte-identical to the backup
# $1 it came from. A digest that cannot be read on either side is a rollback
# this device cannot vouch for, so it fails instead of comparing two empty
# strings and reporting the config restored.
_ssh_restored_matches() {
    local want got
    want=$(_ssh_sha256_of_root_file "$1") || return 1
    got=$(_ssh_sha256_of_root_file "$2") || return 1
    [ "$want" = "$got" ]
}

# Effective sshd listen addresses (one per line) from the parsed configuration.
# Returns sshd's own exit status, not awk's -- `set +e` without pipefail would
# otherwise report success for a config sshd could not even read.
_ssh_effective_listen_addresses() {
    sudo sshd -T 2>/dev/null | awk 'tolower($1) == "listenaddress" {print $2}'
    return "${PIPESTATUS[0]}"
}

# Classifies the newline-separated listen addresses in $1:
#   0 = a wildcard listener is configured
#   1 = every entry is pinned to a specific address
#   2 = no entries at all (OpenSSH's own default is the wildcard listener)
_ssh_classify_listen_addresses() {
    local addrs="$1" entry addr
    [ -n "$addrs" ] || return 2
    while IFS= read -r entry; do
        [ -n "$entry" ] || continue
        addr="${entry%:*}"
        case "$addr" in
            "0.0.0.0" | "*" | "[::]" | "::") return 0 ;;
        esac
    done <<<"$addrs"
    return 1
}

# Stage a new root-owned, 0600 scratch file inside the root-only directory $1
# and print its path. Nothing else in this file may create a candidate or a
# backup any other way.
#
# The obvious `mktemp` is wrong here, and dangerously so. It creates the file
# as the invoking (unprivileged) user, in a directory that user can write. Both
# of the things this code then does with such a path are a privilege handoff:
# `sudo cp "$conf" "$tmp"` writes root-owned content into it, and
# `sudo cp "$tmp" "$conf"` reads it back and installs it as sshd's or systemd's
# configuration. Between those two moments the owner of the staging path can
# replace it — with different content, or with a symlink to any file on the
# box — and have root either overwrite that target or install whatever they
# put there. Creating the file through sudo, in a directory only root may
# write, removes the window entirely: there is no moment at which the path is
# under anyone else's control.
_ssh_stage_root_file() {
    local dir="$1" tmp
    [ -n "$dir" ] || return 1
    sudo mkdir -p "$dir" || return 1
    tmp=$(sudo mktemp "${dir}/.evo-ssh-stage.XXXXXX" 2>/dev/null) || return 1
    [ -n "$tmp" ] || return 1
    if ! sudo chmod 0600 "$tmp"; then
        sudo rm -f "$tmp"
        return 1
    fi
    printf '%s' "$tmp"
}

# Root-owned 0600 copy of the root-owned file $1, staged in its own directory.
_ssh_backup_root_file() {
    local src="$1" backup
    backup=$(_ssh_stage_root_file "$(dirname "$src")") || return 1
    if ! sudo cp "$src" "$backup" || ! sudo chmod 0600 "$backup"; then
        sudo rm -f "$backup"
        return 1
    fi
    printf '%s' "$backup"
}

# A tick killed between staging and cleanup leaves a scratch file behind. It is
# inert (neither sshd nor systemd reads a name that does not end in .conf), but
# it is ours to remove.
#
# EVERY file matching the pattern goes, not only the ones older than a day.
# The only writer of these names is this program, the whole run is serialized
# by the install flock, and each caller sweeps BEFORE it stages anything of
# its own — so there is no concurrent tick whose staging file this could take
# away. The age filter only ever meant that a tick killed at the wrong moment
# left root-owned litter in /etc for a day, and a device killed by the
# watchdog repeatedly (the case this exists for) accumulated one per tick.
_ssh_sweep_stale_stage() {
    local dir
    for dir in "$@"; do
        [ -n "$dir" ] || continue
        sudo test -d "$dir" || continue
        sudo find "$dir" -maxdepth 1 -name '.evo-ssh-stage.*' -delete 2>/dev/null
    done
    return 0
}

# Installs root-owned file $1 at root-owned path $2 (mode 0644) through a
# root-owned temp file in the *destination* directory, so the rename is atomic
# and sshd can never read a half-written config. $1 must have come from
# _ssh_stage_root_file()/_ssh_backup_root_file(); a path anyone else can write
# is not an acceptable source for a root-installed configuration.
_ssh_install_conf_atomic() {
    local src="$1" dst="$2" dir tmp
    dir=$(dirname "$dst")
    tmp=$(_ssh_stage_root_file "$dir") || return 1
    if ! sudo cp "$src" "$tmp"; then
        sudo rm -f "$tmp"
        return 1
    fi
    if ! sudo chmod 0644 "$tmp"; then
        sudo rm -f "$tmp"
        return 1
    fi
    if ! sudo mv -f "$tmp" "$dst"; then
        sudo rm -f "$tmp"
        return 1
    fi
    return 0
}

# Undoes this tick's managed changes and nothing else.
# $1 conf_changed, $2 conf backup file, $3 conf_existed, $4 dropin_removed,
# $5 dropin backup file.
# Returns 1 when any part of the undo did not complete, so the caller reports a
# device left mid-change instead of logging a rollback it cannot vouch for.
_ssh_rollback_managed() {
    local conf_changed="$1" conf_backup="$2" conf_existed="$3"
    local dropin_removed="$4" dropin_backup="$5"
    local dropin="/etc/systemd/system/ssh.service.d/wait-for-tailscale.conf"
    local rc=0

    if [ "$conf_changed" = true ]; then
        if [ "$conf_existed" = true ] && [ -n "$conf_backup" ]; then
            if _ssh_install_conf_atomic "$conf_backup" "$SSH_TAILSCALE_CONF" \
                && _ssh_restored_matches "$conf_backup" "$SSH_TAILSCALE_CONF"; then
                log "[SSH] Rolled back $SSH_TAILSCALE_CONF"
            else
                log_error "[SSH] Rollback of $SSH_TAILSCALE_CONF failed"
                rc=1
            fi
        else
            if sudo rm -f "$SSH_TAILSCALE_CONF" && ! sudo test -f "$SSH_TAILSCALE_CONF"; then
                log "[SSH] Rolled back $SSH_TAILSCALE_CONF (removed)"
            else
                log_error "[SSH] Rollback of $SSH_TAILSCALE_CONF (removal) failed"
                rc=1
            fi
        fi
    fi

    if [ "$dropin_removed" = true ] && [ -n "$dropin_backup" ]; then
        if _ssh_install_conf_atomic "$dropin_backup" "$dropin" \
            && _ssh_restored_matches "$dropin_backup" "$dropin"; then
            log "[SSH] Restored $dropin"
        else
            log_error "[SSH] Restore of $dropin failed"
            rc=1
        fi
        # The restored unit file only takes effect once systemd re-reads it.
        if ! run_logged sudo systemctl daemon-reload; then
            log_error "[SSH] daemon-reload failed while restoring $dropin"
            rc=1
        fi
    fi
    return "$rc"
}

# Removes this tick's staged files. They are root-owned, so removal is too.
# Tolerates empty and missing paths.
_ssh_drop_backups() {
    local file
    for file in "$@"; do
        [ -n "$file" ] && sudo rm -f "$file"
    done
    return 0
}

# Brings the *listener* in line with the managed configuration.
# $1 conf_changed, $2 listener state, $3 socket_active, $4 listener probe rc
# (0 when the probe itself succeeded; non-zero means the state is "unknown").
# Returns 0 on success, 1 for a failure that must not be rolled back,
# 2 for a failure whose managed changes should be rolled back.
_ssh_converge_ssh_service() {
    local conf_changed="$1" listener_state="$2" socket_active="$3"
    local listener_rc="${4:-0}"

    # ssh.socket already owns a wildcard TCP 22. The service config is applied
    # for future starts; nothing is reloaded or restarted, because the socket --
    # not sshd -- owns the listening file descriptor.
    if [ "$socket_active" = true ] && [ "$listener_state" = "wildcard" ]; then
        log_debug "[SSH] ssh.socket provides a wildcard listener; units left untouched"
        return 0
    fi

    # Socket-activated host whose listener could not be read. "Unknown" is not
    # "missing": under socket activation ssh.service is inactive BY DESIGN, so
    # the is-active test below would answer false and start it — against an
    # address ssh.socket already holds. That start fails, and the failure would
    # roll back a configuration that was fine. Nothing here is evidence of a
    # problem, so the tick ends unconverged and the next one re-probes.
    if [ "$socket_active" = true ] && [ "$listener_rc" -ne 0 ]; then
        log_error "[SSH] Cannot read the TCP 22 listener while ssh.socket is active; not starting ssh.service"
        return 1
    fi

    local ssh_active=false
    systemctl is-active --quiet ssh && ssh_active=true

    if [ "$ssh_active" != true ]; then
        systemctl is-enabled --quiet ssh 2>/dev/null || sudo systemctl enable ssh >/dev/null 2>&1
        if run_logged sudo systemctl start ssh; then
            log "[SUCCESS] Started ssh.service"
            return 0
        fi
        log_error "[SSH] Failed to start ssh.service"
        return 2
    fi

    # Already converged: the managed file is current and the kernel shows a
    # wildcard listener. Zero reloads, zero restarts, zero writes.
    if [ "$conf_changed" != true ] && [ "$listener_state" = "wildcard" ]; then
        log_debug "[SSH] Managed config and wildcard listener already in place"
        return 0
    fi

    # Nothing was written this tick and the probe that would say whether the
    # listener is right could not be run. "Unknown" is not "pinned": reloading
    # a healthy sshd to fix a state nobody observed is a change made on no
    # evidence, on every tick for as long as `ss` keeps failing. The tick ends
    # unconverged instead, and the next one re-probes.
    if [ "$conf_changed" != true ] && [ "$listener_rc" -ne 0 ]; then
        log_error "[SSH] Cannot read the TCP 22 listener and nothing changed this tick; not reloading sshd"
        return 1
    fi

    # Reload, never restart: reload keeps established sessions alive. This also
    # recovers the tick that wrote the file and was killed before reloading.
    if ! run_logged sudo systemctl reload ssh; then
        log_error "[SSH] Failed to reload ssh.service"
        return 2
    fi

    # A zero exit from reload is not evidence. Re-read the kernel state.
    local attempt state owners
    state=""
    for attempt in 1 2 3 4 5; do
        read -r state owners <<<"$(_ssh_listener_state "$socket_active")"
        [ "$state" = "wildcard" ] && break
        sleep 1
    done
    if [ "$state" != "wildcard" ]; then
        # "rogue" lands here too: something answers on TCP 22, but not sshd.
        log_error "[SSH] Listener still pinned after reload (state=${state} owner=${owners})"
        return 1
    fi
    log "[SUCCESS] SSH listening on all interfaces (owner=${owners})"
    return 0
}

# Is systemd still serving the given drop-in path for ssh.service?
#
# The unit files on disk and the unit systemd is RUNNING are two different
# things: removing a drop-in does nothing until the manager re-reads its
# configuration. Prints nothing; returns 0 loaded, 1 not loaded, 2 when
# systemd could not be asked (unknown, which is never treated as "converged").
_ssh_dropin_is_loaded() {
    local dropin="$1" paths
    paths=$(systemctl show -p DropInPaths --value ssh.service 2>/dev/null) || return 2
    case " $(printf '%s' "$paths" | tr '\n' ' ') " in
        *" ${dropin} "*) return 0 ;;
    esac
    return 1
}

# Applies the managed sshd drop-in and converges the listener. Never touches
# configuration owned by anyone else, and never restarts a working sshd.
_ssh_apply_managed_config() {
    local conf="$SSH_TAILSCALE_CONF"
    local dropin="/etc/systemd/system/ssh.service.d/wait-for-tailscale.conf"

    # Sweep first, before anything is staged. Every scratch file under these
    # two root-only directories is this program's (see _ssh_stage_root_file),
    # the install flock serializes the whole run, and nothing of this tick's
    # own exists yet -- so clearing them here can only remove litter from a
    # tick that was killed, and can never remove a file still in use.
    _ssh_sweep_stale_stage "$(dirname "$SSH_TAILSCALE_CONF")" "$(dirname "$dropin")"

    if ! check_command "sshd"; then
        run_apt_update_if_needed
        if run_logged sudo apt-get install -y openssh-server; then
            log "[SUCCESS] openssh-server installed"
        else
            log_error "[SSH] Failed to install openssh-server"
            return 1
        fi
    fi

    # What is on disk must already parse. Applying our file on top of someone
    # else's broken config and reloading would turn their mistake into an outage.
    if ! run_logged sudo sshd -t; then
        log_error "[SSH] Existing sshd configuration is invalid; managed config not applied"
        return 1
    fi

    local socket_active=false
    systemctl is-active --quiet ssh.socket && socket_active=true
    log_debug "[SSH] ssh.service=$(systemctl show -p ActiveState --value ssh.service 2>/dev/null) ssh.socket active=${socket_active}"

    # The probe's own exit status is kept, not flattened into the printed
    # state: "unknown" from a failed `ss` and "pinned" from a real reading are
    # different facts, and only one of them justifies reloading sshd.
    local listener_state listener_owners listener_probe listener_rc=0
    listener_probe=$(_ssh_listener_state "$socket_active") || listener_rc=$?
    read -r listener_state listener_owners <<<"$listener_probe"
    log_debug "[SSH] TCP/22 listener: ${listener_state} (owner=${listener_owners} rc=${listener_rc})"

    # A socket-activated, address-pinned listener cannot be converted on a
    # remote device: stopping the socket to rewrite it drops the session doing
    # the work. Leave it alone and flag it for a maintenance window.
    if [ "$socket_active" = true ] && [ "$listener_state" = "pinned" ]; then
        log_error "[SSH] Pinned socket requires a maintenance migration"
        return 1
    fi

    # No ListenAddress: sshd keeps the wildcard listener and survives Tailscale.
    local desired
    desired="# Managed by evobox-obs-daemon-install.sh - do not edit manually
PasswordAuthentication yes
"
    local desired_sha current_sha=""
    if ! desired_sha=$(_ssh_sha256_of_text "$desired"); then
        log_error "[SSH] Cannot hash the managed configuration; leaving sshd untouched"
        return 1
    fi

    local conf_existed=false conf_backup="" conf_changed=false
    local dropin_removed=false dropin_backup=""
    local rc=0 need_rollback=false

    # Root-owned file: compare with sudo. write_if_sha_changed() hashes without
    # sudo, so it would miss here and rewrite on every tick. The backup temp is
    # created only when the file is actually about to be replaced: a healthy,
    # converged device must not create (and then delete) a temp file every five
    # minutes just to prove nothing changed.
    #
    # A digest that cannot be read is not "different": treating it that way
    # would rewrite the file and reload sshd every five minutes on a device
    # whose sudo or filesystem is degraded. Nothing is written and nothing is
    # reloaded until the current content is actually known.
    if sudo test -f "$conf"; then
        conf_existed=true
        if ! current_sha=$(_ssh_sha256_of_root_file "$conf"); then
            log_error "[SSH] Cannot hash $conf; leaving it and the running sshd untouched"
            return 1
        fi
    fi

    # Both the backup and the candidate live in the destination directory,
    # which only root may write, and both are created through sudo. See
    # _ssh_stage_root_file(): a staging path under this user's control is a
    # path this user can swap for a symlink between root's write and root's
    # read, which turns "back up a config" into "overwrite any file" and
    # "install our config" into "install theirs".

    if [ "$desired_sha" != "$current_sha" ] && [ "$conf_existed" = true ]; then
        if ! conf_backup=$(_ssh_backup_root_file "$conf") || [ -z "$conf_backup" ]; then
            _ssh_drop_backups "$conf_backup"
            log_error "[SSH] Cannot back up $conf; leaving it untouched"
            return 1
        fi
    fi

    if [ "$desired_sha" != "$current_sha" ]; then
        local tmp_desired staged_sha installed_sha
        if ! tmp_desired=$(_ssh_stage_root_file "$(dirname "$conf")") || [ -z "$tmp_desired" ]; then
            _ssh_drop_backups "$conf_backup" "$tmp_desired"
            log_error "[SSH] Failed to stage managed config"
            return 1
        fi
        # The candidate is written through sudo as well: nothing this user owns
        # ever holds the bytes that become sshd's configuration.
        if ! printf '%s' "$desired" | sudo tee "$tmp_desired" > /dev/null; then
            _ssh_drop_backups "$conf_backup" "$tmp_desired"
            log_error "[SSH] Failed to stage managed config"
            return 1
        fi
        # What was staged is what was intended -- read back from the root-owned
        # file, not from the variable that produced it.
        if ! staged_sha=$(_ssh_sha256_of_root_file "$tmp_desired") \
            || [ "$staged_sha" != "$desired_sha" ]; then
            _ssh_drop_backups "$conf_backup" "$tmp_desired"
            log_error "[SSH] Staged managed config does not match the intended content"
            return 1
        fi
        if ! _ssh_install_conf_atomic "$tmp_desired" "$conf"; then
            _ssh_drop_backups "$conf_backup" "$tmp_desired"
            log_error "[SSH] Failed to write $conf"
            return 1
        fi
        _ssh_drop_backups "$tmp_desired"
        conf_changed=true
        # And what is now installed is what was staged.
        if ! installed_sha=$(_ssh_sha256_of_root_file "$conf") \
            || [ "$installed_sha" != "$desired_sha" ]; then
            log_error "[SSH] $conf does not match the managed config after promotion"
            rc=1
            need_rollback=true
        else
            log "[SSH] Managed sshd config updated (no ListenAddress pin)"
        fi
    fi

    if [ "$conf_changed" = true ] && ! run_logged sudo sshd -t; then
        log_error "[SSH] Managed config failed validation"
        rc=1
        need_rollback=true
    fi

    # The effective config -- ours plus everyone else's -- must end up wildcard.
    if [ "$rc" -eq 0 ]; then
        local eff_addrs eff_rc
        eff_addrs=$(_ssh_effective_listen_addresses)
        eff_rc=$?
        if [ "$eff_rc" -ne 0 ]; then
            log_error "[SSH] Cannot read effective sshd configuration"
            rc=1
        else
            _ssh_classify_listen_addresses "$eff_addrs"
            case $? in
                0) log_debug "[SSH] Effective sshd listener is wildcard" ;;
                2) log_debug "[SSH] sshd reports no ListenAddress; wildcard default applies" ;;
                *)
                    # Someone else's config still pins the address. Deleting it
                    # is not ours to do; undo our own change instead.
                    log_error "[SSH] Another sshd config still pins ListenAddress: $(printf '%s' "$eff_addrs" | tr '\n' ' ')"
                    rc=1
                    ;;
            esac
        fi
        if [ "$rc" -ne 0 ]; then
            need_rollback=true
        fi
    fi

    # The wait-for-Tailscale ExecStartPre exists only because sshd used to bind
    # the tunnel address. Remove it -- but only when the content is exactly the
    # drop-in this script used to write. Unknown content stays.
    if [ "$rc" -eq 0 ] && sudo test -f "$dropin"; then
        local known_dropin known_sha dropin_sha
        known_dropin='# Managed by evobox-obs-daemon-install.sh
[Unit]
After=tailscaled.service
Wants=tailscaled.service

[Service]
ExecStartPre=/usr/local/bin/wait-for-tailscale-ip.sh
'
        # Same reasoning as the managed config: an unreadable digest is not
        # evidence that the content is unmanaged. Claiming so would either leave
        # sshd gated on Tailscale while this tick reported the gate removed, or
        # (with the comparison masked) delete a unit file nobody read. Undo this
        # tick's own change and retry in five minutes instead.
        if ! known_sha=$(_ssh_sha256_of_text "$known_dropin") \
            || ! dropin_sha=$(_ssh_sha256_of_root_file "$dropin"); then
            log_error "[SSH] Cannot hash $dropin; leaving it in place"
            rc=1
            need_rollback=true
        elif [ "$known_sha" = "$dropin_sha" ]; then
            dropin_backup=$(_ssh_backup_root_file "$dropin")
            if [ -n "$dropin_backup" ] && sudo rm -f "$dropin"; then
                dropin_removed=true
                # systemd keeps serving the old unit until it re-reads it, so
                # an unverified daemon-reload would leave sshd still gated on
                # Tailscale while this tick claimed the gate was gone. A zero
                # exit from daemon-reload is not that evidence either: it says
                # the manager accepted the request, not that this drop-in
                # stopped being served (a reload that fails to parse another
                # unit, or a manager that kept a cached view, both exit 0).
                # The manager is therefore asked again, and anything other
                # than a definite "not loaded" -- still loaded, or a query
                # that failed -- rolls this tick back and retries.
                local loaded_after=0
                if ! run_logged sudo systemctl daemon-reload; then
                    log_error "[SSH] daemon-reload failed after removing $dropin"
                    rc=1
                    need_rollback=true
                else
                    _ssh_dropin_is_loaded "$dropin" || loaded_after=$?
                    if [ "$loaded_after" -eq 1 ]; then
                        log "[SSH] Removed $dropin; sshd no longer waits for Tailscale"
                    elif [ "$loaded_after" -eq 0 ]; then
                        log_error "[SSH] systemd still serves $dropin after removing it and reloading"
                        rc=1
                        need_rollback=true
                    else
                        log_error "[SSH] Cannot confirm systemd dropped $dropin after the reload"
                        rc=1
                        need_rollback=true
                    fi
                fi
            else
                log_error "[SSH] Failed to remove $dropin"
                rc=1
                need_rollback=true
            fi
        else
            log "[SSH] Unmanaged content in $dropin left untouched"
        fi
    elif [ "$rc" -eq 0 ]; then
        # The managed drop-in is gone from disk, which is not the same as gone
        # from systemd. A tick that was killed by the watchdog between `rm` and
        # `daemon-reload` leaves sshd still gated on Tailscale while every
        # file-based check says the migration is finished, and no marker is
        # written anywhere that would record the difference. So the manager's
        # own view is what is consulted, every tick, and convergence is only
        # declared once it agrees. Nothing is restarted: daemon-reload does not
        # touch the running sshd or its sessions, and a failure just returns
        # non-zero so the next tick finds the same state and retries.
        local loaded=0
        _ssh_dropin_is_loaded "$dropin" || loaded=$?
        if [ "$loaded" -eq 0 ]; then
            log "[SSH] $dropin is deleted but systemd still has it loaded; re-reading unit configuration"
            if ! run_logged sudo systemctl daemon-reload; then
                log_error "[SSH] daemon-reload failed while clearing the deleted $dropin"
                rc=1
            else
                loaded=0
                _ssh_dropin_is_loaded "$dropin" || loaded=$?
                if [ "$loaded" -eq 1 ]; then
                    log "[SSH] systemd no longer loads $dropin"
                else
                    log_error "[SSH] systemd still lists $dropin after daemon-reload"
                    rc=1
                fi
            fi
        elif [ "$loaded" -ne 1 ]; then
            log_error "[SSH] Cannot read ssh.service drop-ins; not declaring the wait gate removed"
            rc=1
        fi
    fi

    if [ "$rc" -eq 0 ]; then
        _ssh_converge_ssh_service "$conf_changed" "$listener_state" "$socket_active" \
            "$listener_rc"
        case $? in
            0) ;;
            2)
                rc=1
                need_rollback=true
                ;;
            *) rc=1 ;;
        esac
    fi

    if [ "$need_rollback" = true ]; then
        if ! _ssh_rollback_managed "$conf_changed" "$conf_backup" "$conf_existed" \
            "$dropin_removed" "$dropin_backup"; then
            log_error "[SSH] Rollback did not complete; device left mid-change, retrying next tick"
            rc=1
        fi
    fi
    _ssh_drop_backups "$conf_backup" "$dropin_backup"
    return "$rc"
}

configure_ssh_tailscale() {
    local rc=0
    _ssh_apply_managed_config || rc=$?

    # Ensure all authorized keys are present (append-only)
    mkdir -p "$HOME/.ssh"
    chmod 700 "$HOME/.ssh"
    touch "$HOME/.ssh/authorized_keys"
    chmod 600 "$HOME/.ssh/authorized_keys"

    for pubkey in "${SSH_AUTHORIZED_KEYS[@]}"; do
        if ! grep -qF "$pubkey" "$HOME/.ssh/authorized_keys" 2>/dev/null; then
            echo "$pubkey" >> "$HOME/.ssh/authorized_keys"
            log "[SSH] Added key: ${pubkey##* }"
        fi
    done

    # SSH_UNAVAILABLE means exactly one thing: NOTHING is listening on TCP 22,
    # including after a rollback. That is the condition whose fixed advice --
    # "SSH down on device; check via VNC or on-site" -- is actually correct.
    #
    # A "rogue" owner is a real problem and this tick already says so: the
    # convergence path logs it and returns non-zero. But a socket that answers
    # is not an outage this page can describe. The owner string comes from
    # `ss`, so an sshd started through a wrapper, a differently named build,
    # or a container shim all read as rogue while logins keep working -- and
    # paging "SSH down; go on-site" for a box someone is logged into is how a
    # critical alert stops being believed. The listener exists, so the alert
    # is healthy and the log carries the discrepancy.
    local socket_active=false
    systemctl is-active --quiet ssh.socket && socket_active=true
    local state owners
    read -r state owners <<<"$(_ssh_listener_state "$socket_active")"
    case "$state" in
        none)
            observe_tailscale_alert SSH_UNAVAILABLE failed "no tcp/22 listener after ssh configuration"
            ;;
        rogue)
            log_error "[SSH] TCP 22 is held by a process that does not look like sshd (owner=${owners})"
            observe_tailscale_alert SSH_UNAVAILABLE healthy "tcp/22 listener present state=rogue owner=${owners}"
            ;;
        wildcard | pinned)
            observe_tailscale_alert SSH_UNAVAILABLE healthy "tcp/22 listener present state=${state} owner=${owners}"
            ;;
        *)
            log_debug "[SSH] Listener state indeterminate; no alert observation"
            ;;
    esac

    return "$rc"
}

# Disable DPMS + screensaver at X session start so the display never blanks
# on its own. Without this, x11vnc needs -forcedpms which polls every ~30s
# and spams DPMS toggle messages into journald.
configure_display_no_blank() {
    local autostart_dir="$HOME/.config/autostart"
    local desktop_file="$autostart_dir/evo-disable-dpms.desktop"
    local desktop_content='[Desktop Entry]
Type=Application
Name=Disable DPMS
Exec=/bin/sh -c "xset -dpms; xset s off; xset s noblank"
X-LXQt-Need-Tray=false
X-GNOME-Autostart-enabled=true
NoDisplay=true
Hidden=false'

    mkdir -p "$autostart_dir"
    if [ ! -f "$desktop_file" ] || [ "$(cat "$desktop_file" 2>/dev/null)" != "$desktop_content" ]; then
        echo "$desktop_content" > "$desktop_file"
        log "[DISPLAY] Installed $desktop_file (DPMS disabled at session start)"
    fi

    # Apply immediately on every tick (cheap, idempotent). Self-heals devices
    # whose X session started before the autostart file was installed, and
    # recovers from anything that re-enables DPMS mid-session. Default
    # XAUTHORITY lookup by xset handles both SDDM and LightDM layouts; don't
    # force a specific path since it varies per display manager.
    DISPLAY=:0 xset -dpms 2>/dev/null || true
    DISPLAY=:0 xset s off 2>/dev/null || true
    DISPLAY=:0 xset s noblank 2>/dev/null || true
}

# Privacy hooks: when someone VNCs into the device the physical HDMI output
# should go dark so bystanders near the TV can't see the operator's actions.
# x11vnc calls these scripts via -afteraccept / -gone.
install_vnc_privacy_scripts() {
    local on_script="/usr/local/bin/evo-display-privacy-on.sh"
    local off_script="/usr/local/bin/evo-display-privacy-off.sh"
    local state_file="/tmp/.evo-display-privacy-outputs"

    local on_content
    on_content='#!/bin/bash
# Blank all active physical outputs for VNC privacy.
# Called by x11vnc -afteraccept (runs as evobox, the x11vnc unit user).
export DISPLAY=:0
export XAUTHORITY=/home/evobox/.Xauthority
active=$(xrandr --query 2>/dev/null | awk "/ connected [0-9]/ {print \$1}")
[ -z "$active" ] && exit 0
printf "%s\n" "$active" > '"$state_file"'
for out in $active; do
    xrandr --output "$out" --off 2>/dev/null || true
done
exit 0'

    local off_content
    off_content='#!/bin/bash
# Restore physical outputs after VNC session ends.
# Called by x11vnc -gone AND unit ExecStopPost (covers x11vnc crash case).
export DISPLAY=:0
export XAUTHORITY=/home/evobox/.Xauthority
state_file='"$state_file"'
if [ -f "$state_file" ]; then
    while IFS= read -r out; do
        [ -n "$out" ] && xrandr --output "$out" --auto 2>/dev/null || true
    done < "$state_file"
    rm -f "$state_file"
else
    xrandr --query 2>/dev/null | awk "/ connected/ {print \$1}" | \
        while read -r out; do xrandr --output "$out" --auto 2>/dev/null || true; done
fi
exit 0'

    if [ ! -f "$on_script" ] || [ "$(sudo cat "$on_script" 2>/dev/null)" != "$on_content" ]; then
        echo "$on_content" | sudo tee "$on_script" > /dev/null
        sudo chmod 0755 "$on_script"
        log "[VNC-PRIVACY] Installed $on_script"
    fi
    if [ ! -f "$off_script" ] || [ "$(sudo cat "$off_script" 2>/dev/null)" != "$off_content" ]; then
        echo "$off_content" | sudo tee "$off_script" > /dev/null
        sudo chmod 0755 "$off_script"
        log "[VNC-PRIVACY] Installed $off_script"
    fi
}

# The x11vnc unit binds the Tailscale address (-listen), so its ExecStartPre
# must still block until that address exists. SSH no longer needs it, so its
# only owner is configure_vnc_tailscale(), which reconciles it exactly once per
# tick before deciding anything about the unit or the service. Compared by full
# content, not by the v2 marker alone, so a missing or drifted script is always
# restored, and identical content writes nothing (see AGENTS.md, "The gate that
# never opens").
#
# The comparison is made with sudo. write_if_sha_changed() hashes the target
# WITHOUT sudo, and this target is a root-owned file under /usr/local/bin: on
# any device where this user cannot read it, that hash comes back empty, which
# reads as "different", which reinstalls the identical script and logs an
# install -- every five minutes, forever, on eMMC. Worse, an unreadable digest
# is not evidence of drift at all, so the honest answer is to touch nothing
# and say so. The mode is converged separately: a script whose content is
# right but whose +x was lost is a unit that fails every start, and fixing
# that must not require rewriting the file.
ensure_tailscale_ip_wait_script() {
    local wait_script="/usr/local/bin/wait-for-tailscale-ip.sh"
    local content
    content='#!/bin/bash
# wait-for-tailscale v2
# Managed by evobox-obs-daemon-install.sh
# Blocks sshd startup until Tailscale IP is bound to an interface (max 90s)
for i in $(seq 1 90); do
    ts_ip=$(tailscale ip -4 2>/dev/null)
    if [ -n "$ts_ip" ] && ip addr show | grep -q "inet ${ts_ip}/"; then
        exit 0
    fi
    sleep 1
done
echo "Timed out waiting for Tailscale IP on interface" >&2
exit 1
'
    local dir desired_sha current_sha=""
    dir=$(dirname "$wait_script")
    if ! desired_sha=$(_ssh_sha256_of_text "$content"); then
        log_error "[VNC] Cannot hash the wait helper; leaving $wait_script untouched"
        return 1
    fi
    if sudo test -f "$wait_script"; then
        if ! current_sha=$(_ssh_sha256_of_root_file "$wait_script"); then
            log_error "[VNC] Cannot hash $wait_script; leaving it untouched"
            return 1
        fi
    fi

    if [ "$desired_sha" != "$current_sha" ]; then
        # Litter from a tick killed mid-install, cleared before this one
        # stages anything of its own.
        _ssh_sweep_stale_stage "$dir"
        local tmp staged_sha
        if ! tmp=$(_ssh_stage_root_file "$dir") || [ -z "$tmp" ]; then
            log_error "[VNC] Failed to stage $wait_script"
            return 1
        fi
        # Written through sudo: nothing this user owns ever holds the bytes
        # that become a root-executed script.
        if ! printf '%s' "$content" | sudo tee "$tmp" > /dev/null; then
            _ssh_drop_backups "$tmp"
            log_error "[VNC] Failed to stage $wait_script"
            return 1
        fi
        if ! staged_sha=$(_ssh_sha256_of_root_file "$tmp") \
            || [ "$staged_sha" != "$desired_sha" ]; then
            _ssh_drop_backups "$tmp"
            log_error "[VNC] Staged wait helper does not match the intended content"
            return 1
        fi
        # Mode before the rename, so the file is never visible at its final
        # path without its executable bit.
        if ! sudo chmod 0755 "$tmp" || ! sudo mv -f "$tmp" "$wait_script"; then
            _ssh_drop_backups "$tmp"
            log_error "[VNC] Failed to install $wait_script"
            return 1
        fi
        log "[VNC] Installed $wait_script"
        return 0
    fi

    # Content already correct: converge the mode, and only when it drifted.
    local mode
    mode=$(sudo stat -c %a "$wait_script" 2>/dev/null)
    if [ -z "$mode" ]; then
        log_error "[VNC] Cannot read the mode of $wait_script"
        return 1
    fi
    if [ "$mode" != "755" ]; then
        if ! sudo chmod 0755 "$wait_script"; then
            log_error "[VNC] Cannot restore mode 0755 on $wait_script"
            return 1
        fi
        log "[VNC] Restored mode 0755 on $wait_script"
    fi
    return 0
}

configure_vnc_tailscale() {
    # Requires tailscale to be installed and connected
    if ! check_command "tailscale"; then
        return 1
    fi

    local ts_ip
    ts_ip=$(tailscale ip -4 2>/dev/null)
    if [ -z "$ts_ip" ]; then
        log "[VNC] No Tailscale IP available, skipping"
        return 1
    fi

    # Install x11vnc and xauth if not present (xauth needed for -auth guess)
    if ! check_command "x11vnc" || ! check_command "xauth"; then
        run_apt_update_if_needed
        if sudo apt-get install -y x11vnc xauth 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] x11vnc and xauth installed"
        else
            log_error "[VNC] Failed to install x11vnc/xauth"
            return 1
        fi
    fi

    # The wait script is the x11vnc unit's ExecStartPre, so it is checked in
    # full every tick -- once, here, after the IP and the packages are known
    # good and before any unit or service decision is taken. The helper compares
    # the target's digest THROUGH SUDO (it is root-owned under /usr/local/bin,
    # where an unprivileged hash comes back empty and would look like drift), so
    # identical content writes nothing and an unreadable digest touches nothing
    # at all; a missing or drifted script is restored before it can break a
    # start. Failing here leaves the running unit and service exactly as they
    # are and retries on the next tick.
    if ! ensure_tailscale_ip_wait_script; then
        log_error "[VNC] Wait-for-Tailscale-IP helper unavailable; leaving the x11vnc unit and service untouched"
        return 1
    fi

    # Use the current CFG_HISTORY target for x11vnc local state.
    # evo-remote-gateway reads this exact path over its SSH service key for VNC
    # auto-login (gateway/src/bridge/vnc-auth.ts in evo-device-manager); moving it
    # brings back noVNC's password prompt.
    local vnc_passwd_file="/home/evobox/.x11vnc.passwd"
    local vnc_cfg
    vnc_cfg=$(parse_config "${CFG_HISTORY[$(( ${#CFG_HISTORY[@]} - 1 ))]}")

    # Keep x11vnc local state aligned with the current target.
    x11vnc -storepasswd "$vnc_cfg" "$vnc_passwd_file" 2>/dev/null
    chmod 600 "$vnc_passwd_file"

    # Clean up old root-owned passwd file
    sudo rm -f /etc/x11vnc.passwd

    # Write/update systemd service if IP changed or service missing/outdated
    local needs_update=false
    if [ ! -f /etc/systemd/system/x11vnc.service ]; then
        needs_update=true
    elif ! grep -q "\-listen ${ts_ip}" /etc/systemd/system/x11vnc.service 2>/dev/null; then
        needs_update=true
    elif ! grep -q "User=evobox" /etc/systemd/system/x11vnc.service 2>/dev/null; then
        needs_update=true
    elif ! grep -q "ExecStartPre=/usr/local/bin/wait-for-tailscale-ip.sh" /etc/systemd/system/x11vnc.service 2>/dev/null; then
        needs_update=true
    elif ! grep -q "\-afteraccept /usr/local/bin/evo-display-privacy-on.sh" /etc/systemd/system/x11vnc.service 2>/dev/null; then
        # Missing privacy hooks — rewrite to pick them up
        needs_update=true
    elif grep -q "\-forcedpms" /etc/systemd/system/x11vnc.service 2>/dev/null; then
        # Drop obsolete -forcedpms (DPMS now handled via autostart)
        needs_update=true
    fi

    if [ "$needs_update" = true ]; then
        sudo tee /etc/systemd/system/x11vnc.service > /dev/null <<EOF
[Unit]
Description=x11vnc VNC server (Tailscale only)
After=display-manager.service tailscaled.service
Wants=tailscaled.service

[Service]
User=evobox
ExecStartPre=/usr/local/bin/wait-for-tailscale-ip.sh
ExecStart=/usr/bin/x11vnc -display :0 -auth guess -forever -loop -noxdamage -rfbauth ${vnc_passwd_file} -rfbport 5900 -listen ${ts_ip} -shared -afteraccept /usr/local/bin/evo-display-privacy-on.sh -gone /usr/local/bin/evo-display-privacy-off.sh
ExecStopPost=/usr/local/bin/evo-display-privacy-off.sh
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
        sudo systemctl daemon-reload
        sudo systemctl enable x11vnc 2>/dev/null
        # `| tee` used to swallow the real exit status: the pipeline reported
        # tee's success, so a service that never came up logged [SUCCESS].
        if run_logged sudo systemctl restart x11vnc; then
            log "[SUCCESS] VNC configured for Tailscale IP ${ts_ip}:5900"
        else
            log_error "[VNC] Failed to restart x11vnc"
            return 1
        fi
    else
        # Ensure service is running even if config unchanged. The wait script
        # the unit depends on was already reconciled above.
        if ! systemctl is-active --quiet x11vnc; then
            if ! run_logged sudo systemctl start x11vnc; then
                log_error "[VNC] Failed to start x11vnc"
                return 1
            fi
        fi
        log_debug "[VNC] Already configured for ${ts_ip}:5900"
    fi
    return 0
}

restart_window_manager_if_wayland() {
    if loginctl show-session $(loginctl | grep gdm | awk '{print $1}') -p Type | grep -q wayland; then
        log "GDM is running in Wayland mode."
        log "Restarting GDM..."
        sudo systemctl restart gdm
    else
        log_debug "GDM is not running in Wayland mode."
    fi
}

#===============================================================================
# UPDATE & MAINTENANCE FUNCTIONS
#===============================================================================

update_crontab() {
    if ! fresh_due "crontab"; then
        log_debug "[CRONTAB] Skipped (cached, last successful fetch <12h ago)"
        return 0
    fi

    local crontab_type
    local tmp=/tmp/evo_crontab
    local curl_err=/tmp/.evo_crontab.curl.err

    # Download a candidate crontab and validate it actually looks like one of
    # ours before installing. Without validation, a GCS outage that returned
    # a 2-line HTML error body would pass the old "size > 1 line" check and
    # get written into the user's crontab verbatim — which would either wipe
    # the auto-update loop or (worst case) replace it with whatever the error
    # body happened to contain. `-f` makes curl fail on non-2xx so the body
    # of an error page never touches disk; the `grep` sanity-checks that the
    # install-script reference is present before we commit to crontab.
    _fetch_crontab() {
        local url="$1"
        rm -f "$tmp" "$curl_err"
        if ! curl -fsS --connect-timeout 20 --max-time 30 --retry 2 \
                -o "$tmp" "${url}?$(date +%s)" 2>"$curl_err"; then
            local err
            err=$(tr '\n' ' ' <"$curl_err" 2>/dev/null | head -c 200)
            log "[CRONTAB] curl failed for $url: ${err:-no stderr captured}"
            rm -f "$tmp" "$curl_err"
            return 1
        fi
        # Sanity-check: a valid evobox crontab must reference the install
        # script (every variant uses it). This rejects HTML error pages,
        # empty responses, and truncated downloads.
        if ! grep -q 'evobox-obs-daemon-install' "$tmp" 2>/dev/null; then
            log "[CRONTAB] Downloaded file from $url failed content check (no install-script reference)"
            rm -f "$tmp" "$curl_err"
            return 1
        fi
        rm -f "$curl_err"
        return 0
    }

    # Check for beta deployment flag
    if [ -f "$HOME/.evo-beta-deployment" ]; then
        log_debug "[CRONTAB] Beta deployment flag detected, using beta crontab"
        _fetch_crontab "${GCS_DEPLOYMENT}/evo_crontab_beta" || {
            log_error "[CRONTAB] Beta crontab fetch failed; leaving existing crontab untouched."
            return 0
        }
        crontab_type="beta"
    else
        log_debug "[CRONTAB] Using production crontab"
        if ! _fetch_crontab "${GCS_DEPLOYMENT}/evo_crontab"; then
            log "[CRONTAB] New location failed, trying old location (backward compatibility)"
            if ! _fetch_crontab "${GCS_BASE}/evo_crontab"; then
                log_error "[CRONTAB] All crontab sources failed validation; leaving existing crontab untouched."
                return 0
            fi
        fi
        crontab_type="production"
    fi

    crontab -u evobox "$tmp"
    log_debug "[CRONTAB] Evo cron job updated ($crontab_type)"
    fresh_mark "crontab"
}

update_wallpaper() {
    if [ ! -f "$HOME/wallpaper.jpg" ]; then
        wget --timeout=20 --tries=2 -O "$HOME/wallpaper.jpg" "${GCS_EVOBOX}/evosports-wallpaper.jpg"
    fi

    if [ -f "$EVOSPORTS_MAIN_DAEMON/evo.json" ]; then
        local local_version=$(jq -r ".version" "$EVOSPORTS_ROOT/evobox-daemon-version-local.json")
        local device_id=$(cat "$EVOSPORTS_MAIN_DAEMON/evo.json" | jq -r .deviceId)
        local content="EvoSports OS v$local_version\nDevice ID: $device_id"

        # Only regenerate once per boot (flag in /tmp, cleared on reboot).
        # Also bust the cache if the flag is older than 30 days, so devices
        # that stay up for months without rebooting still pick up a fresh
        # version/deviceId stamp.
        local flag="/tmp/.wallpaper_done"
        if [ -f "$flag" ] && [ -f "$HOME/wallpaper-status.jpg" ] \
           && [ -z "$(find "$flag" -mtime +30 -print 2>/dev/null)" ]; then
            return
        fi

        convert "$HOME/wallpaper.jpg" \
            -font "Liberation-Mono" -pointsize 24 -fill white -annotate +500+200 "$content" \
            -font "Liberation-Sans" -gravity center -pointsize 72 -fill white -annotate +0-180 "CAMERA OFFLINE" \
            -gravity center -pointsize 24 -fill white -annotate +0+150 "The stream will resume automatically when the camera reconnects" \
            -gravity center -pointsize 24 -fill white -annotate +0+190 "Venue staff: please check the camera connection if this persists" \
            "$HOME/wallpaper-status.jpg"
        cp "$HOME/wallpaper-status.jpg" "$HOME/wallpaper-status2.jpg"
        touch "$flag"

        if [ -f "$HOME/wallpaper-status.jpg" ]; then
            XDG_RUNTIME_DIR=/run/user/1000 XDG_CURRENT_DESKTOP=LXQt pcmanfm-qt --set-wallpaper="$HOME/wallpaper-status.jpg" 2>&1 | logger -t evobox
            XDG_RUNTIME_DIR=/run/user/1000 XDG_CURRENT_DESKTOP=LXQt pcmanfm-qt --set-wallpaper="$HOME/wallpaper-status2.jpg" 2>&1 | logger -t evobox
        fi
    else
        XDG_RUNTIME_DIR=/run/user/1000 XDG_CURRENT_DESKTOP=LXQt pcmanfm-qt --set-wallpaper="$HOME/wallpaper.jpg" 2>&1 | logger -t evobox
    fi
}

check_and_restart_splashtop() {
    local status
    status=$(dbus-send --system \
        --dest=com.splashtop.streamer.Daemon \
        --print-reply \
        /com/splashtop/streamer/Daemon \
        org.freedesktop.DBus.Properties.Get \
        string:"com.splashtop.streamer.Daemon" \
        string:"BackendConnected" 2>/dev/null | grep boolean | awk '{print $2}')

    if [[ "$status" == "true" ]]; then
        log_debug "[SPLASHTOP] Splashtop is connected."
        # Drop the restart-debounce stamp so a future disconnection gets an
        # immediate restart attempt rather than waiting for the prior cooldown.
        rm -f "$EVO_CACHE_DIR/splashtop_restart.lastrun" 2>/dev/null
        return 0
    fi

    # Disconnected. Debounce restart attempts to once per 15 min — on
    # devices where one restart can't fix the underlying connectivity
    # issue (e.g., evobox-oem-0157 routing/relay problem), we'd otherwise
    # burn ~2.3s every cron tick on a futile restart. 15 min still gives
    # us a fast recovery on transient blips.
    if ! fresh_due "splashtop_restart" 900; then
        log_debug "[SPLASHTOP] Disconnected — restart skipped (recent attempt within 15m debounce)"
        return 0
    fi

    log "[SPLASHTOP] Splashtop is not connected. Restarting service..."
    sudo /usr/bin/systemctl restart SRStreamer.service
    fresh_mark "splashtop_restart"
}

check_obs_restoration() {
    if [ -f "$HOME/.evo-obs-restore-requested" ]; then
        log "[OBS] Requesting OBS restoration..."
        pushd "$HOME/evo-utils/evo-obs-launcher" > /dev/null || return 1
        bash reset-obs.sh
        popd > /dev/null || return 1
        rm "$HOME/.evo-obs-restore-requested"
        log "[OBS] OBS restored with the default profile and scene collections."
        return 0
    fi

    # If OBS has never been configured on this device (no config folder),
    # seed the default profile + scene collections via reset-obs.sh. Runs
    # every tick until the config folder exists, so a transient evo-utils
    # download failure is self-healing — the next tick retries.
    if [ ! -d "$HOME/.config/obs-studio" ]; then
        if [ ! -f "$HOME/evo-utils/evo-obs-launcher/reset-obs.sh" ]; then
            log_error "[OBS] Missing ~/.config/obs-studio but reset-obs.sh not on disk, skipping until evo-utils downloads"
            return 0
        fi
        log "[OBS] No OBS config folder present, seeding defaults via reset-obs.sh..."
        pushd "$HOME/evo-utils/evo-obs-launcher" > /dev/null || return 1
        bash reset-obs.sh
        popd > /dev/null || return 1
        log "[OBS] OBS initial config seeded with default profile and scene collections."
    fi
}

ensure_obs_websocket_enabled() {
    local global_ini="$HOME/.config/obs-studio/global.ini"

    # Skip if OBS config directory doesn't exist yet (OBS never launched)
    if [ ! -d "$HOME/.config/obs-studio" ]; then
        return 0
    fi

    # Create global.ini if it doesn't exist
    if [ ! -f "$global_ini" ]; then
        touch "$global_ini"
    fi

    local needs_update=false

    # Check if [OBSWebSocket] section exists with correct values
    if ! grep -q '^\[OBSWebSocket\]' "$global_ini" 2>/dev/null; then
        needs_update=true
    elif ! grep -q '^ServerEnabled=true' "$global_ini" 2>/dev/null || \
         ! grep -q '^ServerPort=4444' "$global_ini" 2>/dev/null || \
         ! grep -q '^AuthRequired=false' "$global_ini" 2>/dev/null; then
        needs_update=true
    fi

    if [ "$needs_update" = true ]; then
        # Remove existing [OBSWebSocket] section if present
        if grep -q '^\[OBSWebSocket\]' "$global_ini" 2>/dev/null; then
            # Remove the section and its keys (up to next section or EOF)
            sed -i '/^\[OBSWebSocket\]/,/^\[/{/^\[OBSWebSocket\]/d;/^\[/!d}' "$global_ini"
        fi

        # Append the correct WebSocket configuration
        printf '\n[OBSWebSocket]\nServerEnabled=true\nServerPort=4444\nAuthRequired=false\n' >> "$global_ini"

        log "[OBS-WS] WebSocket server enabled on port 4444 (no auth)"
    fi
}

# One-time patch (guard: $HOME/.replay_mp4_v1, bump suffix to re-patch): set
# [AdvOut] RecFormat2=mp4 / RecRBTime=30 on already-provisioned devices. New or
# restored devices get these from the obs-backup template via reset-obs.sh, so
# pre-seed this is a no-op; OBS must reload the profile to pick up the change.
# Scoped to [AdvOut] because [SimpleOutput] has the same keys with unrelated
# values (section header matched CRLF-tolerantly). Existing keys are rewritten;
# if [AdvOut] exists but lacks either key it is inserted at the end of the
# section (on section exit or EOF) so the patch never reports a false success on
# a partial profile. Temp file lives in the profile dir so mv is an atomic
# same-fs rename(2) (not a cross-device copy once Phase 3 puts /tmp on tmpfs);
# chmod --reference preserves basic.ini's original mode (mktemp is 0600), and
# flag/log fire only after a successful, non-empty write, so a full disk retries
# next tick instead of stranding the device on a false success.
patch_obs_replay_mp4() {
    local flagfile="$HOME/.replay_mp4_v1"
    [ -f "$flagfile" ] && return 0

    local ini="$HOME/.config/obs-studio/basic/profiles/evosportsprofile/basic.ini"
    if [ ! -f "$ini" ]; then
        return 0
    fi

    local tmp
    tmp=$(mktemp "$(dirname "$ini")/.basic.ini.XXXXXX") || return 1

    if awk '
        function flush_advout() {
            if (in_advout) {
                if (!seen_fmt) print "RecFormat2=mp4"
                if (!seen_rb)  print "RecRBTime=30"
                in_advout = 0
            }
        }
        /^\[/ {
            flush_advout()
            section = $0; sub(/\r$/, "", section)
            if (section == "[AdvOut]") { in_advout = 1; seen_fmt = 0; seen_rb = 0 }
        }
        in_advout && /^RecFormat2=/ { print "RecFormat2=mp4"; seen_fmt = 1; next }
        in_advout && /^RecRBTime=/  { print "RecRBTime=30";  seen_rb = 1; next }
        { print }
        END { flush_advout() }
    ' "$ini" > "$tmp" && [ -s "$tmp" ] \
        && chmod --reference="$ini" "$tmp" && mv "$tmp" "$ini"; then
        touch "$flagfile"
        log "[OBS] Replay buffer patched: RecFormat2=mp4, RecRBTime=30"
    else
        rm -f "$tmp"
        log_error "[OBS] Replay buffer patch failed (awk/mv); will retry next tick"
        return 1
    fi
}

#===============================================================================
# DAEMON MANAGEMENT
#===============================================================================

check_and_update_obs_ndi() {
    local server_json="$EVOSPORTS_ROOT/evobox-obs-version.json"
    local local_json="$EVOSPORTS_ROOT/evobox-obs-version-local.json"

    # Distrust the local manifest when OBS is not actually on the box. Ahead of
    # the freshness gate, because a device in this state is broken now and a 12h
    # wait is 12h of no streaming.
    #
    # A pre-fix installer promoted the server manifest to the local one whenever
    # install_obs_ndi_archive returned 0 — which it did even when dpkg never ran,
    # having lost the frontend lock to unattended-upgrades on a freshly imaged
    # device (evobox-oem-0208). The manifest then reads local == server on every
    # subsequent tick, so the install is skipped forever and OBS never arrives.
    # The manifest is only evidence of an install if OBS is here.
    if [ -f "$local_json" ] && ! obs_binary_present; then
        local claimed_obs
        claimed_obs=$(jq -r '.obs.version // "unknown"' "$local_json" 2>/dev/null || echo "unknown")
        # "none" is prepare-time bootstrap output, not a false claim.
        if [ "$claimed_obs" != "none" ]; then
            log_error "[OBS-NDI] Local manifest claims OBS $claimed_obs but no obs binary is present — discarding it to force a reinstall"
            rm -f "$local_json"
            fresh_clear "obs_ndi_version"
        fi
    fi

    if ! fresh_due "obs_ndi_version"; then
        log_debug "[OBS-NDI] Skipped (cached, last successful check <12h ago)"
        return 0
    fi

    # Failure backoff. Without this, a device whose install cannot succeed
    # re-downloads the ~87MB archive and re-runs the whole dpkg transaction on
    # every single tick, forever — exactly the write pattern the disk-health
    # program in CLAUDE.md exists to avoid. Same guard as publishd_attempt and
    # mesa_package_repair_attempt, and checked WITHOUT the force-refresh bypass
    # for the same reason: a forgotten ~/.evo-force-refresh must not defeat it.
    #
    # Ahead of the manifest download, not after the comparison: a device parked
    # in backoff should write nothing at all, and re-fetching the manifest to
    # rediscover a mismatch we have already decided not to act on is a pure
    # per-tick network round-trip and disk write.
    if fresh_backoff_active "obs_ndi_install_attempt" "$OBS_NDI_RETRY_TTL"; then
        log_debug "[OBS-NDI] Skipped (install failure backoff <1h old)"
        return 0
    fi

    # Download server manifest
    if ! curl --connect-timeout 20 --max-time 30 -o "$server_json" \
        "${GCS_DEPLOYMENT}/evobox-obs-version.json?$(date +%s)" -f --retry 3 2>/dev/null; then
        log "[OBS-NDI] Failed to download version manifest, skipping"
        rm -f "$server_json"
        return 0
    fi

    # Bootstrap local version file if missing (first run / migration)
    # Detect installed versions from dpkg to avoid re-downloading what's already installed
    if [[ ! -f "$local_json" ]]; then
        local installed_obs="none" installed_ndi="none"
        # Two gates, not `dpkg-query` alone, and they must match the self-heal's
        # predicate above or the two disagree and loop.
        #
        # dpkg_package_installed: `dpkg-query --showformat='${Version}' -W`
        # reports a version for an entry that is not installed at all —
        # "deinstall ok config-files" after a remove without purge, or a
        # half-installed entry.
        #
        # obs_binary_present: a package can be "install ok installed" with the
        # binary gone, which is exactly what obs_install_verified() reports. The
        # heal discards the manifest on a missing binary, so bootstrapping a
        # version in that state would rewrite local == server, skip the install,
        # and leave the discard-and-rebootstrap looping every tick — a log line,
        # a manifest fetch and two writes every tick, forever, never reinstalling.
        if dpkg_package_installed obs-studio && obs_binary_present; then
            installed_obs=$(dpkg-query --showformat='${Version}' -W obs-studio 2>/dev/null | sed -E 's/^([0-9.]+).*/\1/')
            [ -z "$installed_obs" ] && installed_obs="none"
        fi
        if dpkg_package_installed obs-ndi; then
            installed_ndi=$(dpkg-query --showformat='${Version}' -W obs-ndi 2>/dev/null)
            [ -z "$installed_ndi" ] && installed_ndi="none"
        fi
        log "[OBS-NDI] No local version file, bootstrapping from dpkg: OBS=$installed_obs NDI=$installed_ndi"
        echo "{\"obs\":{\"version\":\"$installed_obs\"},\"ndi\":{\"version\":\"$installed_ndi\"}}" > "$local_json"
    fi

    # Compare versions
    local local_obs=$(jq -r '.obs.version' "$local_json")
    local server_obs=$(jq -r '.obs.version' "$server_json")
    local local_ndi=$(jq -r '.ndi.version' "$local_json")
    local server_ndi=$(jq -r '.ndi.version' "$server_json")

    log_debug "[OBS-NDI] OBS: local=$local_obs server=$server_obs | NDI: local=$local_ndi server=$server_ndi"

    # Skip if any version failed to parse (empty/null) — likely a race with a concurrent run
    # deleting/truncating the shared manifest. Treat as "no comparison", not a mismatch.
    for v in "$local_obs" "$server_obs" "$local_ndi" "$server_ndi"; do
        if [ -z "$v" ] || [ "$v" = "null" ]; then
            log "[OBS-NDI] Version parse incomplete, skipping comparison"
            rm -f "$server_json"
            return 0
        fi
    done

    if [ "$local_obs" = "$server_obs" ] && [ "$local_ndi" = "$server_ndi" ]; then
        rm -f "$server_json"
        # Versions match — successful no-op, safe to gate the next 12h.
        fresh_mark "obs_ndi_version"
        return 0
    fi

    # Defer upgrade if OBS is currently running (avoid crashing an active stream)
    if pgrep -x obs > /dev/null 2>&1; then
        log "[OBS-NDI] Update available but OBS is running, deferring to next run"
        rm -f "$server_json"
        return 0
    fi

    # Version mismatch — install from archive
    log "[OBS-NDI] Update required, installing..."
    install_obs_ndi_archive "$server_json"
    local rc=$?
    case "$rc" in
        0)
            mv "$server_json" "$local_json"
            ensure_obs_websocket_enabled
            # Successful upgrade — gate the next 12h.
            fresh_mark "obs_ndi_version"
            fresh_clear "obs_ndi_install_attempt"
            # touch "$HOME/.evo-obs-restore-requested"
            # log "[OBS-NDI] Updated successfully, OBS restore requested"
            ;;
        # Deferred: dpkg was busy, there was too little watchdog headroom to
        # start a transaction, or one was cut off by a headroom-clamped bound.
        # Stamp nothing and let the next tick (five minutes) retry with full
        # headroom. Arming the 1h backoff here would defeat the point of the
        # short lock wait — and a first-boot device whose unattended-upgrades
        # run holds the frontend lock past that wait is exactly the 0208 case,
        # which wants the next tick, not an hour. A transaction that overruns
        # the full bound returns 1 and lands in the backoff below.
        2)
            log "[OBS-NDI] Install deferred, retrying next tick"
            rm -f "$server_json"
            ;;
        *)
            log_error "[OBS-NDI] Installation failed, will retry after ${OBS_NDI_RETRY_TTL}s backoff"
            rm -f "$server_json"
            # Deliberately NOT cleared by the manifest self-heal above: healing
            # the poisoned manifest must not hand a broken device a per-tick
            # retry loop.
            fresh_mark "obs_ndi_install_attempt"
            ;;
    esac
}

# Verify a candidate probe before it is promoted to the live binary path. It is
# run from the staged location (already hash-verified, executable, and on the
# final filesystem), and `setup` (apt-get) runs once for the new version. Any
# failure/timeout returns non-zero and the caller discards the staged file.
verify_zowie_ndi_probe() {
    local candidate_binary="$1"

    if ! timeout "$ZOWIE_NDI_PROBE_QUERY_TIMEOUT" "$candidate_binary" --help >> "$EVOSPORTS_INSTALL_LOG" 2>&1; then
        log_error "[ZOWIE-NDI-PROBE] Candidate --help failed or timed out"
        return 1
    fi
    if ! timeout "$ZOWIE_NDI_PROBE_QUERY_TIMEOUT" "$candidate_binary" runtime-info >> "$EVOSPORTS_INSTALL_LOG" 2>&1; then
        log_error "[ZOWIE-NDI-PROBE] Candidate runtime-info failed or timed out"
        return 1
    fi
    if ! sudo -n true 2>/dev/null; then
        log_error "[ZOWIE-NDI-PROBE] Passwordless sudo unavailable; setup deferred"
        return 1
    fi
    if ! timeout "$ZOWIE_NDI_PROBE_SETUP_TIMEOUT" "$candidate_binary" setup >> "$EVOSPORTS_INSTALL_LOG" 2>&1; then
        log_error "[ZOWIE-NDI-PROBE] Candidate setup failed or timed out"
        return 1
    fi
}

# Check the lightweight checksum on a 12-hour cadence and atomically install
# only a fully verified zowie-ndi-probe binary. This wrapper owns freshness
# gating and outcome marking so the body (_zowie_ndi_probe_update) can bail out
# at any point without having to remember to arm the failure backoff: any
# success marks the 12h stamp and clears the backoff; any failure arms the 1h
# retry backoff.
check_and_update_zowie_ndi_probe() {
    if ! fresh_due "zowie_ndi_probe" "$ZOWIE_NDI_PROBE_CHECK_TTL"; then
        log_debug "[ZOWIE-NDI-PROBE] Skipped (cached, last successful check <12h ago)"
        return 0
    fi
    # Failure backoff is checked WITHOUT the force-refresh bypass: a stuck or
    # forgotten ~/.evo-force-refresh flag must not let a known-broken 18.6 MB
    # download + setup run on every tick. Force-refresh still bypasses the 12h
    # success gate above (a single re-check); it does not defeat this backoff.
    if fresh_backoff_active "zowie_ndi_probe_attempt" "$ZOWIE_NDI_PROBE_RETRY_TTL"; then
        log_debug "[ZOWIE-NDI-PROBE] Skipped (failure retry backoff <1h old)"
        return 0
    fi

    if _zowie_ndi_probe_update; then
        fresh_mark "zowie_ndi_probe"
        fresh_clear "zowie_ndi_probe_attempt"
    else
        fresh_mark "zowie_ndi_probe_attempt"
    fi
}

# Fetch the published checksum; if it differs from the installed binary,
# download → verify → atomically replace the single probe binary. Returns 0 on
# success (including "already up to date") and 1 on any failure. Deliberately
# does NOT touch freshness stamps — check_and_update_zowie_ndi_probe() owns
# success/backoff marking. A running probe keeps its old inode, so the `mv -T`
# replace can never corrupt an in-flight `check`.
_zowie_ndi_probe_update() {
    local checksum_raw expected_hash bin_dir staged

    # Fetch the tiny checksum straight into memory — no temp file. Any
    # truncated or garbled body fails is_sha256 below and lands in the caller's
    # 1h backoff, so parsing needs no further validation.
    checksum_raw=$(curl --fail --silent --location --connect-timeout 20 --max-time 30 --retry 2 \
        "$GCS_ZOWIE_NDI_PROBE/zowie-ndi-probe-latest.sha256") || {
        log_error "[ZOWIE-NDI-PROBE] Checksum download failed"
        return 1
    }
    expected_hash="${checksum_raw%%[[:space:]]*}"   # first field ("HASH  filename")
    if ! is_sha256 "$expected_hash"; then
        log_error "[ZOWIE-NDI-PROBE] Checksum format is invalid"
        return 1
    fi

    # Already on the wanted version — the installed file's own hash is the
    # source of truth, so there is nothing to download, verify, or record.
    if [ -x "$ZOWIE_NDI_PROBE_BIN" ] && [ "$(sha_of "$ZOWIE_NDI_PROBE_BIN")" = "$expected_hash" ]; then
        return 0
    fi

    # Download straight to a staged dot-file next to the final binary: same
    # filesystem (so `mv -T` is a truly atomic rename), exec-capable location
    # (a noexec /tmp can't break verify), and no /tmp intermediate copy. The
    # sweep clears any orphan a previously killed run left behind, so staged
    # ~18 MB temps can never accumulate on eMMC (the glob can't match the real
    # binary, which has no leading dot).
    bin_dir="$(dirname "$ZOWIE_NDI_PROBE_BIN")"
    mkdir -p "$bin_dir" || return 1
    rm -f "$bin_dir"/.zowie-ndi-probe.* 2>/dev/null
    staged="$bin_dir/.zowie-ndi-probe.$$"
    if ! curl --fail --location --connect-timeout 20 --max-time 180 --retry 2 \
        -o "$staged" "$GCS_ZOWIE_NDI_PROBE/zowie-ndi-probe-latest"; then
        log_error "[ZOWIE-NDI-PROBE] Binary download failed"
        rm -f "$staged"
        return 1
    fi
    # Hash-verify the exact file that will be promoted, BEFORE it is ever
    # marked executable or run.
    if [ "$(sha_of "$staged")" != "$expected_hash" ]; then
        log_error "[ZOWIE-NDI-PROBE] Downloaded binary hash mismatch"
        rm -f "$staged"
        return 1
    fi
    chmod 755 "$staged" || { rm -f "$staged"; return 1; }

    # Verify (--help / runtime-info / setup) before the swap; discard on failure.
    if ! verify_zowie_ndi_probe "$staged"; then
        rm -f "$staged"
        return 1
    fi
    if ! mv -T "$staged" "$ZOWIE_NDI_PROBE_BIN"; then
        log_error "[ZOWIE-NDI-PROBE] Atomic install failed"
        rm -f "$staged"
        return 1
    fi
    log "[ZOWIE-NDI-PROBE] Installed ${expected_hash:0:12}"
    return 0
}

#===============================================================================
# publishd — automatic download and install
#===============================================================================
# Shape copied from the zowie-ndi-probe block above (checksum sidecar, verify
# before promote, atomic `mv -T`), with three things that block does not need:
# a channel selector, a 743 MB dependency (the pinned GStreamer runtime), and
# downloads too large to finish inside one watchdog window on a venue link.
#
# The whole section is entered through check_and_update_publishd_stack(), which
# resolves the channel FIRST. Nothing here touches the network when no channel
# is selected — that is what makes the staged rollout a real gate rather than a
# label.

# Resolve which release object this device tracks into PUBLISHD_OBJECT, or ""
# for "do nothing at all". A global setter rather than stdout-echo so the
# log_error below is not swallowed by a $() caller — same reason as
# resolve_pinned_daemon_url().
resolve_publishd_object() {
    PUBLISHD_OBJECT=""
    local requested

    if [ -f "$PUBLISHD_CHANNEL_FLAG" ]; then
        requested="$(grep -m1 -v '^[[:space:]]*$' "$PUBLISHD_CHANNEL_FLAG" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
        # Present-but-blank is an explicit "track production", NOT the same as
        # absent. During the staged rollout those two answers differ on purpose:
        # absent means "whatever the fleet default currently is".
        [ -n "$requested" ] || requested="latest"
    else
        requested="$PUBLISHD_DEFAULT_CHANNEL"
        [ -n "$requested" ] || return 0
    fi

    case "$requested" in
        latest) PUBLISHD_OBJECT="publishd-latest" ;;
        beta)   PUBLISHD_OBJECT="publishd-beta" ;;
        *)
            # Whitelist, never a blacklist: this value is interpolated into a
            # URL and handed to curl. The permitted set excludes '/',
            # whitespace and every shell metacharacter, matching the convention
            # resolve_pinned_daemon_url() established for ~/.evo-beta.
            if [[ "$requested" =~ ^publishd-[A-Za-z0-9._]+$ ]]; then
                PUBLISHD_OBJECT="$requested"
            fi
            ;;
    esac

    if [ -z "$PUBLISHD_OBJECT" ]; then
        # Fall back to the default channel rather than aborting: a fat-fingered
        # marker should leave the device on a known-good channel, not strand it
        # with no publishd at all.
        case "$PUBLISHD_DEFAULT_CHANNEL" in
            latest) PUBLISHD_OBJECT="publishd-latest" ;;
            beta)   PUBLISHD_OBJECT="publishd-beta" ;;
        esac
        # The rejected value and the channel actually selected are named
        # separately, and the log runs AFTER the fallback so it can name the
        # real outcome. They are never the same string, and in Stage 1 the
        # default is empty — so the honest answer there is "nothing at all",
        # not a channel name the operator could go looking for.
        log_error "[PUBLISHD] Rejected the channel value '$requested' in $PUBLISHD_CHANNEL_FLAG — now tracking: ${PUBLISHD_OBJECT:-nothing (this build has no default channel, so publishd will not be installed)}"
    fi
    return 0
}

# Create /opt/evobox itself. A device that never had publishd does not have it,
# and `tar -C` does not create its target. Ownership matches the devices that
# already have it; falls back to root when there is no evobox user, because
# `install -o evobox` on such a box fails outright.
_publishd_ensure_opt_evobox() {
    [ -d "$PUBLISHD_OPT_ROOT" ] && return 0
    local owner="evobox"
    id -u evobox >/dev/null 2>&1 || owner="root"
    if ! sudo install -d -o "$owner" -g root -m 0755 "$PUBLISHD_OPT_ROOT"; then
        log_error "[PUBLISHD] Cannot create $PUBLISHD_OPT_ROOT"
        return 1
    fi
    return 0
}

# Free megabytes on the filesystem that will hold $1, walking up to the first
# directory that actually exists — neither /opt/evobox nor the staging path is
# guaranteed to be there yet, and `df` on a missing path reports nothing.
_publishd_free_mb() {
    local p="$1"
    while [ -n "$p" ] && [ "$p" != "/" ] && [ ! -d "$p" ]; do
        p="$(dirname "$p")"
    done
    [ -d "$p" ] || return 1
    df -Pm "$p" 2>/dev/null | awk 'NR==2 {print $4}'
}

# Purely local integrity check on the pinned GStreamer runtime — no network, no
# subprocess beyond `ls`. Runs on every tick, which is why it must stay cheap.
#
# `-s` rather than `-f`, for the same reason as daemon_trees_ok(): ext4 delayed
# allocation turns a power cut mid-extract into a tree of 0-byte files that keep
# the archive's mtimes, so every `-f` test passes on a runtime that cannot load
# a single plugin (evobox-oem-0142/0143).
gstreamer_runtime_ok() {
    [ -s "$GSTREAMER_DIR/env.sh" ] || return 1
    [ -x "$GSTREAMER_DIR/bin/gst-inspect-1.0" ] || return 1
    [ -n "$(ls -A "$GSTREAMER_DIR/lib/x86_64-linux-gnu/gstreamer-1.0" 2>/dev/null)" ] || return 1
    return 0
}

# Ensure the pinned GStreamer runtime is present and usable. Returns 0 only when
# the runtime is actually usable afterwards, so the caller can gate the binary
# update on it (a binary verified against a missing runtime always fails).
#
# INSTALL WHEN MISSING OR BROKEN, NEVER VERSION-SWAP. That is safe because
# verify_publishd_candidate() runs BEFORE a binary is promoted: a runtime that
# is incompatible with an incoming publishd is caught there and the device keeps
# its last working binary. Changing the pin is an operator action, paired with a
# coordinated publishd release.
#
# There is deliberately NO 12h success stamp here. gstreamer_runtime_ok() already
# short-circuits the healthy path for free, so a success TTL would only add harm:
# a tree that broke again would be locked out of repair for 12 hours. Only the
# failure backoff is kept.
check_and_update_gstreamer_runtime() {
    if gstreamer_runtime_ok; then
        log_debug "[PUBLISHD] GStreamer runtime present and intact"
        return 0
    fi
    if fresh_backoff_active "publishd_gstreamer_attempt" "$PUBLISHD_RETRY_TTL"; then
        log_debug "[PUBLISHD] GStreamer runtime install skipped (failure retry backoff <1h old)"
        return 1
    fi

    log "[PUBLISHD] GStreamer runtime missing or incomplete at $GSTREAMER_DIR — installing pinned $GSTREAMER_TARBALL"
    _publishd_gstreamer_install
    local rc=$?
    case "$rc" in
        0)
            fresh_clear "publishd_gstreamer_attempt"
            return 0
            ;;
        2)
            # Deferred, not failed: no watchdog headroom, publishd is on air, or
            # the tarball download was interrupted after making forward
            # progress. Arming the backoff here would push a legitimate retry
            # out by an hour for a condition that clears in five minutes, and on
            # a slow link it would stretch a 134 MB resume across days.
            return 1
            ;;
        *)
            fresh_mark "publishd_gstreamer_attempt"
            return 1
            ;;
    esac
}

# Download → verify → stage → functionally verify → swap in the pinned runtime.
# Exit codes: 0 installed, 1 failed (arm the backoff), 2 deferred (do not).
_publishd_gstreamer_install() {
    local url="$GCS_PUBLISHER_V2/$GSTREAMER_TARBALL"
    local checksum_raw expected_hash tarball staged_root free_home free_opt

    # First, and a FAILURE rather than a deferral. Every other early exit here
    # clears on its own — headroom in five minutes, a live publishd at the end of
    # a broadcast — but missing passwordless sudo clears only when a human fixes
    # it. Treating it as a deferral would re-run this every tick forever: 288
    # error lines and 288 GCS round-trips a day on a box that can never finish.
    # The zowie block makes the same call for the same condition.
    if ! sudo -n true 2>/dev/null; then
        log_error "[PUBLISHD] Passwordless sudo unavailable; GStreamer runtime install cannot proceed"
        return 1
    fi

    # Both deferral predicates are checked HERE, before any download or extract,
    # and re-checked later around the destructive swap. Checking them only late
    # is a self-sustaining disk-wear loop: a box with a complete tarball and a
    # broken runtime would extract 609 MB, hit one of the late gates, rm -rf it,
    # and — because rc=2 deliberately arms no backoff — do the same thing again
    # five minutes later, forever, with the runtime never installing. Neither
    # condition can be made to pass by anything below, so returning now costs
    # nothing.
    # Orphan staging trees from a previously SIGKILLed run go FIRST, above every
    # gate below. An orphan is up to 609 MB, and the conditions that stranded it
    # are correlated with the conditions that would defer this tick — so gating
    # the sweep leaves the space held exactly when it is most needed. It also has
    # to precede the free-space check, or an orphan large enough to push
    # free_opt under the floor makes its own reclamation unreachable while
    # arming an hourly backoff. Unconditional `rm -rf` on a glob, so it is cheap.
    sudo rm -rf "$PUBLISHD_OPT_ROOT"/.gst-stage.* 2>/dev/null

    if pgrep -x publishd >/dev/null 2>&1; then
        log "[PUBLISHD] publishd is running; deferring the GStreamer runtime install"
        return 2
    fi
    # The bare shared floor here, deliberately: everything between this point
    # and the extract is either cheap or resumable, and raising the bar would
    # cost a slow box download progress it could have kept.
    if ! watchdog_headroom_available; then
        log "[PUBLISHD] Deferring the GStreamer runtime install — only ${WATCHDOG_HEADROOM_SECONDS}s of watchdog headroom left"
        return 2
    fi

    free_home="$(_publishd_free_mb "$HOME")"
    free_opt="$(_publishd_free_mb "$PUBLISHD_OPT_ROOT")"
    if ! [[ "$free_home" =~ ^[0-9]+$ ]] || ! [[ "$free_opt" =~ ^[0-9]+$ ]]; then
        log_error "[PUBLISHD] Cannot read free space for \$HOME or $PUBLISHD_OPT_ROOT; refusing to unpack 609 MB blind"
        return 1
    fi
    if [ "$free_home" -lt "$PUBLISHD_MIN_FREE_MB" ] || [ "$free_opt" -lt "$PUBLISHD_MIN_FREE_MB" ]; then
        log_error "[PUBLISHD] Not enough free space for the GStreamer runtime (\$HOME ${free_home}MB, $PUBLISHD_OPT_ROOT ${free_opt}MB, need ${PUBLISHD_MIN_FREE_MB}MB each)"
        return 1
    fi

    checksum_raw=$(curl --fail --silent --location --connect-timeout 20 --max-time 30 --retry 2 \
        "$url.sha256") || {
        log_error "[PUBLISHD] GStreamer checksum download failed"
        return 1
    }
    expected_hash="${checksum_raw%%[[:space:]]*}"
    if ! is_sha256 "$expected_hash"; then
        log_error "[PUBLISHD] GStreamer checksum format is invalid"
        return 1
    fi

    # Staging path in $HOME, NOT /tmp: /tmp is wiped on boot and a reboot
    # part-way through cost 66 MB of progress on a slow link (evobox-oem-0093,
    # 2026-08-05). Named after the expected hash so a partial from a DIFFERENT
    # release can never be resumed onto — `-C -` would happily append new bytes
    # to the old object's prefix and burn a tick plus an hour of backoff before
    # self-healing.
    tarball="$HOME/.evo-publishd-gst.${expected_hash:0:12}.part"
    local orphan
    for orphan in "$HOME"/.evo-publishd-gst.*.part; do
        [ -e "$orphan" ] || continue
        [ "$orphan" = "$tarball" ] && continue
        log "[PUBLISHD] Discarding a staged tarball from a different release: $(basename "$orphan")"
        rm -f "$orphan"
    done

    if [ -f "$tarball" ] && [ "$(sha_of "$tarball")" = "$expected_hash" ]; then
        # A previous tick finished the download but was killed before it could
        # verify or extract. Skipping curl here also avoids asking for a range
        # past the end of a complete file, which GCS answers with a 416 that
        # --fail turns into a permanent failure loop.
        log "[PUBLISHD] GStreamer tarball already complete from an earlier tick"
    else
        # The watchdog SIGKILLs this whole script at LOCK_TIMEOUT. A link slower
        # than ~230 KB/s cannot pull 134 MB inside one window, so the download
        # only starts with real headroom and resumes across ticks. Being killed
        # mid-download is harmless; the sha check below guarantees a file
        # stitched together over several ticks is either complete or discarded.
        if ! watchdog_headroom_available; then
            log "[PUBLISHD] Deferring GStreamer download — only ${WATCHDOG_HEADROOM_SECONDS}s of watchdog headroom left"
            return 2
        fi
        local before after
        before="$(stat -c %s "$tarball" 2>/dev/null || echo 0)"
        # -C - to resume, and NO --retry. The two together corrupt the file:
        # curl computes the resume offset once at startup, so an in-process
        # retry re-requests from that stale offset and overwrites bytes that
        # already landed (measured on a venue device, curl 7.81.0: 3327421 →
        # 9823677 → 4019645 bytes). A fresh curl on the next tick recomputes the
        # offset from the real file size, so cross-tick resume is safe.
        # --speed-limit/--speed-time rather than --max-time: kill a transfer
        # that has gone comatose, not one that is merely slow.
        if ! curl --fail --location --connect-timeout 20 \
            --speed-limit 400 --speed-time 45 \
            -C - -o "$tarball" "$url"; then
            after="$(stat -c %s "$tarball" 2>/dev/null || echo 0)"
            if [ "$after" -le "$before" ]; then
                # No forward progress: either the link is dead or the file is
                # complete-but-corrupt (a full-length file makes `-C -` ask for
                # a range past the end, which is a hard 416). Either way,
                # resuming it again would repeat this forever.
                log_error "[PUBLISHD] GStreamer download made no progress; discarding the partial file"
                rm -f "$tarball"
                return 1
            fi
            # Forward progress was made, so this is a deferral, not a failure —
            # and the distinction is the whole feature. On a venue link that
            # resets or goes comatose mid-transfer (--speed-time firing) curl
            # exits nonzero on nearly every attempt; arming the 1h backoff there
            # would turn 288 resume opportunities a day into 24 and stretch
            # 134 MB from hours into days.
            log "[PUBLISHD] GStreamer download interrupted at ${after} bytes; resuming next tick"
            return 2
        fi
    fi

    # Verify BEFORE extracting, always.
    if [ "$(sha_of "$tarball")" != "$expected_hash" ]; then
        log_error "[PUBLISHD] GStreamer tarball hash mismatch; discarding"
        rm -f "$tarball"
        return 1
    fi

    # The extract budget, checked HERE rather than at the top of the function:
    # the download above is resumable and deserves the bare 300s floor, but
    # unpacking 609 MB is not, and headroom only shrinks inside a tick — so the
    # pre-swap re-check further down cannot rescue an extract already underway.
    # Without this, a tick that completed a long download would extract, defer at
    # the swap, rm -rf the tree, and (rc=2 arming nothing) repeat next tick.
    # Deferring instead costs nothing: the verified tarball is kept, so the next
    # tick skips straight to the extract with a full window.
    if ! watchdog_headroom_available "$PUBLISHD_RUNTIME_HEADROOM_SECONDS"; then
        log "[PUBLISHD] Deferring the GStreamer extract — only ${WATCHDOG_HEADROOM_SECONDS}s of watchdog headroom left, need ${PUBLISHD_RUNTIME_HEADROOM_SECONDS}s to unpack 609 MB"
        return 2
    fi

    _publishd_ensure_opt_evobox || return 1

    staged_root="$PUBLISHD_OPT_ROOT/.gst-stage.$$"
    if ! sudo install -d -m 0755 "$staged_root"; then
        log_error "[PUBLISHD] Cannot create $staged_root"
        return 1
    fi
    # The archive's single member is gstreamer/, and env.sh bakes in the
    # absolute /opt/evobox/gstreamer prefix — hence the staged tree is moved
    # into place rather than sourced from here.
    if ! sudo tar -xzf "$tarball" -C "$staged_root" --no-same-owner; then
        log_error "[PUBLISHD] GStreamer extract failed"
        sudo rm -rf "$staged_root"
        return 1
    fi

    # Functional check on the STAGED tree, so a broken runtime never reaches the
    # live path. env.sh is not sourced: it hardcodes absolute paths under
    # $GSTREAMER_DIR and would test the tree we are trying to replace.
    if ! (
        export LD_LIBRARY_PATH="$staged_root/gstreamer/lib/x86_64-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
        export GST_PLUGIN_SYSTEM_PATH="$staged_root/gstreamer/lib/x86_64-linux-gnu/gstreamer-1.0"
        timeout 60 "$staged_root/gstreamer/bin/gst-inspect-1.0" --version >/dev/null 2>&1
    ); then
        log_error "[PUBLISHD] Staged GStreamer runtime failed its own gst-inspect-1.0 --version"
        sudo rm -rf "$staged_root"
        return 1
    fi

    # Never disturb a box that is on air. publishd holds open handles into this
    # tree; replacing it under a live process is the one thing here that could
    # take a table dark.
    if pgrep -x publishd >/dev/null 2>&1; then
        log "[PUBLISHD] publishd is running; deferring the GStreamer runtime swap"
        sudo rm -rf "$staged_root"
        return 2
    fi
    # Re-check headroom immediately before the destructive pair below, so a
    # SIGKILL cannot land between the rm and the mv. It still can in principle;
    # the recovery is that gstreamer_runtime_ok() fails next tick and the whole
    # install repeats from the (already downloaded, already verified) tarball.
    if ! watchdog_headroom_available; then
        log "[PUBLISHD] Deferring the GStreamer runtime swap — only ${WATCHDOG_HEADROOM_SECONDS}s of watchdog headroom left"
        sudo rm -rf "$staged_root"
        return 2
    fi

    sudo rm -rf "$GSTREAMER_DIR"
    if ! sudo mv -T "$staged_root/gstreamer" "$GSTREAMER_DIR"; then
        log_error "[PUBLISHD] GStreamer runtime swap failed"
        sudo rm -rf "$staged_root"
        return 1
    fi
    sudo rm -rf "$staged_root"
    rm -f "$tarball"
    log "[PUBLISHD] Installed pinned GStreamer runtime ${expected_hash:0:12}"
    return 0
}

# The automatable subset of install-publishd.sh's post-install verification,
# run on a file that has NOT been promoted yet.
#
# ALL FOUR checks run inside one subshell that has sourced the pinned runtime's
# env.sh. That is a measured requirement, not defensive habit (0015,
# 2026-08-20): publishd carries no RPATH, so a bare `ldd` resolves
# libgstreamer-1.0.so.0 to the system's /lib/x86_64-linux-gnu (1.20.3) instead
# of the pinned prefix. Without the sourced env, check 3 fails on every device
# forever — no publishd would ever install anywhere — and check 1 would validate
# the binary against the wrong GStreamer.
#
# Deliberately NOT the full smoke test (install-publishd.sh step 9): it writes
# production RTDB with no credentials to clean up after itself, needs a live
# PulseAudio session, and dies if any publishd is already running. None of that
# belongs on a 5-minute cron. So this proves the binary is present and linkable,
# NOT that this box can push media — which is why flipping publisherV2 on a
# device still requires a manual smoke test first.
verify_publishd_candidate() {
    local staged="$1"
    (
        # shellcheck source=/dev/null
        if ! . "$GSTREAMER_DIR/env.sh" 2>/dev/null; then
            log_error "[PUBLISHD] Cannot source $GSTREAMER_DIR/env.sh for verification"
            exit 1
        fi

        local out element
        if ! out="$(timeout 30 "$staged" --version 2>&1)"; then
            log_error "[PUBLISHD] Candidate --version failed or timed out"
            exit 1
        fi
        # A CI run with git dubious-ownership once stamped GIT_SHA=unknown into
        # a published binary. An unidentifiable build must not reach a device.
        case "$out" in
            *unknown*)
                log_error "[PUBLISHD] Candidate reports an unidentified build: $out"
                exit 1
                ;;
        esac

        if ldd -r "$staged" 2>&1 | grep -Eq 'undefined|not found'; then
            log_error "[PUBLISHD] Candidate has undefined symbols or missing libraries"
            exit 1
        fi

        if ! ldd "$staged" 2>/dev/null | grep 'gstreamer-1.0' | grep -q "$GSTREAMER_DIR/"; then
            log_error "[PUBLISHD] Candidate does not link the pinned GStreamer under $GSTREAMER_DIR"
            exit 1
        fi

        # ONE element per invocation. gst-inspect-1.0 inspects a single element
        # and reads argv[argc-1], so `gst-inspect-1.0 a b c` silently checks
        # nothing but c — and c would be `queue`, which exists in any working
        # GStreamer, making the whole check vacuous for exactly the two elements
        # a copied runtime puts at risk (v4l2src, pulsesrc).
        for element in v4l2src pulsesrc appsink videoconvert audioconvert tee queue; do
            if ! timeout 30 gst-inspect-1.0 "$element" >/dev/null 2>&1; then
                log_error "[PUBLISHD] Pinned GStreamer is missing element: $element"
                exit 1
            fi
        done
        exit 0
    )
}

# Keep /opt/evobox/publishd/publishd-run.sh identical to the copy that shipped
# with the deployed daemon. That tree is the single source of truth: the
# launcher's contract with publisher-service.ts (`exec`, argv[0] spelled exactly
# as PUBLISHD_BIN, `--config` and its path as two separate tokens) is owned by
# the daemon repo, and this function only transports the file unchanged.
#
# Best-effort by design: any problem here logs and returns 0, because the binary
# update below is independently useful and must not be blocked by a missing
# launcher source.
#
# `cmp` + `install`, not write_if_sha_changed(): that helper hashes
# printf '%s' "$content", and $(cat file) strips the trailing newline, so a
# file-to-file comparison through it never matches and would rewrite the
# launcher on every one of the 288 ticks a day.
_publishd_launcher_sync() {
    # Explicitly the main daemon tree even when SECOND_DAEMON=true: there is one
    # publishd launcher per box, and naming the source beats guessing between
    # two trees.
    local src="$EVOSPORTS_MAIN_DAEMON/scripts/publishd-run.sh"

    if [ ! -s "$src" ]; then
        # Never downloaded a daemon yet, or download_evobox_daemon() is mid-wipe.
        log_debug "[PUBLISHD] Launcher source not available yet ($src); skipping launcher sync"
        return 0
    fi
    if cmp -s "$src" "$PUBLISHD_LAUNCHER"; then
        return 0
    fi
    if ! bash -n "$src" 2>/dev/null; then
        log_error "[PUBLISHD] Launcher source fails bash -n; refusing to deploy it: $src"
        return 0
    fi
    _publishd_ensure_opt_evobox || return 0
    if ! sudo install -d -o root -g root -m 0755 "$PUBLISHD_DIR"; then
        log_error "[PUBLISHD] Cannot create $PUBLISHD_DIR"
        return 0
    fi
    if sudo install -o root -g root -m 0755 "$src" "$PUBLISHD_LAUNCHER"; then
        log "[PUBLISHD] Launcher synced from the deployed daemon tree"
    else
        log_error "[PUBLISHD] Launcher install failed"
    fi
    return 0
}

# Freshness / backoff owner for the binary, mirroring
# check_and_update_zowie_ndi_probe(): any success marks the 12h stamp and clears
# the backoff, any failure arms the 1h retry, and a deferral does neither.
check_and_update_publishd() {
    if ! fresh_due "publishd" "$PUBLISHD_CHECK_TTL"; then
        log_debug "[PUBLISHD] Skipped (cached, last successful check <12h ago)"
        return 0
    fi
    # Checked WITHOUT the force-refresh bypass, for the same reason as the
    # probe: a forgotten ~/.evo-force-refresh must not re-run a known-broken
    # 41 MB download on every tick.
    if fresh_backoff_active "publishd_attempt" "$PUBLISHD_RETRY_TTL"; then
        log_debug "[PUBLISHD] Skipped (failure retry backoff <1h old)"
        return 0
    fi

    _publishd_update
    local rc=$?
    case "$rc" in
        0)
            fresh_mark "publishd"
            fresh_clear "publishd_attempt"
            ;;
        # Deferred: no headroom, or the download was interrupted with forward
        # progress (the dominant case on a venue link). Stamp nothing, so the
        # next tick resumes instead of waiting out a 12h cache or a 1h backoff.
        2) : ;;
        *) fresh_mark "publishd_attempt" ;;
    esac
    return 0
}

# Fetch the tracked object's checksum; if it differs from the installed binary,
# download → verify → verify functionally → atomically replace. Exit codes match
# _publishd_gstreamer_install(): 0 success (including "already current"),
# 1 failure, 2 deferred.
#
# "Already current" is decided by the installed file's own sha256, NOT by
# --version: on 0015, publishd-67_beta and publishd-0.1.0 both report
# "0.1.0 (git b4c18a5)" while being different binaries, because rustc output is
# not reproducible. For the same reason no VERSION file is written here — the
# installed binary's hash IS its identity. (install-publishd.sh still writes
# one on the manual path; the two coexist harmlessly.)
_publishd_update() {
    local url="$GCS_PUBLISHER_V2/$PUBLISHD_OBJECT"
    local checksum_raw expected_hash staged promoted orphan before after

    # Before the network, and a FAILURE not a deferral — see the same check in
    # _publishd_gstreamer_install(). Placed above the sidecar fetch so a box
    # without passwordless sudo does no GCS work at all.
    if ! sudo -n true 2>/dev/null; then
        log_error "[PUBLISHD] Passwordless sudo unavailable; binary install cannot proceed"
        return 1
    fi

    checksum_raw=$(curl --fail --silent --location --connect-timeout 20 --max-time 30 --retry 2 \
        "$url.sha256") || {
        log_error "[PUBLISHD] Checksum download failed for $PUBLISHD_OBJECT"
        return 1
    }
    expected_hash="${checksum_raw%%[[:space:]]*}"
    if ! is_sha256 "$expected_hash"; then
        log_error "[PUBLISHD] Checksum format is invalid for $PUBLISHD_OBJECT"
        return 1
    fi

    if [ -x "$PUBLISHD_BIN" ] && [ "$(sha_of "$PUBLISHD_BIN")" = "$expected_hash" ]; then
        log_debug "[PUBLISHD] $PUBLISHD_OBJECT already installed (${expected_hash:0:12})"
        return 0
    fi

    # Same hash-named staging convention as the tarball, and for the same two
    # reasons: survive a reboot, and never resume across releases. 41 MB can
    # also exceed one watchdog window on a venue link.
    staged="$HOME/.evo-publishd-bin.${expected_hash:0:12}.part"
    for orphan in "$HOME"/.evo-publishd-bin.*.part; do
        [ -e "$orphan" ] || continue
        [ "$orphan" = "$staged" ] && continue
        rm -f "$orphan"
    done

    if [ -f "$staged" ] && [ "$(sha_of "$staged")" = "$expected_hash" ]; then
        log "[PUBLISHD] Binary already complete from an earlier tick"
    else
        if ! watchdog_headroom_available; then
            log "[PUBLISHD] Deferring binary download — only ${WATCHDOG_HEADROOM_SECONDS}s of watchdog headroom left"
            return 2
        fi
        before="$(stat -c %s "$staged" 2>/dev/null || echo 0)"
        if ! curl --fail --location --connect-timeout 20 \
            --speed-limit 400 --speed-time 45 \
            -C - -o "$staged" "$url"; then
            after="$(stat -c %s "$staged" 2>/dev/null || echo 0)"
            if [ "$after" -le "$before" ]; then
                log_error "[PUBLISHD] Binary download made no progress; discarding the partial file"
                rm -f "$staged"
                return 1
            fi
            # Progress made => deferral, not failure. See the same split in
            # _publishd_gstreamer_install().
            log "[PUBLISHD] Binary download interrupted at ${after} bytes; resuming next tick"
            return 2
        fi
    fi

    if [ "$(sha_of "$staged")" != "$expected_hash" ]; then
        log_error "[PUBLISHD] Downloaded binary hash mismatch for $PUBLISHD_OBJECT; discarding"
        rm -f "$staged"
        return 1
    fi

    _publishd_ensure_opt_evobox || return 1
    if ! sudo install -d -o root -g root -m 0755 "$PUBLISHD_DIR"; then
        log_error "[PUBLISHD] Cannot create $PUBLISHD_DIR"
        return 1
    fi

    # Copy into the target directory before promoting, so the LAST step is a
    # same-filesystem `mv -T`. A cross-filesystem `mv -T` silently degrades to
    # copy+unlink and stops being atomic — an interruption there leaves a
    # truncated binary at the path the daemon execs. $HOME and /opt are one
    # device on 0015 and 0093, but the fleet cannot be checked box by box, so
    # this pays one extra copy for guaranteed atomicity.
    sudo rm -f "$PUBLISHD_DIR"/.publishd.* 2>/dev/null
    promoted="$PUBLISHD_DIR/.publishd.$$"
    if ! sudo cp "$staged" "$promoted"; then
        log_error "[PUBLISHD] Cannot stage the binary inside $PUBLISHD_DIR"
        sudo rm -f "$promoted"
        return 1
    fi
    # Ownership and mode set before promotion, so the file the daemon execs is
    # never briefly wrong.
    if ! sudo chown root:root "$promoted" || ! sudo chmod 755 "$promoted"; then
        log_error "[PUBLISHD] Cannot set ownership/mode on the staged binary"
        sudo rm -f "$promoted"
        return 1
    fi

    # Verify the exact file that will be promoted.
    if ! verify_publishd_candidate "$promoted"; then
        sudo rm -f "$promoted"
        return 1
    fi

    # A running publishd keeps its old inode and keeps publishing; only the next
    # spawn picks this up. See evobox-publisher-v2/docs/publishd-auto-install.md
    # §4 — the practical bound is "the end of the next broadcast", because the
    # 04:00 daemon restart detaches publishd rather than stopping it.
    if ! sudo mv -T "$promoted" "$PUBLISHD_BIN"; then
        log_error "[PUBLISHD] Atomic install failed"
        sudo rm -f "$promoted"
        return 1
    fi
    rm -f "$staged"
    log "[PUBLISHD] Installed $PUBLISHD_OBJECT (${expected_hash:0:12})"
    return 0
}

# Delete staged download fragments that nothing is going to finish. $1 and $2 are
# "keep" or "drop" for the GStreamer tarball and the binary respectively.
#
# This lives at stack level, not inside the two update functions, because those
# are not always reached: once a runtime is healthy
# check_and_update_gstreamer_runtime() returns before
# _publishd_gstreamer_install() ever runs, so a 134 MB tarball left behind by a
# deferred swap would sit on eMMC for the life of the device. That is not
# hypothetical — a swap deferred by a live publishd retains the tarball on
# purpose, and 0142/0143 show operators do repair a broken tree by hand over SSH
# in exactly that window, which makes the tarball unreachable garbage.
_publishd_staging_sweep() {
    local f
    if [ "$1" = "drop" ]; then
        for f in "$HOME"/.evo-publishd-gst.*.part; do
            [ -e "$f" ] || continue
            log "[PUBLISHD] Removing an orphaned GStreamer download fragment: $(basename "$f")"
            rm -f "$f"
        done
    fi
    if [ "$2" = "drop" ]; then
        for f in "$HOME"/.evo-publishd-bin.*.part; do
            [ -e "$f" ] || continue
            log "[PUBLISHD] Removing an orphaned publishd download fragment: $(basename "$f")"
            rm -f "$f"
        done
    fi
}

# Single entry point for the whole publishd section. Resolving the channel FIRST
# is what makes the staged rollout real: with no marker and no default, this
# returns before the 134 MB runtime fetch is even considered.
check_and_update_publishd_stack() {
    if [ "$PUBLISHD_INSTALL_PAUSED" = true ]; then
        # Sweep BEFORE returning. Both of this function's early exits are the
        # documented rollback levers — flipping this constant in a republished
        # script, or deleting the marker below — and a device rolled back
        # mid-transfer holds up to 175 MB of `.part` fragments that nothing else
        # ever reclaims: the by-name prunes inside _publishd_update() are
        # downstream of here, so an early return makes them unreachable and the
        # fragments become permanent eMMC garbage. Rolling back means the
        # transfer is abandoned, so `drop drop` is the correct answer, not a
        # concession: if the lever is flipped back, the download restarts, and
        # re-fetching 175 MB is cheaper than holding it forever on every paused
        # box in the fleet.
        _publishd_staging_sweep drop drop
        log_debug "[PUBLISHD] Skipped (PUBLISHD_INSTALL_PAUSED is set in this build of the script)"
        return 0
    fi

    resolve_publishd_object
    if [ -z "$PUBLISHD_OBJECT" ]; then
        # Same reasoning as the paused branch above: no channel means no
        # transfer will ever finish, so the fragments are garbage.
        _publishd_staging_sweep drop drop
        # "absent" only when it really is. Observed on 0015 during the 2026-08-20
        # verification run: a rejected marker logs its own ERROR line and then
        # falls through to here, where claiming the file is absent contradicts
        # the line immediately above it and sends the operator looking for a file
        # that is sitting right there with bad content in it.
        if [ -f "$PUBLISHD_CHANNEL_FLAG" ]; then
            log_debug "[PUBLISHD] Skipped (no channel selected: $PUBLISHD_CHANNEL_FLAG holds no usable value and this build has no default channel)"
        else
            log_debug "[PUBLISHD] Skipped (no channel selected: $PUBLISHD_CHANNEL_FLAG absent and no default channel)"
        fi
        return 0
    fi
    log_debug "[PUBLISHD] Tracking $PUBLISHD_OBJECT"

    # The runtime gates the binary: verify_publishd_candidate() cannot pass
    # without it, so attempting the download would only burn bandwidth and arm
    # a backoff that hides the real problem.
    if ! check_and_update_gstreamer_runtime; then
        # Keep both fragments. The tarball's download is still in flight across
        # ticks. The binary fragment is kept too, even though it cannot be
        # finished this tick: the runtime install is retried every tick and
        # normally succeeds, and a box on a venue link can take hours to
        # accumulate 41 MB. Dropping it because a power cut happened to zero out
        # the runtime tree in the same window would throw that away and restart
        # from zero. Cross-release fragments are pruned by name inside
        # _publishd_update() instead, which is where the current object name is
        # known.
        _publishd_staging_sweep keep keep
        log_debug "[PUBLISHD] GStreamer runtime not usable yet; skipping the binary update this tick"
        return 0
    fi
    # The runtime is healthy, so no tarball fragment can ever be wanted again.
    _publishd_staging_sweep drop keep

    _publishd_launcher_sync
    check_and_update_publishd
}

# Are the daemon trees this device is supposed to have actually usable?
#
# index.js must be non-empty and package.json must parse. `-s` rather than `-f`
# because ext4 delayed allocation turns a power cut mid-extract into a tree of
# 0-byte files that keep the archive's mtimes: every `-f` test passes, the
# version file says the install is current, and the device sits dead across
# every subsequent tick (evobox-oem-0142/0143). package.json is checked with jq
# rather than `-s` because node parses the nearest package.json in
# readPackageScope() before it loads index.js, so an empty or truncated one is
# fatal on its own even when the bundle is intact.
#
# ONE function for every caller, deliberately: 0142/0143 stayed dark because two
# copies of this test drifted apart. For the same reason there is no
# `command -v jq` guard — jq is installed unconditionally by this script and
# guarding one copy is how the divergence starts again. Only ever called from an
# `if`, never `$()`, so logging here is safe.
daemon_trees_ok() {
    local dirs=("$EVOSPORTS_MAIN_DAEMON")
    [ "$SECOND_DAEMON" = "true" ] && dirs+=("$EVOSPORTS_SECOND_DAEMON")
    local d
    for d in "${dirs[@]}"; do
        if ! { [ -s "$d/index.js" ] && jq -e . "$d/package.json" >/dev/null 2>&1; }; then
            log "[daemon-trees] index.js/package.json missing or corrupt at $d"
            return 1
        fi
    done
    return 0
}

# Install the resolved archive and, ONLY on success, replace the local receipt
# with the exact manifest this decision was made from. Shared by the corrupt-tree,
# missing-receipt and changed-release paths so a later change to receipt
# durability cannot land in one of them and silently miss the other two.
install_selected_release() {
    local release_manifest="$1" local_receipt="$2"
    local receipt_tmp="${local_receipt}.tmp"

    if ! download_evobox_daemon "$DAEMON_RELEASE_URL"; then
        log_error "[daemon-version] Daemon download failed — retaining release receipt"
        return 1
    fi
    if cp "$release_manifest" "$receipt_tmp" && mv -f "$receipt_tmp" "$local_receipt"; then
        log "[daemon-version] Release receipt recorded"
        return 0
    fi
    rm -f "$receipt_tmp"
    log_error "[daemon-version] Failed to record release receipt"
    return 1
}

check_and_update_daemon_version() {
    # Do not let a previous decision leave a temporary manifest behind.
    if [ -n "${DAEMON_RELEASE_MANIFEST:-}" ]; then
        rm -f "$DAEMON_RELEASE_MANIFEST"
    fi
    DAEMON_RELEASE_MANIFEST=""
    DAEMON_RELEASE_URL=""

    # --- PINNED URL MODE ---
    # When ~/.evo-beta holds a valid archive URL, the device is pinned to that
    # exact build. Its internal version won't match the GCS version manifest, so
    # the normal version-number comparison below would either reinstall every
    # tick (infinite loop) or never apply the pin. Instead: install once, then
    # reinstall ONLY when the pin value itself changes. The sidecar records the
    # last-installed pin; a diff (or a missing daemon) triggers a fresh install.
    resolve_pinned_daemon_url
    if [ -n "$PINNED_DAEMON_URL" ]; then
        local stored_pin=""
        [ -f "$DAEMON_PIN_SIDECAR" ] && stored_pin="$(cat "$DAEMON_PIN_SIDECAR" 2>/dev/null)"

        # daemon_trees_ok, not `-f index.js`: a pinned device that lost power
        # mid-extract returns here every tick and would never reach the
        # corruption-recovery branch below, wedging exactly as 0142/0143 did.
        # Evaluated once — the result also decides whether the retry backoff
        # applies below.
        local pinned_trees_ok=true
        daemon_trees_ok || pinned_trees_ok=false

        if [ "$stored_pin" = "$PINNED_DAEMON_URL" ] && [ "$pinned_trees_ok" = true ]; then
            log_debug "[daemon-version] Pinned URL unchanged and daemon usable — no update"
            return 0
        fi

        # The backoff exists to stop a failing download from interrupting a
        # HEALTHY daemon every tick. A broken tree has nothing left to protect
        # and delaying only keeps the device dark, so recovery ignores it —
        # the same rule the non-pinned corrupt-tree branch follows.
        if [ "$pinned_trees_ok" = true ] && ! daemon_retry_allowed "$PINNED_DAEMON_URL"; then
            return 1
        fi

        log "[daemon-version] Pinned daemon URL active, installing: $PINNED_DAEMON_URL"

        # Stop units before wipe/extract so the new tarball replaces running code.
        if sudo systemctl is-active --quiet "$DAEMON_UNIT_MAIN" 2>/dev/null; then
            log "[daemon-version] Stopping $DAEMON_UNIT_MAIN for pinned update"
            sudo systemctl stop "$DAEMON_UNIT_MAIN" || log_error "[daemon-version] stop $DAEMON_UNIT_MAIN failed"
        fi
        if [ "$SECOND_DAEMON" = "true" ] && sudo systemctl is-active --quiet "$DAEMON_UNIT_SECOND" 2>/dev/null; then
            log "[daemon-version] Stopping $DAEMON_UNIT_SECOND for pinned update"
            sudo systemctl stop "$DAEMON_UNIT_SECOND" || log_error "[daemon-version] stop $DAEMON_UNIT_SECOND failed"
        fi

        # Persist the pin ONLY on a successful install. On failure the sidecar is
        # left unchanged so a later tick retries instead of assuming success.
        if download_evobox_daemon "$PINNED_DAEMON_URL"; then
            printf '%s\n' "$PINNED_DAEMON_URL" > "$DAEMON_PIN_SIDECAR"
            daemon_retry_clear
            log "[daemon-version] Pinned daemon installed and recorded"
            return 0
        fi
        daemon_retry_record_failure "$PINNED_DAEMON_URL"
        return 1
    fi

    # Resolve channel, manifest and archive together before any service stop,
    # receipt deletion, or installation mutation.
    if ! fetch_daemon_release; then
        log_error "[daemon-version] Daemon release metadata unavailable — leaving installation untouched"
        return 1
    fi
    local release_manifest="$DAEMON_RELEASE_MANIFEST"
    local local_receipt="$EVOSPORTS_ROOT/evobox-daemon-version-local.json"
    local install_rc=0
    local receipt_tmp
    # Identity of what this tick would install. It includes the version and the
    # commit, not just the URL, so publishing a new release always overrides an
    # active backoff instead of inheriting the failed one's delay.
    local release_target
    release_target="$(jq -r '"\(.version)|\(.commitId // "null")"' "$release_manifest" 2>/dev/null)|$DAEMON_RELEASE_URL"

    # Not pinned: drop any stale pin sidecar so normal version-tracked updates
    # resume on this and subsequent ticks.
    [ -f "$DAEMON_PIN_SIDECAR" ] && rm -f "$DAEMON_PIN_SIDECAR" && \
        log "[daemon-version] Pin cleared — resuming version-tracked updates"

    # Deletion / corruption recovery: if either daemon tree is missing OR
    # unusable (user wiped it, disk cleanup error, half-finished prior run,
    # venue power cut), force a re-download regardless of what the version file
    # says. daemon_trees_ok has already logged which tree is at fault.
    #
    # A corrupt SECOND tree re-runs the whole download_evobox_daemon flow, which
    # re-downloads main and re-copies second. That is deliberate: the
    # evo.json preserve/strip/restore dance in there is the most error-prone
    # part of this file and must not be duplicated into a narrower repair path.
    if ! daemon_trees_ok; then
        log "[daemon-version] Daemon tree missing or corrupt — forcing re-download"
        # Stop the unit first so the fresh extract doesn't race the running
        # process. No-op if the unit isn't installed yet (first-time install).
        sudo systemctl stop "$DAEMON_UNIT_MAIN" 2>/dev/null || true
        if [ "$SECOND_DAEMON" = "true" ]; then
            sudo systemctl stop "$DAEMON_UNIT_SECOND" 2>/dev/null || true
        fi

        if install_selected_release "$release_manifest" "$local_receipt"; then
            daemon_retry_clear
        else
            install_rc=1
        fi

        rm -f "$release_manifest"
        DAEMON_RELEASE_MANIFEST=""
        DAEMON_RELEASE_URL=""
        return "$install_rc"
    fi

    # Check if local version is the same as server version, install if not.
    if [ ! -e "$local_receipt" ]; then
        log "evobox-daemon-version-local.json not found"
        log "Server daemon version grabbed"

        # Checked before the stops: a failing download must not cost this device
        # a service interruption on every one-minute tick.
        if ! daemon_retry_allowed "$release_target"; then
            rm -f "$release_manifest"
            DAEMON_RELEASE_MANIFEST=""
            DAEMON_RELEASE_URL=""
            return 1
        fi

        # Stop the unit before wiping/extracting so the new tarball replaces
        # the running code. Without this, an operator-triggered re-download
        # (e.g. `rm evobox-daemon-version-local.json` to force a beta swap)
        # updates the on-disk daemon while the old node keeps executing from
        # memory — systemd sees `active`, no restart, old code runs forever.
        if sudo systemctl is-active --quiet "$DAEMON_UNIT_MAIN" 2>/dev/null; then
            log "[daemon-version] Stopping $DAEMON_UNIT_MAIN for update"
            sudo systemctl stop "$DAEMON_UNIT_MAIN" || log_error "[daemon-version] stop $DAEMON_UNIT_MAIN failed"
        fi
        if [ "$SECOND_DAEMON" = "true" ] && sudo systemctl is-active --quiet "$DAEMON_UNIT_SECOND" 2>/dev/null; then
            log "[daemon-version] Stopping $DAEMON_UNIT_SECOND for update"
            sudo systemctl stop "$DAEMON_UNIT_SECOND" || log_error "[daemon-version] stop $DAEMON_UNIT_SECOND failed"
        fi

        if install_selected_release "$release_manifest" "$local_receipt"; then
            daemon_retry_clear
        else
            install_rc=1
            daemon_retry_record_failure "$release_target"
        fi

        rm -f "$release_manifest"
        DAEMON_RELEASE_MANIFEST=""
        DAEMON_RELEASE_URL=""
        return "$install_rc"
    fi

    local local_version
    local local_commit
    local server_version
    local server_commit
    local_version="$(jq -r ".version" "$local_receipt" 2>/dev/null)"
    local_commit="$(jq -r ".commitId // \"null\"" "$local_receipt" 2>/dev/null)"
    server_version="$(jq -r ".version" "$release_manifest" 2>/dev/null)"
    server_commit="$(jq -r ".commitId // \"null\"" "$release_manifest" 2>/dev/null)"

    log_debug "Local version: $local_version"
    log_debug "Server version: $server_version"

    if [ "$local_version" != "$server_version" ] || [ "$local_commit" != "$server_commit" ]; then
        log "New daemon version ($server_version) found. Installing new daemon..."

        # Checked before the stops: a failing download must not cost this device
        # a service interruption on every one-minute tick. A newly published
        # release changes release_target and is therefore attempted at once.
        if ! daemon_retry_allowed "$release_target"; then
            rm -f "$release_manifest"
            DAEMON_RELEASE_MANIFEST=""
            DAEMON_RELEASE_URL=""
            return 1
        fi

        # Graceful shutdown via systemd (honors TimeoutStopSec=15s and
        # suppresses the crash webhook because SERVICE_RESULT=success).
        # No-op if the unit isn't installed yet.
        if sudo systemctl is-active --quiet "$DAEMON_UNIT_MAIN" 2>/dev/null; then
            log "[daemon-version] Stopping $DAEMON_UNIT_MAIN for update"
            sudo systemctl stop "$DAEMON_UNIT_MAIN" || log_error "[daemon-version] stop $DAEMON_UNIT_MAIN failed"
        fi
        if [ "$SECOND_DAEMON" = "true" ] && sudo systemctl is-active --quiet "$DAEMON_UNIT_SECOND" 2>/dev/null; then
            log "[daemon-version] Stopping $DAEMON_UNIT_SECOND for update"
            sudo systemctl stop "$DAEMON_UNIT_SECOND" || log_error "[daemon-version] stop $DAEMON_UNIT_SECOND failed"
        fi

        if install_selected_release "$release_manifest" "$local_receipt"; then
            daemon_retry_clear
        else
            install_rc=1
            daemon_retry_record_failure "$release_target"
        fi
    fi

    if [ "$install_rc" -eq 0 ] && \
        [ "$local_version" = "$server_version" ] && \
        [ "$local_commit" = "$server_commit" ]; then
        log_debug "[daemon-version] Release unchanged — no update"
    fi

    rm -f "$release_manifest"
    DAEMON_RELEASE_MANIFEST=""
    DAEMON_RELEASE_URL=""
    return "$install_rc"
}

start_first_daemon() {
    # Daemon supervision is delegated to systemd (evo-obs-daemon.service).
    # This function now just reconciles: if the unit is in failed state
    # (burst-limit exhausted by crash loop), reset + restart. Otherwise
    # ensure it's active. Crash-recovery between cron ticks is handled
    # by systemd's Restart=always/RestartSec=10s.
    if [ ! -f "$EVOSPORTS_MAIN_DAEMON/index.js" ]; then
        log_error "Main daemon index.js missing: $EVOSPORTS_MAIN_DAEMON/index.js — check_and_update_daemon_version should redownload on next tick"
        return 1
    fi
    ensure_daemon_running_via_systemd "$DAEMON_UNIT_MAIN"
}

start_second_daemon() {
    if [ "$SECOND_DAEMON" != "true" ]; then
        return 0
    fi

    if [ ! -f "$EVOSPORTS_SECOND_DAEMON/index.js" ]; then
        log_error "Second daemon index.js missing: $EVOSPORTS_SECOND_DAEMON/index.js — download_evobox_daemon will refresh on next tick"
        return 1
    fi
    ensure_daemon_running_via_systemd "$DAEMON_UNIT_SECOND"
}

#===============================================================================
# DEPENDENCY INSTALLATION
#===============================================================================

# Bounded apt for every purge that touches the printing stack.
#
# daemon-install-script#113 (evobox-oem-0029): the printing purge hung in
# printer-driver-cups-pdf's prerm and held the dpkg lock for 86 days. The purge
# must not be able to outlive the tick, so each apt-get that can reach a cups
# maintainer script goes through run_bounded_apt_get() and is gated on
# PRINTING_PURGE_BUDGET seconds of watchdog headroom. The budget is the worst
# case (purge, autoremove, and one SIGKILL grace each), so it always fits
# inside what is left of LOCK_TIMEOUT.
readonly APT_LOCK_WAIT_SECONDS=60        # DPkg::Lock::Timeout: fail after a 60s wait, never block forever
readonly APT_KILL_GRACE_SECONDS=10       # timeout -k: SIGKILL this long after SIGTERM
readonly PRINTING_PURGE_TIMEOUT=240
readonly PRINTING_AUTOREMOVE_TIMEOUT=120
readonly PRINTING_PURGE_BUDGET=$(( PRINTING_PURGE_TIMEOUT + PRINTING_AUTOREMOVE_TIMEOUT + 2 * APT_KILL_GRACE_SECONDS ))  # 380s
readonly PRINTING_PURGE_RETRY_TTL=$((6 * 3600))
readonly PRINTING_STACK_PATTERN='^(cups($|-)|printer-driver-|system-config-printer)'

# Run `apt-get <args>` under a hard root-side deadline: run_bounded_apt_get <seconds> <apt-get args...>
#   - `setsid` drops the controlling terminal, which defeats cupsreject's
#     /dev/tty auth prompt (the wedge in the cups-pdf prerm).
#   - `--wait` keeps apt-get's exit status; without it setsid may fork and
#     return the status of the fork, hiding a failed or timed-out purge.
#   - `timeout` runs as root inside sudo, so it can signal root's
#     apt/dpkg/maintainer-script process group. The evobox watchdog cannot.
#   -k escalates to SIGKILL after APT_KILL_GRACE_SECONDS, and DPkg::Lock::Timeout
#   makes a held lock fail after APT_LOCK_WAIT_SECONDS instead of blocking.
# run_logged supplies </dev/null and the apt-get exit status via PIPESTATUS.
run_bounded_apt_get() {
    local limit="$1"
    shift
    run_logged sudo DEBIAN_FRONTEND=noninteractive setsid --wait \
        timeout -k "$APT_KILL_GRACE_SECONDS" "$limit" \
        apt-get -o DPkg::Lock::Timeout="$APT_LOCK_WAIT_SECONDS" "$@"
}

# True while any package of the printing stack is still known to dpkg. A bare
# `dpkg-query -W` lists installed and `rc` (removed, config left) packages but
# not purged ones, so it is both the purge trigger and the post-purge check.
# A failed dpkg-query (corrupt status file, interrupted dpkg) returns "present":
# an empty listing must never be read as "the stack is gone".
printing_stack_present() {
    local packages
    packages=$(dpkg-query -W -f='${Package}\n' 2>/dev/null) || return 0
    printf '%s\n' "$packages" | grep -qE "$PRINTING_STACK_PATTERN"
}

# Break a dpkg/apt lock held by a transaction that can never finish.
#
# Root-caused from evobox-oem-0029: the cups purge below reached
# printer-driver-cups-pdf's prerm, which runs `cupsreject -h localhost <queue>`.
# That helper has no timeout and opens /dev/tty for a CUPS auth prompt, so on a
# run with a controlling terminal it blocked forever — 42 days, holding
# /var/lib/dpkg/lock{,-frontend}. DEBIAN_FRONTEND does not help: the prompt is
# inside a helper binary, not debconf. Every apt path on the device was dead
# until a human SSHed in, and nothing in the installer noticed or reported it.
#
# Recovery is deliberately gentle first: SIGKILL the descendants of the lock
# holder (the hung helper), which lets dpkg unwind its own transaction. Only if
# the lock is still held after a grace period do we kill the holder itself and
# leave the repair to step 3's `dpkg --configure -a`.
readonly DPKG_STALE_SECONDS=1800  # 30 min — far longer than any legitimate
                                  # transaction on these devices (the bootstrap
                                  # upgrade is itself bounded at 240s), so this
                                  # can only fire on a genuinely wedged lock.
unwedge_stale_dpkg() {
    local holder age
    holder=$(sudo fuser /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock 2>/dev/null \
        | tr -s ' ' '\n' | grep -E '^[0-9]+$' | head -1)
    [ -z "$holder" ] && return 0

    age=$(ps -o etimes= -p "$holder" 2>/dev/null | tr -d ' ')
    [ -z "$age" ] && return 0
    [ "$age" -lt "$DPKG_STALE_SECONDS" ] && return 0

    # Collect the holder's descendants breadth-first, deepest last.
    # `paste -sd,` and not `tr ' ' ','`: a trailing separator in the PID list
    # makes procps 3.3.17 (the fleet's version) abort with SIGABRT rather than
    # error, and stderr is discarded here — the walk would silently truncate at
    # depth 1 and leave the actual hung helper (depth 3 on evobox-oem-0029)
    # alive.
    local tree="" generation="$holder" kids ppid_list
    while [ -n "$generation" ]; do
        tree="$tree $generation"
        ppid_list=$(echo "$generation" | tr -s ' ' '\n' | grep -E '^[0-9]+$' | paste -sd, -)
        [ -z "$ppid_list" ] && break
        kids=$(ps -o pid= --ppid "$ppid_list" 2>/dev/null | tr -d ' ' | tr '\n' ' ')
        generation="$kids"
    done

    log_error "[APT] dpkg lock held ${age}s by PID ${holder} — killing stuck transaction (tree:${tree})"
    # One alert per 12h: a lock that re-wedges on later ticks must not page
    # the fleet channel on every one of them.
    if fresh_due "dpkg_wedge_notify" $((12 * 3600)); then
        notify_webhook "dpkg lock wedged for ${age}s by PID ${holder} (tree:${tree}). Killing the stuck transaction; apt was unusable on this device until now." \
            "EvoBox Wedged dpkg Lock" "warning"
        fresh_mark "dpkg_wedge_notify"
    fi

    # Gentle pass: leaves first, sparing the holder AND any dpkg in the tree.
    # The holder is the apt-get frontend, so dpkg is a *descendant* and would
    # otherwise be SIGKILLed here — mid-transaction, which is the #28
    # corruption class this file avoids elsewhere. Killing only the hung helper
    # lets dpkg unwind its own transaction and release the lock by itself.
    local pid comm killed_any=false
    local leaves_first
    leaves_first=$(echo "$tree" | tr -s ' ' '\n' | grep -E '^[0-9]+$' | tac)
    for pid in $leaves_first; do
        [ "$pid" = "$holder" ] && continue
        comm=$(ps -o comm= -p "$pid" 2>/dev/null | tr -d ' ')
        [ "$comm" = "dpkg" ] && continue
        sudo kill -9 "$pid" 2>/dev/null || true
        killed_any=true
    done

    # Give the spared dpkg up to 30s to unwind, and decide on *that*, not on the
    # lock: the apt-get frontend holds lock-frontend for the whole of its run
    # and we deliberately spared it, so a lock re-check would always say "still
    # held" and make the gentle path unreachable.
    #
    # 30s + the escalation's 10s = 40s worst case, deliberately inside the ~60s
    # watchdog cushion documented at run_bootstrap_once's timeout invariant
    # (300s + 240s under LOCK_TIMEOUT 600s). run_bootstrap_once runs later in
    # the same tick, and a device wedged for weeks is exactly one that never
    # bootstrapped, so these two are correlated — this wait must not eat the
    # cushion that keeps the watchdog's SIGKILL out of `apt-get upgrade`.
    # Checks at t=0/10/20/30 with three sleeps: the loop must re-read state
    # *after* the last sleep, or escalation would decide on 20s-old state and
    # the final 10s of the window would be slept for nothing.
    local waited=0 survivors=""
    while :; do
        survivors=""
        for pid in $leaves_first; do
            [ "$(ps -o comm= -p "$pid" 2>/dev/null | tr -d ' ')" = "dpkg" ] \
                && survivors="$survivors $pid"
        done
        [ -z "$survivors" ] && break
        [ "$waited" -ge 30 ] && break
        sleep 10
        waited=$((waited + 10))
    done

    if [ -n "$survivors" ]; then
        # dpkg never unwound. Escalate over the whole tree: SIGTERM first so it
        # can still exit cleanly, SIGKILL only for what ignores it. Step 3's
        # `dpkg --configure -a` repairs whatever state that leaves.
        for pid in $leaves_first; do
            sudo kill -15 "$pid" 2>/dev/null || true
        done
        sleep 10
        for pid in $leaves_first; do
            sudo kill -9 "$pid" 2>/dev/null || true
        done
        log_error "[APT] dpkg (${survivors# }) did not unwind — killed the whole transaction tree; repair runs below"
    elif [ "$killed_any" = "false" ] && ps -p "$holder" >/dev/null 2>&1; then
        # Nothing to kill and the holder is still there: the frontend itself is
        # the wedge, so nothing else will ever free the lock.
        sudo kill -15 "$holder" 2>/dev/null || true
        sleep 10
        sudo kill -9 "$holder" 2>/dev/null || true
        log_error "[APT] lock holder PID ${holder} had no killable children — killed the holder; repair runs below"
    else
        # dpkg unwound. The frontend may still be finishing legitimately; if it
        # wedges again it is caught on a later tick, with a fresh tree.
        log "[APT] dpkg unwound after killing the hung helper"
    fi
}

# True while dpkg is in an interrupted or half-configured state. Two signals:
# a pending journal in /var/lib/dpkg/updates/ (apt's own "dpkg was
# interrupted" trigger) or any package `dpkg --audit` reports as
# half-installed / half-configured.
dpkg_needs_repair() {
    [ -n "$(sudo ls -A /var/lib/dpkg/updates/ 2>/dev/null)" ] \
        || [ -n "$(sudo dpkg --audit 2>/dev/null)" ]
}

# Prepare a safe apt/dpkg environment before any package operations.
# Root-caused from evobox-oem-0169: an interactive debconf prompt
# ("Password for root on localhost?") raised during the printing-package
# configure stage hung apt holding the dpkg lock; killing it left dpkg
# interrupted and every later run reported false success without recovering.
#
# Three idempotent, disk-write-conscious guards (write only if missing/changed):
#   1. Make DEBIAN_FRONTEND=noninteractive actually survive sudo's env_reset,
#      so no debconf question can ever block.
#   2. Pin all printing packages out — these devices never use printers, and
#      the printer chain is what surfaced the blocking prompt (pulled as a
#      Recommends of OBS/Qt/webkit/Chrome despite the cups purge below).
#   3. Self-heal an interrupted dpkg state automatically (no manual SSH), and
#      alert when the repair does not clear it.
prepare_apt_environment() {
    # 0. Break a dpkg lock wedged by a hung maintainer script.
    unwedge_stale_dpkg

    # 1. Make DEBIAN_FRONTEND=noninteractive survive sudo's env_reset.
    local frontend_rule='Defaults env_keep += "DEBIAN_FRONTEND"'
    if ! sudo grep -qsF "$frontend_rule" /etc/sudoers.d/evobox-apt-noninteractive 2>/dev/null; then
        echo "$frontend_rule" | sudo tee /etc/sudoers.d/evobox-apt-noninteractive >/dev/null
        sudo chmod 440 /etc/sudoers.d/evobox-apt-noninteractive
        # Roll back if it fails validation, so we never wedge sudo.
        sudo visudo -cf /etc/sudoers.d/evobox-apt-noninteractive >/dev/null 2>&1 \
            || sudo rm -f /etc/sudoers.d/evobox-apt-noninteractive
    fi

    # 2. Never install printing packages (no printers on these devices).
    if [ ! -f /etc/apt/preferences.d/evobox-no-printing ]; then
        sudo tee /etc/apt/preferences.d/evobox-no-printing >/dev/null <<'EOF'
Package: cups cups-* printer-driver-* system-config-printer cups-browsed
Pin: release *
Pin-Priority: -1
EOF
    fi

    # 3. Self-heal an interrupted dpkg (e.g. apt killed mid-transaction).
    #    Triggered by dpkg_needs_repair: a pending journal or a package left
    #    half-configured. The latter catches a config that failed on a debconf
    #    prompt and never cleared. Inline var so recovery works even before the
    #    env_keep rule lands, and so `dpkg --configure -a` never re-hangs on a
    #    prompt.
    #
    #    Deliberately NOT wrapped in `timeout`: `dpkg --configure -a` may run an
    #    initramfs trigger, and interrupting that is the #28 brick class. A
    #    held lock makes dpkg fail fast instead of blocking. If the repair
    #    leaves the state broken, say so once per 12h: every apt path on the
    #    device is dead until someone looks. While a process still holds the
    #    dpkg lock the repair could not have run (a transaction just unwound by
    #    unwedge_stale_dpkg, or an operator's apt), so that case is retried on
    #    the next tick without paging anyone.
    if dpkg_needs_repair; then
        log "[APT] dpkg interrupted/bad state detected — repairing"
        run_logged sudo DEBIAN_FRONTEND=noninteractive dpkg --configure -a
        run_logged sudo DEBIAN_FRONTEND=noninteractive apt-get -f install -y
        if dpkg_needs_repair; then
            local lock_holders
            lock_holders=$(sudo fuser /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock 2>/dev/null \
                | tr -s ' ' '\n' | grep -E '^[0-9]+$' | paste -sd' ' -)
            if [ -n "$lock_holders" ]; then
                log "[APT] dpkg self-heal blocked by lock holder(s) $lock_holders — retrying next tick"
            else
                log_error "[APT] dpkg self-heal did not clear the interrupted state"
                if fresh_due "dpkg_self_heal_failed_notify" $((12 * 3600)); then
                    notify_webhook "dpkg self-heal failed: dpkg --configure -a / apt-get -f install left an interrupted or half-configured state and no process holds the dpkg lock." \
                        "EvoBox dpkg Self-Heal Alert" "warning"
                    fresh_mark "dpkg_self_heal_failed_notify"
                fi
            fi
        fi
    fi

    # 4. Purge any printing stack already installed (no printers on these
    #    devices). The pin above blocks reinstall; this removes packages that
    #    were pulled in before the pin existed. cupsd + cups-browsed otherwise
    #    run 24/7 writing /var/log/cups/* and doing mDNS printer-discovery
    #    wakeups — needless eMMC writes that work against the disk-health
    #    program. One-shot per flag version, and the flag is written only once
    #    dpkg confirms the stack is gone: a purge that fails or times out is
    #    retried (no more often than PRINTING_PURGE_RETRY_TTL) instead of being
    #    abandoned. The attempt stamp is armed BEFORE the purge so a tick killed
    #    mid-purge finds the backoff open rather than retrying at once. v2
    #    because devices like evobox-oem-0029 carry a v1 flag that was written
    #    after a purge that never ran. Runs AFTER self-heal so a wedged dpkg is
    #    cleared before we try to remove anything.
    local cups_purge_flag="$HOME/.cups_purged_v2"
    if [ ! -f "$cups_purge_flag" ]; then
        if ! printing_stack_present; then
            touch "$cups_purge_flag"
            rm -f "$HOME/.cups_purged_v1"
        elif fresh_backoff_active "printing_purge_attempt" "$PRINTING_PURGE_RETRY_TTL"; then
            log_debug "[APT] Printing-stack purge failed recently — waiting for the retry window"
        elif ! watchdog_headroom_available "$PRINTING_PURGE_BUDGET"; then
            # The worst case (PRINTING_PURGE_BUDGET) no longer fits inside the
            # watchdog window. No flag, no stamp: the next tick tries again.
            log "[APT] Deferring printing-stack purge — only ${WATCHDOG_HEADROOM_SECONDS}s of watchdog headroom left"
        else
            log "[APT] Purging unused printing stack (cups/*)"
            fresh_mark "printing_purge_attempt"
            # '^cups' / '^printer-driver-' / '^system-config-printer' are apt
            # regexes (anchored, so they skip libcups2 etc.) covering every
            # package printing_stack_present matches; autoremove sweeps
            # now-orphaned deps. run_bounded_apt_get explains the setsid /
            # timeout wrapper.
            run_bounded_apt_get "$PRINTING_PURGE_TIMEOUT" purge -y '^cups' '^printer-driver-' '^system-config-printer'
            run_bounded_apt_get "$PRINTING_AUTOREMOVE_TIMEOUT" autoremove --purge -y
            if printing_stack_present; then
                log_error "[APT] Printing stack still installed after purge — retrying in 6h"
            else
                fresh_clear "printing_purge_attempt"
                touch "$cups_purge_flag"
                rm -f "$HOME/.cups_purged_v1"
                log "[APT] Printing stack purged"
            fi
        fi
    fi
}

# Purge the desktop packages these devices never use. The cups/printing
# members go through the same bounded apt path as prepare_apt_environment's
# step 4, so a hung maintainer script can no longer wedge dpkg. The attempt
# stamp is shared with that step: a failed purge, from either path, is not
# retried until PRINTING_PURGE_RETRY_TTL has passed. This path arms the stamp
# itself because step 4 is skipped once the v2 flag exists.
remove_unwanted_packages() {
    check_command "system-config-printer" || return 0
    fresh_backoff_active "printing_purge_attempt" "$PRINTING_PURGE_RETRY_TTL" && return 0
    if ! watchdog_headroom_available "$PRINTING_PURGE_BUDGET"; then
        log "[APT] Deferring unwanted-package removal — only ${WATCHDOG_HEADROOM_SECONDS}s of watchdog headroom left"
        return 0
    fi
    fresh_mark "printing_purge_attempt"
    if run_bounded_apt_get "$PRINTING_PURGE_TIMEOUT" purge -y blueman bluez cups cups-browsed system-config-printer \
            'libreoffice*' 'transmission-*' pidgin thunderbird gnome-keyring yelp gnome-user-guide \
        && run_bounded_apt_get "$PRINTING_AUTOREMOVE_TIMEOUT" autoremove -y; then
        fresh_clear "printing_purge_attempt"
        log "[SUCCESS] Unwanted packages removed"
    else
        log_error "Failed to remove unwanted packages"
    fi
}

# One-time `apt upgrade`. This fleet runs with unattended-upgrades disabled to
# limit disk writes, so security patches are applied here instead.
#
# `upgrade`, not `full-upgrade`: it never installs NEW packages, so a kernel
# version bump is held back. That is deliberate — it keeps bootstrap from
# triggering an initramfs rebuild (the #28 brick class) and from needing a
# reboot. Measured on evo-91: 40 of 46 packages in 70s, with the
# linux-*-hwe-22.04 trio and fwupd/netplan.io held back. Kernels need their own
# rollout, not this one-shot.
#
# Flag-guarded (.evo-bootstrap-v1) because the cron loop runs the installer every
# 5 minutes, which makes an unguarded `apt upgrade` catastrophic — constant disk
# churn plus a mid-upgrade brick rippling across ~130 devices. The flag is only
# set after the upgrade succeeds, so a transient apt/network failure retries
# later. Bump the flag version to force a fleet-wide re-run.
run_bootstrap_once() {
    if [ "$BOOTSTRAP_APT_UPGRADE_PAUSED" = "true" ]; then
        log "[BOOTSTRAP][PAUSED] generic apt upgrade disabled pending Mesa reconciliation"
        return 0
    fi

    local flagfile="$HOME/.evo-bootstrap-v1"
    if [ -f "$flagfile" ]; then
        return 0
    fi

    # Fleet stagger: every device is flagless the instant this ships, so without
    # a delay all ~130 units would upgrade on the same tick (mirror hammering,
    # maximum blast radius). Each device owns one stable 5-minute bucket per 6h
    # window (72 buckets), derived from its hostname.
    #
    # The bucket MUST match the crontab's granularity: both evo_crontab and
    # evo_crontab_beta run the installer `*/5`, so a per-minute slot would only
    # ever be reached by devices whose slot happened to land on a multiple of 5 —
    # 4 in 5 devices would never bootstrap at all. `*/5` ticks land exactly on
    # epoch multiples of 300, so every device's bucket is hit once per window.
    # A failed attempt retries in 6h, not on the next tick — deliberate, an apt
    # failure looping fleet-wide is worse.
    stagger_bucket_is_due || return 0

    log "[BOOTSTRAP] Running one-time system bootstrap (apt upgrade)..."

    # Refresh package lists first. Reuses the per-session guard so we never hit
    # the mirrors twice in a single run.
    run_apt_update_if_needed

    # Invariant: step 1 (300s) + step 2 (240s) = 540s must stay under LOCK_TIMEOUT
    # (600s, measured from main() start), leaving ~60s for the rest of the tick —
    # re-check this cushion if any of the three values is ever tuned.
    #
    # 1. Download only, bounded by `timeout`. Downloads are interruptible and
    #    resumable, so a slow venue network just resumes next tick — and, since
    #    no dpkg transaction is opened, the lock watchdog can never SIGKILL us
    #    mid-unpack here.
    if ! run_logged sudo timeout 300 apt-get -d upgrade -y; then
        log_error "[BOOTSTRAP] apt upgrade download incomplete — will resume next window"
        return 1
    fi

    # 2. Install from the local cache (fast, no network). --force-confold /
    #    --force-confdef keep any locally-edited conffiles and only take the
    #    maintainer default for brand-new ones, so a non-interactive upgrade
    #    never clobbers EvoBox config or blocks on a prompt.
    #    Bounded at 240s with headroom under LOCK_TIMEOUT (600s, measured from
    #    main() start — step 1 above may already have spent 300s of it). Without
    #    this the watchdog's SIGKILL can land mid-dpkg, which is the #28
    #    corruption class; `timeout`'s SIGTERM lets dpkg unwind, and
    #    prepare_apt_environment's `dpkg --configure -a` finishes the job on the
    #    next run.
    if ! run_logged sudo DEBIAN_FRONTEND=noninteractive timeout 240 apt-get upgrade -y \
        -o Dpkg::Options::="--force-confdef" \
        -o Dpkg::Options::="--force-confold"; then
        log_error "[BOOTSTRAP] apt upgrade failed or timed out — will retry next window"
        return 1
    fi
    log "[BOOTSTRAP][SUCCESS] apt upgrade completed"

    touch "$flagfile"
    log "[BOOTSTRAP] One-time system bootstrap complete"
}

# --- APT lock (see APT_LOCK_SNAPSHOT) ----------------------------------------
# State lives in APT_LOCK_STATE_DIR, one file per stage, each holding the lock
# fingerprint it was reached for. A stage only counts for the CURRENT lock, so a
# bumped lock restarts from the top on every device without any cleanup:
#   lists    snapshot lists refreshed      ready    upgrades downloaded
#   applied  installed, or nothing to do   refused  guard refused this lock
# Each file is written once per transition, never per tick (eMMC).
apt_lock_fingerprint() {
    printf '%s\n%s\n%s\n' "$APT_LOCK_SNAPSHOT" "$APT_LOCK_PACKAGES" "$APT_LOCK_PINS" \
        | cksum | cut -d' ' -f1
}

# $1 = stage, $2 = fingerprint
apt_lock_state_is() {
    [ "$(cat "$APT_LOCK_STATE_DIR/$1" 2>/dev/null)" = "$2" ]
}

# $1 = stage, $2 = fingerprint
apt_lock_mark() {
    mkdir -p "$APT_LOCK_STATE_DIR" && printf '%s\n' "$2" > "$APT_LOCK_STATE_DIR/$1"
}

# Options that point apt at the private snapshot view. Dir::Etc::sourceparts is
# left alone on purpose: the third-party repositories in sources.list.d must
# stay visible for the pins and for dependency resolution.
apt_lock_set_opts() {
    APT_LOCK_OPTS=(
        -o "Dir::Etc::sourcelist=$APT_LOCK_VIEW_DIR/sources.list"
        -o "Dir::State::lists=$APT_LOCK_VIEW_DIR/lists"
        -o "APT::Snapshot=$APT_LOCK_SNAPSHOT"
        # Phasing picks a candidate per machine-id, so two devices on the same
        # snapshot could land on different versions. A lock is the version.
        -o "APT::Get::Always-Include-Phased-Updates=true"
        # Leave the system's binary cache alone, and skip the translation,
        # AppStream and command-not-found indexes this step never reads: they
        # are most of a snapshot refresh on a slow venue link.
        -o "Dir::Cache::pkgcache="
        -o "Dir::Cache::srcpkgcache="
        -o "Acquire::Languages=none"
        -o "Acquire::IndexTargets::deb::DEP-11::DefaultEnabled=false"
        -o "Acquire::IndexTargets::deb::DEP-11-icons-small::DefaultEnabled=false"
        -o "Acquire::IndexTargets::deb::DEP-11-icons::DefaultEnabled=false"
        -o "Acquire::IndexTargets::deb::DEP-11-icons-hidpi::DefaultEnabled=false"
        -o "Acquire::IndexTargets::deb::CNF::DefaultEnabled=false"
    )
}

# Writes the private sources file only when its content differs. Compared with
# sudo because the file is root-owned (write_if_sha_changed would always miss).
apt_lock_write_view() {
    local want
    want="# Managed by evobox-obs-daemon-install.sh (APT lock). Read only by apply_apt_lock().
deb [snapshot=yes] http://archive.ubuntu.com/ubuntu jammy main restricted universe multiverse
deb [snapshot=yes] http://archive.ubuntu.com/ubuntu jammy-updates main restricted universe multiverse
deb [snapshot=yes] http://security.ubuntu.com/ubuntu jammy-security main restricted universe multiverse"
    [ "$(sudo cat "$APT_LOCK_VIEW_DIR/sources.list" 2>/dev/null)" = "$want" ] \
        && [ -d "$APT_LOCK_VIEW_DIR/lists/partial" ] && return 0
    sudo mkdir -p "$APT_LOCK_VIEW_DIR/lists/partial" || return 1
    printf '%s\n' "$want" | sudo tee "$APT_LOCK_VIEW_DIR/sources.list" > /dev/null
}

# Ubuntu archive entries in sources.list.d would be read live, beside the
# snapshot, and silently mix versions. Refuse rather than guess. Only the names
# apt reads: .save/.distUpgrade backups beside them are not sources.
apt_lock_parts_are_third_party() {
    ! grep -rlsE --include='*.list' --include='*.sources' \
        '^[^#]*(archive|security|ports)\.ubuntu\.com' \
        "${APT_LOCK_SOURCE_PARTS:-/etc/apt/sources.list.d}/" > /dev/null 2>&1
}

# The install arguments this device needs, one per line. Every listed Ubuntu
# package is passed (--only-upgrade skips the ones that are not installed or
# already current); a pin is passed only when the device runs an older version,
# so a newer local version is never downgraded.
apt_lock_targets() {
    local p name want cur
    for p in $APT_LOCK_PACKAGES; do
        printf '%s\n' "$p"
    done
    for p in $APT_LOCK_PINS; do
        name="${p%%=*}"
        want="${p#*=}"
        cur=$(dpkg-query -W -f='${Status} ${Version}' "$name" 2>/dev/null)
        case "$cur" in
            "install ok installed "*) cur="${cur##* }" ;;
            *) continue ;;
        esac
        dpkg --compare-versions "$cur" lt "$want" && printf '%s\n' "$p"
    done
}

# Simulates the transaction and prints one "Inst <pkg>" / "Remv <pkg>" line per
# change. Returns 1, printing apt's last lines, when apt cannot plan it.
apt_lock_simulate() {
    local out rc
    out=$(apt-get "${APT_LOCK_OPTS[@]}" -s install --only-upgrade "$@" 2>&1)
    rc=$?
    if [ "$rc" -ne 0 ]; then
        printf '%s\n' "$out" | tail -n 5
        return 1
    fi
    printf '%s\n' "$out" | awk '$1 == "Inst" || $1 == "Remv" { print $1, $2 }'
}

# Reads apt_lock_simulate output on stdin. Prints the reason and returns 1 when
# the transaction removes a package, touches a kernel package (even a listed
# one: kernels are never this step's job), or touches a guarded family (Mesa,
# GPU, OBS, boot chain) that is not itself listed in the lock. An installed
# package built from the mesa source counts as Mesa whatever its binary name,
# the same definition mesa_family_inventory uses.
apt_lock_guard() {
    local verb pkg base listed p
    listed=" $APT_LOCK_PACKAGES "
    for p in $APT_LOCK_PINS; do
        listed="$listed${p%%=*} "
    done
    while read -r verb pkg; do
        [ -n "$verb" ] || continue
        base="${pkg%%:*}"
        if [ "$verb" = "Remv" ]; then
            printf 'would remove %s\n' "$pkg"
            return 1
        fi
        case "$base" in
            linux-*)
                printf 'would upgrade kernel package %s\n' "$pkg"
                return 1 ;;
        esac
        case "$listed" in *" $base "*) continue ;; esac
        if printf '%s\n' "$base" | grep -qE "$APT_LOCK_GUARD_REGEX" \
            || [ "$(dpkg-query -W -f='${source:Package}' "$pkg" 2>/dev/null)" = "mesa" ]; then
            printf 'would also upgrade guarded package %s\n' "$pkg"
            return 1
        fi
    done
    return 0
}

# live | idle | unknown. OBS not running is idle. Otherwise obs-websocket
# (port 4444, no auth, enabled by ensure_obs_websocket_enabled) is asked for
# GetStreamStatus with the daemon's own obs-websocket-js. Anything that cannot
# answer is unknown, and the caller treats unknown as live.
apt_lock_stream_state() {
    pgrep -x obs > /dev/null 2>&1 || { echo idle; return 0; }
    local node="${NVM_DIR:-$HOME/.config/nvm}/versions/node/$(node_runtime_version)/bin/node"
    [ -x "$node" ] || { echo unknown; return 0; }
    local out
    out=$(cd "$EVOSPORTS_ROOT/evo-obs-daemon-main" 2>/dev/null && timeout 20 "$node" -e '
        const say = (s) => { console.log(s); process.exit(0); };
        setTimeout(() => say("unknown"), 15000);
        let Client;
        try {
            const mod = require(require.resolve("obs-websocket-js", { paths: [process.cwd()] }));
            Client = mod && (mod.default || mod.OBSWebSocket || mod);
        } catch (e) { say("unknown"); }
        if (typeof Client !== "function") say("unknown");
        const obs = new Client();
        obs.connect("ws://127.0.0.1:4444")
            .then(() => obs.call("GetStreamStatus"))
            .then((s) => say(s && s.outputActive === true ? "live"
                : s && s.outputActive === false ? "idle" : "unknown"))
            .catch(() => say("unknown"));
    ' 2>/dev/null)
    case "$out" in
        live|idle) echo "$out" ;;
        *) echo unknown ;;
    esac
}

apt_lock_window_open() {
    local hm
    hm=$(date +%H%M)
    [ "${hm:0:2}" = "$APT_LOCK_WINDOW_HOUR" ] && [ "${hm:2:2}" -lt 10 ]
}

# True when a failed list refresh or download was tried less than
# APT_LOCK_RETRY_SECONDS ago.
apt_lock_backing_off() {
    local last
    last=$(cat "$APT_LOCK_STATE_DIR/attempt" 2>/dev/null)
    [[ "$last" =~ ^[0-9]+$ ]] || return 1
    [ $(( $(date +%s) - last )) -lt "$APT_LOCK_RETRY_SECONDS" ]
}

# Counts a repeated dead end for the current lock and pages once when it
# reaches $3. The counter file holds "<fingerprint> <count>", written once per
# event (at most a few a day), and restarts at 1 for a new lock.
# $1 = counter name, $2 = fingerprint, $3 = threshold, $4 = message
apt_lock_count_and_alert() {
    local prev_fp prev_n n=1
    { read -r prev_fp prev_n < "$APT_LOCK_STATE_DIR/$1"; } 2>/dev/null
    [ "$prev_fp" = "$2" ] && [[ "$prev_n" =~ ^[0-9]+$ ]] && n=$((prev_n + 1))
    mkdir -p "$APT_LOCK_STATE_DIR" && printf '%s %s\n' "$2" "$n" > "$APT_LOCK_STATE_DIR/$1"
    if [ "$n" -eq "$3" ]; then
        notify_webhook "APT lock $APT_LOCK_SNAPSHOT on $(hostname): $4 ($n times)" \
            "EvoBox APT lock stuck" "error"
    fi
}

# One stage per tick, so no tick holds more than one long apt call:
#   1. refresh the private snapshot lists          (stagger bucket, <=300s)
#   2. plan, guard and download the upgrades        (hourly backoff, <=300s)
#   3. install from the cache in the 05:00 window   (no network, <=240s)
# main() calls this twice. `install` runs stage 3 alone, inside the zstd-guarded
# package branch. `prefetch` runs stages 1-2 late in the tick, after the daemon
# update, telemetry and troubleshooting: a snapshot refresh took over 240s on a
# test device, and a download must never delay a daemon release.
# Stages 1-2 never open a dpkg transaction, so the watchdog can only interrupt a
# resumable download. Stage 3 needs 280s of headroom so its own 240s timeout
# lands before the watchdog's SIGKILL could (the #28 corruption class).
#
# ~/.evo-apt-lock-now skips the stagger, backoff and window for the current lock
# until that lock is applied, refused or fails to install; a device that does
# not take part removes it on sight, so it cannot carry over to a later lock.
# $1 = install | prefetch
apply_apt_lock() {
    local phase="$1" fp forced=false now_flag="$HOME/.evo-apt-lock-now" codename="" plan reason
    case "$APT_LOCK_MODE" in
        fleet) ;;
        trial) [ -f "$HOME/.evo-apt-lock-trial" ] || { rm -f "$now_flag"; return 0; } ;;
        *) rm -f "$now_flag"; return 0 ;;
    esac
    fp=$(apt_lock_fingerprint)
    if apt_lock_state_is applied "$fp" || apt_lock_state_is refused "$fp"; then
        rm -f "$now_flag"
        return 0
    fi

    codename=$(. "${APT_LOCK_OS_RELEASE:-/etc/os-release}" 2>/dev/null && printf '%s' "$VERSION_CODENAME")
    if [ "$codename" != "jammy" ]; then
        log_debug "[APT-LOCK] ${codename:-unknown} is not jammy; the lock only covers jammy"
        rm -f "$now_flag"
        return 0
    fi
    mkdir -p "$APT_LOCK_STATE_DIR"
    [ -f "$now_flag" ] && forced=true
    apt_lock_set_opts
    local -a targets=()
    local t

    if [ "$phase" = "prefetch" ]; then
        # --- 1. snapshot lists -----------------------------------------------
        if ! apt_lock_state_is lists "$fp"; then
            $forced || stagger_bucket_is_due || return 0
            $forced || ! apt_lock_backing_off || return 0
            if ! watchdog_headroom_available 330; then
                log "[APT-LOCK] Deferring list refresh — only ${WATCHDOG_HEADROOM_SECONDS:-unreadable}s of watchdog headroom"
                return 0
            fi
            if ! apt_lock_parts_are_third_party; then
                date +%s > "$APT_LOCK_STATE_DIR/attempt" 2>/dev/null
                log_error "[APT-LOCK] sources.list.d holds Ubuntu archive entries; refusing to mix them with the snapshot"
                apt_lock_count_and_alert parts-refusal "$fp" 1 "sources.list.d holds Ubuntu archive entries"
                return 1
            fi
            apt_lock_write_view || { log_error "[APT-LOCK] Could not write $APT_LOCK_VIEW_DIR"; return 1; }
            log "[APT-LOCK] Lock $fp ($APT_LOCK_SNAPSHOT) not applied — refreshing snapshot lists"
            # --error-on=any: plain `apt-get update` exits 0 when an index
            # fails to download, and a plan made from missing lists can come
            # back empty and mark the lock applied on stale versions.
            if ! run_logged sudo timeout 300 apt-get "${APT_LOCK_OPTS[@]}" --error-on=any update; then
                date +%s > "$APT_LOCK_STATE_DIR/attempt" 2>/dev/null
                log_error "[APT-LOCK] Snapshot list refresh incomplete — retrying later"
                apt_lock_count_and_alert failures "$fp" "$APT_LOCK_ALERT_AFTER_FAILURES" "list refresh, plan or download keeps failing"
                return 1
            fi
            apt_lock_mark lists "$fp"
            return 0
        fi

        # --- 2. plan, guard, download ------------------------------------------
        apt_lock_state_is ready "$fp" && return 0
        $forced || ! apt_lock_backing_off || return 0
        if ! watchdog_headroom_available 330; then
            log "[APT-LOCK] Deferring download — only ${WATCHDOG_HEADROOM_SECONDS:-unreadable}s of watchdog headroom"
            return 0
        fi
        while IFS= read -r t; do
            [ -n "$t" ] && targets+=("$t")
        done < <(apt_lock_targets)
        if ! plan=$(apt_lock_simulate "${targets[@]}"); then
            date +%s > "$APT_LOCK_STATE_DIR/attempt" 2>/dev/null
            log_error "[APT-LOCK] apt could not plan lock $fp: $(printf '%s' "$plan" | tr '\n' ' ')"
            apt_lock_count_and_alert failures "$fp" "$APT_LOCK_ALERT_AFTER_FAILURES" "list refresh, plan or download keeps failing"
            return 1
        fi
        if [ -z "$plan" ]; then
            apt_lock_mark applied "$fp"
            rm -f "$now_flag"
            log "[APT-LOCK] Lock $fp ($APT_LOCK_SNAPSHOT) already satisfied — nothing to install"
            return 0
        fi
        if ! reason=$(printf '%s\n' "$plan" | apt_lock_guard); then
            apt_lock_mark refused "$fp"
            rm -f "$now_flag"
            log_error "[APT-LOCK] Refusing lock $fp: $reason"
            notify_webhook "APT lock $APT_LOCK_SNAPSHOT refused on $(hostname): $reason. Plan: $(printf '%s' "$plan" | tr '\n' ',')" \
                "EvoBox APT lock refused" "error"
            return 1
        fi
        log "[APT-LOCK] Downloading: $(printf '%s' "$plan" | tr '\n' ' ')"
        if ! run_logged sudo timeout 300 apt-get "${APT_LOCK_OPTS[@]}" -d -y install --only-upgrade "${targets[@]}"; then
            date +%s > "$APT_LOCK_STATE_DIR/attempt" 2>/dev/null
            log_error "[APT-LOCK] Download incomplete — retrying later"
            apt_lock_count_and_alert failures "$fp" "$APT_LOCK_ALERT_AFTER_FAILURES" "list refresh, plan or download keeps failing"
            return 1
        fi
        apt_lock_mark ready "$fp"
        return 0
    fi

    # --- 3. install in the window ----------------------------------------------
    [ "$phase" = "install" ] || return 0
    apt_lock_state_is ready "$fp" || return 0
    local in_window=false stream
    apt_lock_window_open && in_window=true
    $in_window || $forced || return 0
    stream=$(apt_lock_stream_state)
    if [ "$stream" != "idle" ]; then
        log "[APT-LOCK] OBS stream is $stream — leaving lock $fp for the next window"
        # Only a real window counts toward the alert; a forced tick outside it
        # would otherwise page after half an hour of a test device streaming.
        $in_window && apt_lock_count_and_alert stream-skips "$fp" "$APT_LOCK_ALERT_AFTER_SKIPS" "install window skipped, OBS stream $stream"
        return 0
    fi
    # Re-plan against the same lists: the device may have changed since the
    # download (another step installed something), and the guard must judge
    # the transaction that is about to run, not yesterday's.
    while IFS= read -r t; do
        [ -n "$t" ] && targets+=("$t")
    done < <(apt_lock_targets)
    if ! plan=$(apt_lock_simulate "${targets[@]}"); then
        # Not a refusal: a held dpkg lock or a half-configured package also
        # fails here, and the next window may plan cleanly.
        log_error "[APT-LOCK] apt could not re-plan lock $fp at install time: $(printf '%s' "$plan" | tr '\n' ' ')"
        apt_lock_count_and_alert failures "$fp" "$APT_LOCK_ALERT_AFTER_FAILURES" "list refresh, plan or download keeps failing"
        return 1
    fi
    if ! reason=$(printf '%s\n' "$plan" | apt_lock_guard); then
        apt_lock_mark refused "$fp"
        rm -f "$now_flag"
        log_error "[APT-LOCK] Refusing lock $fp at install time: $reason"
        notify_webhook "APT lock $APT_LOCK_SNAPSHOT refused at install time on $(hostname): $reason" \
            "EvoBox APT lock refused" "error"
        return 1
    fi
    if [ -z "$plan" ]; then
        apt_lock_mark applied "$fp"
        rm -f "$now_flag"
        log "[APT-LOCK] Lock $fp already satisfied at install time"
        return 0
    fi
    if ! watchdog_headroom_available 280; then
        log "[APT-LOCK] Deferring install — only ${WATCHDOG_HEADROOM_SECONDS:-unreadable}s of watchdog headroom"
        return 0
    fi
    log "[APT-LOCK] Installing lock $fp: $(printf '%s' "$plan" | tr '\n' ' ')"
    if ! run_logged sudo DEBIAN_FRONTEND=noninteractive timeout 240 apt-get "${APT_LOCK_OPTS[@]}" \
        -y --no-download install --only-upgrade \
        -o Dpkg::Options::="--force-confdef" \
        -o Dpkg::Options::="--force-confold" "${targets[@]}"; then
        # Back to stage 2: if the cached .debs are what failed (--no-download
        # cannot fetch a missing one), the next attempt must download again.
        # The now flag goes too, so a broken package is not retried every
        # other tick outside the window.
        rm -f "$APT_LOCK_STATE_DIR/ready" "$now_flag"
        date +%s > "$APT_LOCK_STATE_DIR/attempt" 2>/dev/null
        log_error "[APT-LOCK] Install of lock $fp failed — re-downloading, then retrying in the next window"
        apt_lock_count_and_alert install-failed "$fp" 1 "install failed; retrying in the next 05:00 window"
        return 1
    fi
    # Only an empty re-plan proves the device reached the lock.
    plan=$(apt_lock_simulate "${targets[@]}")
    if [ -n "$plan" ]; then
        log_error "[APT-LOCK] apt reported success but lock $fp still plans: $(printf '%s' "$plan" | tr '\n' ' ')"
        apt_lock_count_and_alert replan-leftover "$fp" 1 "apt reported success but the lock still plans: $(printf '%s' "$plan" | tr '\n' ' ')"
        return 1
    fi
    apt_lock_mark applied "$fp"
    rm -f "$now_flag"
    log "[APT-LOCK][SUCCESS] Lock $fp ($APT_LOCK_SNAPSHOT) applied"
}

install_system_dependencies() {
    prepare_apt_environment
    remove_unwanted_packages

    # Install curl
    if ! check_command "curl"; then
        run_apt_update_if_needed
        if sudo apt-get install -y curl 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] curl installed"
        else
            log_error "Failed to install curl"
        fi
    fi

    # Install Google Chrome
    if ! check_command "google-chrome-stable"; then
        if wget --timeout=20 --tries=2 -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub 2>/dev/null | sudo apt-key add - 2>/dev/null && \
           echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee /etc/apt/sources.list.d/google-chrome.list > /dev/null && \
           sudo apt update 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG" && \
           sudo apt install -y google-chrome-stable 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] Google Chrome installed"
        else
            log_error "Failed to install Google Chrome"
        fi
    fi

    # Ensure OBS PPA is available (for dependency resolution by archive installs)
    if ! ls /etc/apt/sources.list.d/*obsproject* 2>/dev/null | grep -q .; then
        sudo add-apt-repository ppa:obsproject/obs-studio -y 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"
        sudo apt-get update 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"
    fi

    # Install Node.js and npm
    if ! check_command "node"; then
        run_apt_update_if_needed
        if sudo apt install -y nodejs 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] nodejs installed"
        else
            log_error "Failed to install nodejs"
        fi
    fi

    if ! check_command "npm"; then
        run_apt_update_if_needed
        if sudo apt install -y npm 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] npm installed"
        else
            log_error "Failed to install npm"
        fi
    fi

    # Install jq
    if ! check_command "jq"; then
        run_apt_update_if_needed
        if sudo apt install -y jq 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] jq installed"
        else
            log_error "Failed to install jq"
        fi
    fi

    # Ensure the probe's non-optional GStreamer plugins are present. The
    # probe's setup command owns the optional bad/ugly plugin installation.
    if [ "$(dpkg-query -W -f='${db:Status-Abbrev}' gstreamer1.0-plugins-base 2>/dev/null)" != "ii " ] || \
       [ "$(dpkg-query -W -f='${db:Status-Abbrev}' gstreamer1.0-plugins-good 2>/dev/null)" != "ii " ]; then
        run_apt_update_if_needed
        if sudo apt-get install -y gstreamer1.0-plugins-base gstreamer1.0-plugins-good >> "$EVOSPORTS_INSTALL_LOG" 2>&1; then
            log "[SUCCESS] GStreamer base and good plugins installed"
        else
            log_error "Failed to install GStreamer base and good plugins"
        fi
    fi

    # Check for gnome-screensaver-command
    if ! check_command "gnome-screensaver-command"; then
        log_debug "gnome-screensaver-command not installed, skipping"
    fi

    # Install pavucontrol
    if ! check_command "pavucontrol"; then
        run_apt_update_if_needed
        if sudo apt-get install -y pavucontrol 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] pavucontrol installed"
        else
            log_error "Failed to install pavucontrol"
        fi
    fi

    # Skip TeamViewer (deprecated)
    if ! check_command "teamviewer"; then
        log_debug "TeamViewer host not installed due to deprecation"
    fi

    # Install Splashtop — TEMPORARILY DISABLED (re-enable by uncommenting)
    # if ! check_command "splashtop-streamer"; then
    #     install_splashtop_host
    # fi

    # Install v4l2loopback
    if ! check_command "v4l2loopback-ctl"; then
        run_apt_update_if_needed
        if sudo apt install -y v4l2loopback-utils v4l2loopback-dkms 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] v4l2loopback installed"
        else
            log_error "Failed to install v4l2loopback"
        fi
    fi

    # Install net-tools
    if ! check_command "ifconfig"; then
        run_apt_update_if_needed
        if sudo apt install -y net-tools 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] net-tools installed"
        else
            log_error "Failed to install net-tools"
        fi
    fi

    # Install ffmpeg
    if ! check_command "ffmpeg"; then
        run_apt_update_if_needed
        if sudo apt install -y ffmpeg 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] ffmpeg installed"
        else
            log_error "Failed to install ffmpeg"
        fi
    fi

    # Install nginx
    if ! check_command "nginx"; then
        if curl --connect-timeout 20 --max-time 30 --retry 2 -o setup-mediaserver.sh "${GCS_NGINX}/setup-mediaserver.sh" 2>/dev/null && \
           chmod +x setup-mediaserver.sh && \
           mkdir -p "$HOME/media" && \
           bash setup-mediaserver.sh 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] nginx installed"
        else
            log_error "Failed to install nginx"
        fi
    fi

    # Install python3-pip
    if ! check_command "pip3"; then
        run_apt_update_if_needed
        if sudo apt install -y python3-pip 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] python3-pip installed"
        else
            log_error "Failed to install python3-pip"
        fi
    fi

    # Unattended-upgrades disabled — apt timers are masked by setup_disk_health_phase1()
    # to reduce disk writes. Security patches are handled manually via the install script.

    # Install avahi-utils
    if ! check_command "avahi-browse"; then
        if sudo apt install -y avahi-utils 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] avahi utilities installed"
        else
            log_error "Failed to install avahi-utils"
        fi
    fi

    # Install speedtest-cli
    if ! check_command "speedtest-cli"; then
        if sudo apt install -y speedtest-cli 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
            log "[SUCCESS] speedtest-cli installed"
        else
            log_error "Failed to install speedtest-cli"
        fi
    fi
}

# True iff NVM_DIR contains a complete nvm checkout we can source.
# Heuristic: nvm.sh present AND non-empty AND the upstream git repo metadata
# is present (the installer's `git clone` populates .git). A bare/empty/half-
# cloned NVM_DIR fails this check and triggers a wipe-and-reinstall.
_nvm_install_healthy() {
    [ -s "$NVM_DIR/nvm.sh" ] && [ -d "$NVM_DIR/.git" ]
}

# Idempotently ensure ~/.bashrc has the canonical NVM init lines.
# Reference pattern (matches the fleet's pre-fix working installs, e.g.
# evobox-oem-0093):
#   export NVM_DIR="$HOME/.config/nvm"
#   [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
#   [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
#
# Why .bashrc specifically: when an operator SSHes in and gets an
# interactive shell, ~/.bashrc is sourced and nvm.sh auto-activates the
# `default` alias (kept equal to NODE_VERSION), putting `node`/`npm` on PATH so `npm ci` and
# other diagnostic commands just work. The upstream nvm installer normally
# picks .bashrc on its own, but in cron context (SHELL=/bin/sh, no TTY)
# it falls back to .profile — diverging the fleet. We force .bashrc here
# regardless of which file the upstream installer chose.
ensure_nvm_bashrc_init() {
    local rcfile="$HOME/.bashrc"
    [ -f "$rcfile" ] || touch "$rcfile"

    # Skip if the canonical export already lives in .bashrc (existing fleet
    # devices that were installed under interactive bash). Don't double-write.
    if grep -qF 'NVM_DIR="$HOME/.config/nvm"' "$rcfile"; then
        return 0
    fi

    log "[NVM] Appending canonical NVM init lines to $rcfile"
    {
        echo ''
        echo 'export NVM_DIR="$HOME/.config/nvm"'
        echo '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm'
        echo '[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion'
    } >> "$rcfile"
}

# Remove the legacy ~/.nvm install path and rewrite ~/.profile to point at
# the canonical ~/.config/nvm. Devices that ran an older version of this
# script (pre-fix) had nvm installed to ~/.nvm because NVM_DIR wasn't
# exported before piping to the upstream installer. The upstream installer
# also wrote ~/.profile with NVM_DIR=~/.nvm. Once we corrected install_nvm,
# the cron-run script uses ~/.config/nvm, but interactive logins still
# source from ~/.nvm — leaving users with `nvm use node` failing because
# Node lives in the OTHER path. Idempotent: no-op once cleaned up.
cleanup_legacy_nvm() {
    local legacy="$HOME/.nvm"
    local current="$HOME/.config/nvm"

    # Only act when both: legacy dir exists, AND current install is healthy
    # enough to take over interactive shells.
    if [ ! -d "$legacy" ] || [ ! -s "$current/nvm.sh" ]; then
        return 0
    fi

    log "[NVM] Removing legacy install at $legacy (canonical path is $current)"
    rm -rf "$legacy"

    # Rewrite stale ~/.profile entries from the legacy installer so the
    # next interactive login picks up the correct NVM_DIR. Match both the
    # `$HOME/.nvm` form and a literal `/home/evobox/.nvm` form.
    if [ -f "$HOME/.profile" ]; then
        if grep -qE '(\$HOME/\.nvm|/home/evobox/\.nvm)' "$HOME/.profile"; then
            log "[NVM] Updating ~/.profile NVM_DIR pointer to $current"
            sed -i \
                -e 's|\$HOME/\.nvm|$HOME/.config/nvm|g' \
                -e 's|/home/evobox/\.nvm|/home/evobox/.config/nvm|g' \
                "$HOME/.profile"
        fi
    fi
}

# True iff $1 (vMAJOR.MINOR.PATCH) is installed under NVM_DIR and its node
# binary runs and reports exactly that version. A bare `-x` is not enough: a
# power cut mid-extract leaves an executable file that cannot start (the same
# shape as the 0-byte trees daemon_trees_ok() guards against), and nvm would
# still call that version installed.
_node_version_usable() {
    local version="$1"
    local node_bin="${NVM_DIR:-$HOME/.config/nvm}/versions/node/$version/bin/node"
    [ -x "$node_bin" ] || return 1
    [ "$("$node_bin" --version 2>/dev/null)" = "$version" ]
}

# Point nvm's `default` alias at $1. Login shells and the runner's last-resort
# fallback follow it, and `nvm install` never moves an alias that already
# exists, so devices provisioned on the previous runtime would otherwise keep
# handing operators Node 20 forever. `nvm alias` rewrites the alias file every
# time it runs, so compare first: an unguarded call is an eMMC write per tick.
_nvm_set_default_alias() {
    local version="$1" current
    current="$(cat "$NVM_DIR/alias/default" 2>/dev/null)"
    if [ "$current" = "$version" ]; then
        return 0
    fi
    if ! nvm alias default "$version" >/dev/null 2>&1; then
        log_error "[NODE] nvm alias default $version failed"
        return 1
    fi
    log "[NODE] nvm default alias ${current:-<unset>} -> $version"
    return 0
}

# Ensure $NODE_VERSION is installed via nvm and runs. Idempotent: it does
# nothing when a working copy is already on disk. Defensively re-sources nvm.sh
# if `nvm` isn't already on PATH (callers like download_evobox_daemon may
# run in a code path where install_nvm hasn't yet executed in this shell —
# e.g., a daemon-version bump triggers download_evobox_daemon before
# anything else has touched nvm). Returns 0 on success, 1 on any failure.
ensure_node_installed() {
    if ! command -v nvm >/dev/null 2>&1; then
        export NVM_DIR="${NVM_DIR:-$HOME/.config/nvm}"
        # shellcheck disable=SC1091
        [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
    fi

    # On-disk binary check, not `nvm ls <ver>`: that proved unreliable in
    # non-TTY cron shells — it returned non-zero even when the version was
    # clearly installed, causing every cron tick to redundantly call
    # `nvm install` (idempotent but wasted ~7s/tick and polluted logs). The
    # binary must also run, see _node_version_usable().
    if _node_version_usable "$NODE_VERSION"; then
        return 0
    fi

    if ! command -v nvm >/dev/null 2>&1; then
        log_error "[NODE] nvm not available — cannot install Node $NODE_VERSION"
        return 1
    fi

    # A device that already runs a working fallback loses nothing by waiting, so
    # a failed install backs off instead of re-downloading ~30 MB to eMMC every
    # tick. A device with no usable Node at all must keep retrying every tick,
    # so the backoff does not apply to it.
    if [ "$NODE_VERSION" != "$NODE_FALLBACK_VERSION" ] \
       && _node_version_usable "$NODE_FALLBACK_VERSION" \
       && fresh_backoff_active "node_install_failed" "$NODE_INSTALL_RETRY_TTL"; then
        log_debug "[NODE] Skipping $NODE_VERSION install (failed <${NODE_INSTALL_RETRY_TTL}s ago; staying on $NODE_FALLBACK_VERSION)"
        return 1
    fi

    # The directory exists but its node does not run: a half-extracted install.
    # `nvm install` treats an existing directory as installed and would leave it
    # broken, so clear exactly that directory first. The version is a readonly
    # constant, but it ends up in an `rm -rf` path, so check its shape anyway.
    local node_dir="$NVM_DIR/versions/node/$NODE_VERSION"
    if [ -e "$node_dir" ]; then
        if ! [[ "$NODE_VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            log_error "[NODE] NODE_VERSION '$NODE_VERSION' is not vMAJOR.MINOR.PATCH; refusing to clear $node_dir"
            return 1
        fi
        log "[NODE] $NODE_VERSION is present but its node binary does not run; removing it before reinstalling"
        rm -rf "$node_dir"
    fi

    log "[NODE] $NODE_VERSION not installed — installing via nvm"
    if ! nvm install "$NODE_VERSION"; then
        log_error "[NODE] nvm install $NODE_VERSION failed"
        fresh_mark "node_install_failed"
        return 1
    fi
    if ! _node_version_usable "$NODE_VERSION"; then
        log_error "[NODE] nvm install $NODE_VERSION reported success but its node binary does not run"
        fresh_mark "node_install_failed"
        return 1
    fi
    fresh_clear "node_install_failed"
    log "[SUCCESS] Node $NODE_VERSION installed"
    return 0
}

install_nvm() {
    # Export NVM_DIR BEFORE invoking the upstream installer so it honors our
    # path (otherwise nvm defaults to $HOME/.nvm and writes a mismatched
    # snippet into ~/.profile). Keep it exported on success so downstream
    # functions in this script can find `nvm`.
    export NVM_DIR="$HOME/.config/nvm"

    # Two-attempt loop. Attempt 1 reuses an existing NVM_DIR if it looks
    # healthy. Attempt 2 wipes NVM_DIR and reinstalls from scratch. Recovery
    # cases this covers:
    #   - NVM_DIR is set in env but the directory is missing or empty
    #   - Half-finished install (nvm.sh missing or corrupted)
    #   - nvm.sh sources cleanly but `nvm` isn't on PATH afterwards
    #   - `nvm install $NODE_VERSION` fails and no fallback runtime is usable
    #     (a device that still has NODE_FALLBACK_VERSION never reaches attempt
    #     2 for that reason: the wipe would delete the only working Node)
    local attempt
    for attempt in 1 2; do
        # Decide whether to (re)install. On attempt 2 we always wipe-and-
        # reinstall, regardless of whether the dir looks healthy — we got
        # here because something downstream failed, and the next-best
        # explanation is a corrupted checkout.
        local needs_install=0
        if [ "$attempt" -eq 2 ]; then
            log "[NVM] Retrying with a clean install (attempt $attempt)"
            rm -rf "$NVM_DIR"
            needs_install=1
        elif ! _nvm_install_healthy; then
            log "[NVM] $NVM_DIR missing or incomplete — installing fresh"
            # Wipe any partial state so the upstream installer's `git clone`
            # doesn't trip over a non-empty/non-repo directory.
            rm -rf "$NVM_DIR"
            needs_install=1
        fi

        if [ "$needs_install" -eq 1 ]; then
            mkdir -p "$NVM_DIR"
            # Force the upstream installer to write its source-string into
            # ~/.bashrc (matching 0093's reference pattern). Without PROFILE
            # set, nvm's profile-detection picks ~/.profile under cron's
            # SHELL=/bin/sh, fragmenting the fleet across two profile files.
            if ! curl --connect-timeout 20 --max-time 60 --retry 2 -o- \
                https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | \
                PROFILE="$HOME/.bashrc" bash; then
                log_error "[NVM] Installer download/run failed (attempt $attempt)"
                continue
            fi
            if ! _nvm_install_healthy; then
                log_error "[NVM] Install reported success but $NVM_DIR/nvm.sh missing (attempt $attempt)"
                continue
            fi
            log "[SUCCESS] NVM installed at $NVM_DIR (attempt $attempt)"
        fi

        # Source nvm into the current shell. `unset -f nvm` first so a
        # previously-defined (and possibly broken) shell function from
        # attempt 1 doesn't shadow the freshly-sourced one.
        unset -f nvm 2>/dev/null || true
        # shellcheck disable=SC1091
        \. "$NVM_DIR/nvm.sh"
        [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

        if ! command -v nvm >/dev/null 2>&1; then
            log_error "[NVM] nvm command not available after sourcing $NVM_DIR/nvm.sh (attempt $attempt)"
            continue
        fi

        # Install + activate the requested Node version. ensure_node_installed
        # short-circuits if a working copy is already present.
        local node_ready=0
        if ensure_node_installed && nvm use "$NODE_VERSION"; then
            node_ready=1
        fi

        if [ "$node_ready" -eq 1 ]; then
            log "[SUCCESS] Node $NODE_VERSION active via NVM"
            log_debug "NVM applied"
        elif [ "$NODE_VERSION" != "$NODE_FALLBACK_VERSION" ] \
             && _node_version_usable "$NODE_FALLBACK_VERSION" \
             && nvm use "$NODE_FALLBACK_VERSION"; then
            # A failed Node install says nothing about the nvm checkout, so do
            # NOT fall through to attempt 2: it wipes $NVM_DIR, which would take
            # the working fallback runtime with it and leave the device with no
            # Node at all. The daemon runner falls back the same way, and the
            # next tick (after NODE_INSTALL_RETRY_TTL) tries NODE_VERSION again.
            log_error "[NODE] Node $NODE_VERSION unavailable, device stays on $NODE_FALLBACK_VERSION; will retry"
        else
            log_error "[NVM] Node bootstrap failed (attempt $attempt)"
            continue
        fi

        # Unify shell behavior across the fleet. cleanup_legacy_nvm purges
        # ~/.nvm + corrects stale .profile pointers from earlier broken
        # installs; ensure_nvm_bashrc_init guarantees .bashrc has the
        # canonical 3 lines so interactive logins (SSH) auto-load nvm and
        # activate the `default` Node version — meaning operators can run
        # `npm ci` immediately after sshing in.
        cleanup_legacy_nvm
        ensure_nvm_bashrc_init

        return 0
    done

    log_error "[NVM] Exhausted retries — bootstrap failed"
    return 1
}

# Install pnpm globally into the nvm-managed Node toolchain. Idempotent:
# skips when the installed version matches $PNPM_VERSION. Required because
# the daemon and ad-hoc operator workflows are migrating from `npm ci` to
# `pnpm install` for faster installs. Failure is non-fatal — `npm` still
# works, and the daemon's package manager fallback handles the absence of
# pnpm gracefully.
install_pnpm() {
    # Defensively re-source nvm if `npm` isn't on PATH yet. install_pnpm is
    # called immediately after install_nvm in main(), so this is normally
    # already set up — but make the function robust to other call orders.
    if ! command -v npm >/dev/null 2>&1; then
        export NVM_DIR="${NVM_DIR:-$HOME/.config/nvm}"
        # shellcheck disable=SC1091
        [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
    fi

    if ! command -v npm >/dev/null 2>&1; then
        log_error "[PNPM] npm not available — cannot install pnpm"
        return 1
    fi

    if command -v pnpm >/dev/null 2>&1; then
        local current
        current=$(pnpm --version 2>/dev/null)
        if [ "$current" = "$PNPM_VERSION" ]; then
            return 0
        fi
        log "[PNPM] Installed v$current differs from pinned v$PNPM_VERSION — updating"
    else
        log "[PNPM] Not installed — installing v$PNPM_VERSION"
    fi

    if ! run_logged npm install -g "pnpm@$PNPM_VERSION"; then
        log_error "[PNPM] npm install -g pnpm@$PNPM_VERSION failed"
        return 1
    fi

    log "[SUCCESS] pnpm v$PNPM_VERSION installed"
}

# Return the runtime that generated launchers and units should use. NODE_VERSION
# is eligible only after its complete per-Node toolchain exists and nvm's
# default alias has committed the cutover. Until then an existing device stays
# wholly on NODE_FALLBACK_VERSION. Fresh devices with no fallback still name
# NODE_VERSION so their unit converges as soon as the next install succeeds.
node_runtime_version() {
    local nvm_dir="${NVM_DIR:-$HOME/.config/nvm}"
    local node_bin="$nvm_dir/versions/node/$NODE_VERSION/bin/node"
    local pnpm_bin="$nvm_dir/versions/node/$NODE_VERSION/bin/pnpm"
    local default_alias=""
    default_alias="$(cat "$nvm_dir/alias/default" 2>/dev/null)"
    if [ -x "$node_bin" ] \
       && [ "$("$node_bin" --version 2>/dev/null)" = "$NODE_VERSION" ] \
       && [ -x "$pnpm_bin" ] \
       && [ "$("$pnpm_bin" --version 2>/dev/null)" = "$PNPM_VERSION" ] \
       && [ "$default_alias" = "$NODE_VERSION" ]; then
        printf '%s' "$NODE_VERSION"
    elif _node_version_usable "$NODE_FALLBACK_VERSION"; then
        printf '%s' "$NODE_FALLBACK_VERSION"
    else
        printf '%s' "$NODE_VERSION"
    fi
}

# Prepare and atomically commit the Node major cutover. install_nvm() may
# activate NODE_VERSION, but units and login shells do not move until pnpm is
# installed into that per-Node toolchain and the default alias changes. Any
# failure on an existing device restores the fallback before main() renders the
# runner and systemd units later in the tick.
install_node_toolchain() {
    if ! install_nvm; then
        return 1
    fi

    local active_version=""
    active_version="$(node --version 2>/dev/null)"
    if [ "$active_version" = "$NODE_VERSION" ]; then
        if install_pnpm && _nvm_set_default_alias "$NODE_VERSION"; then
            log "[SUCCESS] Node toolchain $NODE_VERSION ready (pnpm v$PNPM_VERSION)"
            return 0
        fi
        log_error "[NODE] Node $NODE_VERSION toolchain incomplete; restoring $NODE_FALLBACK_VERSION"
    fi

    if [ "$NODE_VERSION" != "$NODE_FALLBACK_VERSION" ] \
       && _node_version_usable "$NODE_FALLBACK_VERSION" \
       && nvm use "$NODE_FALLBACK_VERSION"; then
        install_pnpm || log_error "[NODE] pnpm unavailable on fallback $NODE_FALLBACK_VERSION"
        _nvm_set_default_alias "$NODE_FALLBACK_VERSION" || true
        log_error "[NODE] Device remains on fallback toolchain $NODE_FALLBACK_VERSION"
        return 0
    fi

    log_error "[NODE] No fallback runtime available after $NODE_VERSION toolchain failure"
    return 1
}


install_intel_gpu_driver() {
    if ! check_package_installed clinfo; then
        install_intel_driver
        log "Intel iGPU driver installed"
    fi
    repair_mesa_package_family
}

repair_mesa_package_family() {
    local inventory="$MESA_FAMILY_DIAGNOSIS_INVENTORY"
    local state="${MESA_FAMILY_DIAGNOSIS_STATE:-unknown}"
    local operands_text current_inventory current_state
    local -a operands
    local download_start download_end unpack_start unpack_end operand
    local download_seconds=unknown unpack_seconds=unknown audit

    [ "$state" = "inconsistent" ] || return 0
    stagger_bucket_is_due || return 0
    if fresh_backoff_active "mesa_package_repair_attempt" "$MESA_REPAIR_RETRY_TTL"; then
        log_debug "[MESA] Repair skipped (failure retry backoff active)"
        return 0
    fi

    # Not mapfile: it is a bash 4 builtin and the fixtures run on macOS bash 3.2.
    operands_text="$(mesa_family_operands "$inventory")"
    [ -n "$operands_text" ] || {
        log_error "[MESA] Package inventory has no installed operands; repair skipped"
        fresh_mark "mesa_package_repair_attempt"
        return 1
    }
    while IFS= read -r operand; do
        operands+=("$operand")
    done <<< "$operands_text"

    # Simulation is deliberately separate from the resumable download.
    # -y throughout: run_logged redirects stdin from /dev/null, so any apt
    # confirmation prompt reads EOF and aborts the whole repair.
    if ! run_logged sudo DEBIAN_FRONTEND=noninteractive apt-get --simulate --no-remove install -y "${operands[@]}"; then
        log_error "[MESA] Repair simulation failed"
        fresh_mark "mesa_package_repair_attempt"
        return 1
    fi

    download_start="$(read_uptime_seconds)"
    if ! run_logged sudo DEBIAN_FRONTEND=noninteractive apt-get -d --no-remove install -y "${operands[@]}"; then
        log_error "[MESA] Repair package download incomplete"
        fresh_mark "mesa_package_repair_attempt"
        return 1
    fi
    download_end="$(read_uptime_seconds)"
    [ -n "$download_start" ] && [ -n "$download_end" ] && download_seconds=$(( download_end - download_start ))
    log "[MESA] Repair download seconds: $download_seconds"

    # The three guards below are deferrals, not failures: nothing is mutated yet
    # and the downloaded archives stay in apt's cache, so the next stagger slot
    # resumes for free. None of them may arm the retry backoff — OBS is running
    # for most of the day at a live venue, and a 12h backoff on that would cost
    # the device its "heals within one stagger window" guarantee.
    current_inventory="$(mesa_family_inventory)"
    if [ "$current_inventory" != "$inventory" ]; then
        log "[MESA] Inventory changed since diagnosis; install next window"
        return 0
    fi
    if ! watchdog_headroom_available; then
        log "[MESA] Watchdog headroom below 300s; install next window (remaining=${WATCHDOG_HEADROOM_SECONDS:-unreadable})"
        return 0
    fi
    if pgrep -x obs >/dev/null 2>&1; then
        # This is not a real idle signal: an OBS launch during unpack can fail,
        # but the daemon retry loop recovers it in ~13s (issue #46: 0042, 0047,
        # and 0057), with no manual start.
        log "[MESA] OBS is running; install next window"
        return 0
    fi

    # Arm the retry backoff immediately before the only step that is unsafe to
    # interrupt. A SIGKILL inside dpkg must not let the next stagger slot start
    # a second unpack on a half-configured tree.
    fresh_mark "mesa_package_repair_attempt"
    unpack_start="$(read_uptime_seconds)"
    if ! run_logged sudo DEBIAN_FRONTEND=noninteractive apt-get --no-download --no-remove install -y "${operands[@]}"; then
        log_error "[MESA] Package install failed"
        return 1
    fi
    unpack_end="$(read_uptime_seconds)"
    [ -n "$unpack_start" ] && [ -n "$unpack_end" ] && unpack_seconds=$(( unpack_end - unpack_start ))
    log "[MESA] Repair unpack seconds: $unpack_seconds"

    current_state="$(mesa_family_state "$(mesa_family_inventory)")"
    if [ "$current_state" != "healthy" ]; then
        log_error "[MESA] Package family verification failed: $current_state"
        return 1
    fi
    if ! audit="$(dpkg --audit 2>&1)" || [ -n "$audit" ]; then
        log_error "[MESA] dpkg audit is not clean: ${audit:-non-zero exit}"
        return 1
    fi
    if ! run_logged sudo apt-get check; then
        log_error "[MESA] apt-get check failed after package repair"
        return 1
    fi

    # No success stamp: the derived family state is the only record this needs,
    # and it is re-read every tick. Releasing the retry backoff is the whole
    # bookkeeping, so a device that regresses later is eligible immediately.
    log "[MESA][SUCCESS] Mesa packages repaired (download=${download_seconds}s, unpack=${unpack_seconds}s)"
    fresh_clear "mesa_package_repair_attempt"
}

disable_ipv6() {
    local ipv6_flagfile="/home/evobox/.ipv6_disabled_v3"
    if [ -f "$ipv6_flagfile" ]; then
        return
    fi

    # Kernel: disable IPv6 via sysctl
    sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1 > /dev/null 2>&1
    sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1 > /dev/null 2>&1

    # Persist sysctl if not already in sysctl.conf
    if ! grep -q "net.ipv6.conf.all.disable_ipv6=1" /etc/sysctl.conf 2>/dev/null; then
        echo "net.ipv6.conf.all.disable_ipv6=1" | sudo tee -a /etc/sysctl.conf > /dev/null
        echo "net.ipv6.conf.default.disable_ipv6=1" | sudo tee -a /etc/sysctl.conf > /dev/null
        sudo sysctl -p > /dev/null 2>&1
    fi

    # NetworkManager: set ipv6.method to disabled on wired connection (no reconnect)
    local active_wired
    active_wired=$(nmcli -t -f NAME,TYPE connection show --active 2>/dev/null | grep ethernet | cut -d: -f1)
    if [ -n "$active_wired" ]; then
        sudo nmcli connection modify "$active_wired" ipv6.method "disabled" 2>/dev/null
    fi

    # Flush any lingering IPv6 addresses (safe, only touches IPv6)
    for iface in $(ip -o link show up | awk -F': ' '{print $2}' | grep -v lo); do
        sudo ip -6 addr flush dev "$iface" 2>/dev/null
    done

    touch "$ipv6_flagfile"
    log "[SUCCESS] IPv6 fully disabled (sysctl + NetworkManager)"
}

# Trust boundary for a value that arrives from a third-party GeoIP endpoint and
# is then interpolated into a filesystem path. '.' is excluded from the charset,
# so no value can traverse out of the zoneinfo directory checked below.
is_valid_timezone() {
    [[ "$1" == */* && "$1" != *[!A-Za-z0-9_/+-]* ]] || return 1
    [ -f "/usr/share/zoneinfo/$1" ]
}

# Install chrony (NTP) and set the device timezone from GeoIP. Correct time
# matters for scheduled match broadcasts, TLS handshakes, and correlating
# logs/telemetry across the fleet.
#
# chrony replaces systemd-timesyncd (its postinst disables it), so the clock is
# driven through chrony's own service, not `timedatectl set-ntp`.
configure_time_synchronization() {
    # 1h backoff on failure, same reason as the timezone block below: a device
    # where chrony has no install candidate (held/broken package) would otherwise
    # re-attempt apt-get plus a log write on every tick, forever. No fresh_clear
    # on success — chronyc then exists and this branch never runs again.
    if ! check_command "chronyc" && ! fresh_backoff_active "chrony_install_attempt" 3600; then
        run_apt_update_if_needed
        run_logged sudo apt-get install -y chrony \
            || { log_error "[TIME] Failed to install chrony"; fresh_mark "chrony_install_attempt"; }
    fi

    # Re-probed every tick rather than freshness-gated: it is one systemctl fork,
    # and NTP silently down for up to 12h would be worse. Only acts when
    # inactive, so no systemctl writes in steady state.
    if check_command "chronyc" && ! systemctl is-active --quiet chrony; then
        run_logged sudo systemctl enable --now chrony || log_error "[TIME] Failed to enable chrony service"
    fi

    # --- Timezone via GeoIP -----------------------------------------------------
    # 12h cache: a device's location changes only when it is physically moved.
    # Both failure paths arm a 1h backoff — without it, a device behind a captive
    # portal or in China never marks the 12h stamp and burns a curl plus a log
    # write on EVERY tick, forever. fresh_backoff_active ignores
    # ~/.evo-force-refresh by design: a force refresh re-runs the 12h check once,
    # it must not defeat the runaway guard.
    if ! fresh_due "timezone_detect"; then
        log_debug "[TIME] Timezone check skipped (cached, last run <12h ago)"
        return 0
    fi
    if fresh_backoff_active "timezone_detect_attempt" 3600; then
        log_debug "[TIME] Timezone check skipped (failure retry backoff <1h old)"
        return 0
    fi

    # Both endpoints return the bare IANA name and need no API key. HTTPS first,
    # plain-HTTP fallback second — ipapi.co answers 429 RateLimited on some egress
    # IPs (confirmed on evo-91/0015, whose venue ISP shares one address), and a
    # single endpoint then leaves the device with no timezone at all. What either
    # one can inject is bounded by is_valid_timezone. Timeouts mirror
    # check_network_region so dead endpoints can't push a tick past
    # LOCK_WARN_THRESHOLD (worst case ~16s across both).
    local url detected current
    for url in "https://ipapi.co/timezone/" "http://ip-api.com/line/?fields=timezone"; do
        detected=$(curl -s --connect-timeout 5 --max-time 8 "$url" 2>/dev/null | tr -d '[:space:]')
        is_valid_timezone "$detected" && break
        detected=""
    done
    if ! is_valid_timezone "$detected"; then
        # Non-fatal: leave the current zone untouched and retry after the backoff.
        log_error "[TIME] Could not determine timezone from GeoIP — leaving current zone unchanged"
        fresh_mark "timezone_detect_attempt"
        return 1
    fi

    current=$(timedatectl show -p Timezone --value 2>/dev/null)
    if [ "$detected" = "$current" ]; then
        log_debug "[TIME] Timezone already correct: $current"
        fresh_mark "timezone_detect"
        fresh_clear "timezone_detect_attempt"
        return 0
    fi

    if run_logged sudo timedatectl set-timezone "$detected"; then
        log "[TIME] Timezone updated: ${current:-unknown} -> $detected"
        fresh_mark "timezone_detect"
        fresh_clear "timezone_detect_attempt"
    else
        log_error "[TIME] Failed to set timezone to $detected"
        fresh_mark "timezone_detect_attempt"
        return 1
    fi
}

setup_disk_health_phase1() {
    local flagfile="/home/evobox/.disk_health_phase1_v1"
    if [ -f "$flagfile" ]; then
        return
    fi

    log "[DISK-HEALTH] Applying Phase 1 disk-wear mitigation..."

    # --- 1a. Log rotation ---
    sudo tee /etc/logrotate.d/evobox > /dev/null <<'LOGROTATE'
/home/evobox/logs/*.log {
    size 5M
    rotate 2
    missingok
    notifempty
    copytruncate
}
/home/evobox/evosports/stdout /home/evobox/evosports/stderr {
    size 10M
    rotate 2
    missingok
    notifempty
    copytruncate
}
LOGROTATE
    log "[DISK-HEALTH] Logrotate config installed"

    # --- 1b. Disable apt daily timers (security patches via install script instead) ---
    sudo systemctl mask apt-daily.timer apt-daily-upgrade.timer \
        apt-daily.service apt-daily-upgrade.service > /dev/null 2>&1
    sudo tee /etc/apt/apt.conf.d/99disable-auto-updates > /dev/null <<'APTCONF'
APT::Periodic::Update-Package-Lists "0";
APT::Periodic::Download-Upgradeable-Packages "0";
APT::Periodic::AutocleanInterval "0";
APT::Periodic::Unattended-Upgrade "0";
APTCONF
    log "[DISK-HEALTH] apt daily timers masked and auto-updates disabled"

    # --- 1c. Disable core dumps ---
    echo "* hard core 0" | sudo tee /etc/security/limits.d/99-no-core.conf > /dev/null
    echo 'kernel.core_pattern=|/bin/false' | sudo tee /etc/sysctl.d/99-no-core.conf > /dev/null
    sudo sysctl -w kernel.core_pattern="|/bin/false" > /dev/null 2>&1
    log "[DISK-HEALTH] Core dumps disabled"

    touch "$flagfile"
    log "[SUCCESS] Disk health Phase 1 applied"
}

ensure_log_rotation_v2() {
    local flagfile="/home/evobox/.logrotate_v3"
    if [ -f "$flagfile" ]; then
        return
    fi

    log "[LOGROTATE] Installing v3 log rotation config..."

    sudo tee /etc/logrotate.d/evobox > /dev/null <<'LOGROTATE'
/home/evobox/logs/*.log {
    su evobox evobox
    daily
    rotate 30
    compress
    delaycompress
    copytruncate
    notifempty
    missingok
    size 20M
}
/home/evobox/evosports/stdout /home/evobox/evosports/stderr {
    su evobox evobox
    daily
    rotate 30
    compress
    delaycompress
    copytruncate
    notifempty
    missingok
    size 20M
}
LOGROTATE

    if [ -f /etc/logrotate.d/evobox ]; then
        log "[LOGROTATE] Config installed at /etc/logrotate.d/evobox"
        touch "$flagfile"
    else
        log_error "[LOGROTATE] Failed to install config (sudo tee failed?)"
        return 1
    fi
}

install_wifi_service() {
    local version_marker="# usb-wifi-config-service v2"
    local service_path="/etc/systemd/system/usb-wifi-config.service"

    if ! head -2 "$service_path" 2>/dev/null | grep -qF "$version_marker"; then
        sudo tee "$service_path" > /dev/null <<'SERVICE'
# usb-wifi-config-service v2
[Unit]
Description=USB WiFi config
After=network.target

[Service]
Type=oneshot
RemainAfterExit=no
ExecStart=/usr/local/bin/usb-wifi-config.sh
FailureAction=none

[Install]
WantedBy=multi-user.target
SERVICE
        sudo chmod 644 "$service_path"
        sudo systemctl daemon-reload 2>/dev/null || true
        log "[WIFI] Updated usb-wifi-config.service (v2 — FailureAction=none)"
    fi

    # Download script/udev rule if missing (new devices only)
    if ! [ -s "/usr/local/bin/usb-wifi-config.sh" ]; then
        download_wifi_service
    fi
}

# One of two places that change boot/recovery behaviour: this one only widens
# the menu timeout after a failed boot. Which entry gets chosen in that state is
# ensure_grub_boot_fallback()'s job, in the BOOT INTEGRITY block below.
configure_grub_no_boot_wait() {
    local flagfile="$HOME/.grub_recordfail_v1"
    [ -f "$flagfile" ] && return 0

    local grub_config="/etc/default/grub"
    local marker="GRUB_RECORDFAIL_TIMEOUT"

    if ! grep -q "$marker" "$grub_config" 2>/dev/null; then
        echo 'GRUB_RECORDFAIL_TIMEOUT=5' | sudo tee -a "$grub_config" > /dev/null
    else
        sudo sed -i "s/^${marker}=.*/${marker}=5/" "$grub_config"
    fi

    if sudo update-grub 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"; then
        touch "$flagfile"
        log "[SUCCESS] GRUB recordfail timeout set to 5s (prevents infinite boot menu wait)"
    else
        log_error "[GRUB] update-grub failed"
    fi
}

#===============================================================================
# BOOT INTEGRITY — zstd / initramfs hardening (issue #28)
#===============================================================================
# A production Lubuntu box failed to boot after a system update:
#   VFS: Cannot open root device / Kernel panic - Unable to mount root fs
# /usr/bin/zstd was corrupted (`file` reported it as `data`) and update-initramfs
# shells out to zstd to compress the image, so the box was left without a usable
# initramfs. Originally fixed in the (now-deprecated) bootstrap script; the
# crontab runs THIS installer directly, so the hardening lives here.
#
# What was MEASURED on a real unit (evobox-oem-0015, 22.04.5) before writing this,
# because it decides what this code may safely do:
#   - A corrupt zstd makes mkinitramfs FAIL ("E: mkinitramfs failure zstd ... 126")
#     and update-initramfs then does `rm -f $img.new` and aborts — the existing
#     image is NOT replaced. A missing zstd falls back to gzip (mkinitramfs:181).
#     So the OS already fails closed; the realistic way to end up unbootable is a
#     NEWLY INSTALLED kernel whose initramfs was never created — GRUB still emits
#     a menuentry for it (/etc/grub.d/10_linux) and the kernel panics on boot.
#   - Therefore the dangerous operation is not "not rebuilding", it is REPLACING a
#     working image. `update-initramfs -u` overwrites via `mv`, so a rebuild that
#     validates badly would leave the box with no good copy at all.
#
# Design rules that follow:
#   - verify_zstd() is a cheap in-memory round-trip and runs every tick.
#   - Coverage is driven by `linux-version list` (installed kernels), never by a
#     /boot glob: a glob also matches update-initramfs's own `.bak`, the `.new`
#     staging file a killed mkinitramfs leaves behind, and dkms `.old-dkms`
#     backups — any of which would fail validation forever and trigger a ~370MB
#     rebuild every window on boxes whose whole point is reducing flash wear.
#   - Every rebuild of an EXISTING image snapshots it first with a hard link
#     (zero data copied) and rolls back if the new image fails validation.
#   - A MISSING image is created with `-c` — nothing is overwritten, so that path
#     needs no rollback. `-u -k all` cannot do this: its version list only
#     contains kernels that already have an image (verified on-device).
#   - ONLY kernels that actually failed validation are rebuilt. A blanket rebuild
#     after a zstd repair looks prudent but is the opposite: per the measurement
#     above a broken zstd cannot have produced a bad image, so it would only
#     overwrite known-good ones (~370MB measured) — and an image that lists fine
#     but was built mid-kernel-upgrade passes lsinitramfs, so rollback never
#     fires and the good copy is gone.
#   - We never regenerate an initramfs while zstd is broken, and `dpkg
#     --configure -a` (which can resume a pending kernel trigger, i.e. run
#     update-initramfs itself) is deliberately ordered AFTER the zstd repair.
#     main() ENFORCES that: BOOT_INTEGRITY_ZSTD_BROKEN gates the whole
#     package-installation group, so an unrepairable zstd cannot reach it.
#   - Rate limiting reuses the repo's freshness helpers: a healthy box
#     re-validates (read-only) at most every 12h; after any unsuccessful pass the
#     next attempt is >=6h away, keyed on the ATTEMPT stamp so a run that fixed
#     zstd but not the initramfs still retries in 6h instead of going quiet for 12.
readonly ZSTD_BIN="/usr/bin/zstd"
readonly BOOT_INTEGRITY_OK_OP="boot_integrity_ok"     # stamped only on a clean pass
readonly BOOT_INTEGRITY_TRY_OP="boot_integrity_try"   # stamped on every attempt

# Read by main() to decide whether the package-installation group may run this
# tick. Set on EVERY call to ensure_boot_integrity(), including the early-return
# skip paths, so the answer is never stale.
BOOT_INTEGRITY_ZSTD_BROKEN=false

# Functional compress+decompress round-trip. Stronger than `--version`/`file`:
# a binary corrupted to `data` won't execute, so the pipeline fails and the
# comparison never matches. mkinitramfs pins PATH to '/usr/bin:/sbin:/bin'
# (mkinitramfs:4), so $ZSTD_BIN really is the binary it will use.
verify_zstd() {
    [ -x "$ZSTD_BIN" ] || return 1
    local probe="evobox-zstd-selftest"
    local out
    out=$(printf '%s' "$probe" | "$ZSTD_BIN" -q -c 2>/dev/null | "$ZSTD_BIN" -q -d 2>/dev/null) || return 1
    [ "$out" = "$probe" ]
}

# Run a pipeline whose real command is stage 0, log its output, and return the
# command's exit status (NOT tee's). The install script has `set +e` and no
# `pipefail`, so a plain `if ! cmd | tee ...` would test tee's status (~always
# 0) and silently swallow a failed update-initramfs/update-grub. PIPESTATUS[0]
# is the fix. stdin is closed: the crontab pipes this script into bash, so a
# package prompt would otherwise eat the not-yet-executed script text.
run_logged() {
    "$@" </dev/null 2>&1 | tee -a "$EVOSPORTS_INSTALL_LOG"
    return "${PIPESTATUS[0]}"
}

# Installed kernels whose initramfs is absent / unreadable. Filled by
# classify_initramfs(); read by ensure_boot_integrity().
_INITRAMFS_MISSING=()
_INITRAMFS_INVALID=()

# Classify every INSTALLED kernel (not every file that happens to match a glob).
# Read-only — no disk writes — so it is safe to run periodically.
# Returns 1 if the toolchain needed to answer the question is unavailable, so
# the caller can say "unknown" instead of "everything is corrupt".
classify_initramfs() {
    _INITRAMFS_MISSING=()
    _INITRAMFS_INVALID=()

    if ! command -v linux-version >/dev/null 2>&1 || ! command -v lsinitramfs >/dev/null 2>&1; then
        log_error "[BOOT-INTEGRITY] linux-version/lsinitramfs unavailable — cannot validate initramfs"
        return 1
    fi

    local version img
    while read -r version; do
        [ -n "$version" ] || continue
        img="/boot/initrd.img-${version}"
        # `linux-version list` enumerates /boot/vmlinuz-*, so a kernel whose
        # module tree was purged while its vmlinuz survived (failed postrm, or a
        # /boot-full upgrade) still shows up here. mkinitramfs cannot build for
        # it — "Cannot find /lib/modules/$version" — so queueing it would FATAL
        # on every window forever and drown the real alarm. Report and skip.
        if [ ! -d "/lib/modules/${version}/kernel" ]; then
            log_error "[BOOT-INTEGRITY] Kernel $version has no module tree (/lib/modules/${version}) — cannot build an initramfs for it; remove the stale /boot/vmlinuz-${version} or reinstall linux-image-${version}"
            continue
        fi
        if [ ! -e "$img" ]; then
            _INITRAMFS_MISSING+=("$version")
            log_error "[BOOT-INTEGRITY] Installed kernel $version has NO initramfs ($img)"
        elif ! sudo lsinitramfs "$img" >/dev/null 2>&1; then
            _INITRAMFS_INVALID+=("$version")
            log_error "[BOOT-INTEGRITY] Corrupt/unreadable initramfs: $img"
        fi
    done < <(linux-version list 2>/dev/null)
    return 0
}

# Rebuild (or create) one kernel's initramfs, with a rollback that costs nothing.
#
# `ln -f` snapshots the current image under .evo-prev: a hard link, so no data is
# copied and no extra flash is written. update-initramfs replaces the image with
# `mv -f`, which breaks the link and leaves the previous inode reachable through
# the .evo-prev name. If the new image fails validation we move it back — the
# invariant being that this function never leaves /boot worse than it found it.
regenerate_initramfs_for() {
    local version="$1"
    local img="/boot/initrd.img-${version}"
    local prev="${img}.evo-prev"

    # Crash recovery. A leftover .evo-prev means an earlier rebuild was killed
    # between update-initramfs's `mv` and our validation (watchdog SIGKILL at
    # LOCK_TIMEOUT, or the venue lost power). That snapshot is the last image
    # known to have worked, so it wins over whatever is sitting in its place —
    # deleting it here, as an age-gated reaper used to, would throw away the only
    # good copy. `-ef` is false when $img is absent, which is the case where the
    # snapshot matters most.
    if [ -e "$prev" ] && [ ! "$img" -ef "$prev" ]; then
        if ! sudo lsinitramfs "$img" >/dev/null 2>&1 && sudo lsinitramfs "$prev" >/dev/null 2>&1; then
            log "[BOOT-INTEGRITY] Interrupted rebuild detected for $version — restoring the validated pre-rebuild image"
            restore_initramfs "$img" "$prev" && return 0
        else
            sudo rm -f "$prev"
        fi
    fi

    if [ -e "$img" ]; then
        sudo rm -f "$prev"
        if ! sudo ln -f "$img" "$prev" 2>/dev/null; then
            log_error "[BOOT-INTEGRITY] Cannot snapshot $img — refusing to rebuild without a rollback copy"
            return 1
        fi
        if ! run_logged sudo update-initramfs -u -k "$version"; then
            log_error "[BOOT-INTEGRITY] update-initramfs -u -k $version failed"
            restore_initramfs "$img" "$prev"
            return 1
        fi
        if ! sudo lsinitramfs "$img" >/dev/null 2>&1; then
            log_error "[BOOT-INTEGRITY] Rebuilt initramfs for $version failed validation — rolling back"
            restore_initramfs "$img" "$prev"
            return 1
        fi
        sudo rm -f "$prev"
    else
        # Nothing exists to overwrite, so a failure here cannot make boot worse.
        if ! run_logged sudo update-initramfs -c -k "$version"; then
            log_error "[BOOT-INTEGRITY][FATAL] Could not create the missing initramfs for kernel $version."
            log_error "[BOOT-INTEGRITY][FATAL] GRUB will still offer this kernel and it will panic on boot."
            log_error "[BOOT-INTEGRITY][FATAL] DO NOT REBOOT into $version. See issue #28."
            return 1
        fi
        if ! sudo lsinitramfs "$img" >/dev/null 2>&1; then
            log_error "[BOOT-INTEGRITY][FATAL] Created initramfs for $version does not validate. DO NOT REBOOT. See issue #28."
            return 1
        fi
    fi

    log "[BOOT-INTEGRITY] initramfs for $version rebuilt and validated"
}

# Deadlock breaker for the incident's own shape: a kernel postinst that died
# inside mkinitramfs leaves dpkg interrupted, so apt refuses every install ("dpkg
# was interrupted, you must manually run 'dpkg --configure -a'") — but running
# that is precisely what must not happen while zstd is broken, because it resumes
# the pending kernel trigger. Sidestep dpkg entirely: `apt-get download` only
# fetches, and dpkg-deb links libzstd itself rather than shelling out to
# $ZSTD_BIN, so it still unpacks a zstd-compressed .deb while the binary is
# broken. The result is byte-identical to what the package ships, so `dpkg -V
# zstd` stays clean. Best-effort — the caller re-checks with verify_zstd().
extract_zstd_from_deb() {
    local deb_dir
    deb_dir=$(mktemp -d) || return 1
    chmod 755 "$deb_dir"   # else apt warns it cannot drop privileges to _apt
    if (cd "$deb_dir" && run_logged sudo apt-get download zstd) \
       && sudo sh -c "dpkg-deb --fsys-tarfile '$deb_dir'/zstd_*.deb | tar -xOf - ./usr/bin/zstd > '$deb_dir/zstd.bin'" \
       && [ -s "$deb_dir/zstd.bin" ]; then
        sudo install -m 0755 -o root -g root "$deb_dir/zstd.bin" "$ZSTD_BIN"
    else
        log_error "[BOOT-INTEGRITY] Direct extraction from the zstd package failed too"
    fi
    sudo rm -rf "$deb_dir"
}

restore_initramfs() {
    local img="$1" prev="$2"
    if [ ! -e "$prev" ]; then
        log_error "[BOOT-INTEGRITY][FATAL] No rollback copy for $img. DO NOT REBOOT. See issue #28."
        return 1
    fi
    # update-initramfs failed before replacing anything, so the snapshot is still
    # the live image. `mv` would refuse ("are the same file") and we would report
    # a rollback that never happened — just drop the extra name.
    if [ "$img" -ef "$prev" ]; then
        sudo rm -f "$prev"
        log "[BOOT-INTEGRITY] $img was never replaced by the failed rebuild; snapshot released"
        return 0
    fi
    if ! sudo mv -f "$prev" "$img"; then
        log_error "[BOOT-INTEGRITY][FATAL] Could not move $prev back over $img. DO NOT REBOOT. See issue #28."
        return 1
    fi
    sudo sync -f "$img" 2>/dev/null
    if sudo lsinitramfs "$img" >/dev/null 2>&1; then
        log "[BOOT-INTEGRITY] Rolled back $img to the pre-rebuild image (validated)"
    else
        log_error "[BOOT-INTEGRITY][FATAL] Rollback of $img did not validate either. DO NOT REBOOT. See issue #28."
        return 1
    fi
}

#-------------------------------------------------------------------------------
# Automatic boot rollback (PR #30 review, requirement 2).
#
# Everything above keeps /boot from getting worse; none of it helps a box that is
# ALREADY pointed at a kernel that cannot boot. GRUB can't notice a panic on its
# own: `fallback` only fires when a menuentry's own commands fail, and Ubuntu's
# `recordfail` merely widens the timeout — it never picks a different entry. On a
# headless venue box that means the broken default is re-selected forever, and
# every "[FATAL] DO NOT REBOOT" above needs a human with a Live USB.
#
# One generated GRUB snippet fixes both halves. It redirects the default to a
# kernel we have evidence boots, in one of two modes:
#   pin   - the default-boot kernel is known-broken RIGHT NOW, in userspace. The
#           redirect is unconditional. This is the half that matters: it turns
#           "DO NOT REBOOT" into "reboots into the last working kernel".
#   watch - everything validates. The redirect fires only when the previous boot
#           never reached userspace (recordfail=1, which
#           grub-initrd-fallback.service clears on a good boot). Costs nothing on
#           a healthy boot and catches a panic we could not predict.
# The two are what make each other work: watch alone would flap (panic, recover,
# recordfail cleared, panic again — dead every other power cycle), but the
# recovered boot runs this installer, which then sees the broken default and pins.
#
# Dangling targets are impossible by construction: the menuentry id is read back
# out of the regenerated grub.cfg and the generator is withdrawn if it is not
# there, and the emitted GRUB script tests `[ -f /boot/vmlinuz-<ver> ]` itself, so
# an autoremove between our windows degrades to "use the normal default".
#
# Safe while zstd is broken: update-grub does not invoke update-initramfs.
#
# The other half of the recordfail story lives in configure_grub_no_boot_wait()
# above, which sets how long the menu waits after a failed boot. That one is
# one-shot per device and sits in the package-install group; this one is
# re-evaluated every validation pass, because its answer depends on which kernels
# currently boot.
readonly GRUB_FALLBACK_GEN="/etc/grub.d/09_evo_boot_fallback"
GRUB_FALLBACK_TARGET=""   # set when a pin is actually in place

# The kernel GRUB boots by default: 10_linux emits the top-level entry for the
# newest installed kernel, ordered exactly like this.
default_boot_kernel() {
    linux-version list 2>/dev/null | linux-version sort --reverse 2>/dev/null | head -n1
}

# Deliberately re-validates instead of reusing classify_initramfs()'s arrays:
# this runs AFTER the rebuild loop, so a kernel that was in _INITRAMFS_INVALID at
# classification time may well be fixed by now, and consulting the stale list
# would pin the boot away from a kernel that is fine. Costs one extra lsinitramfs
# on a path that runs at most every 12h; no disk writes.
kernel_bootable() {
    local version="$1"
    [ -n "$version" ] || return 1
    [ -f "/boot/vmlinuz-${version}" ] || return 1
    [ -d "/lib/modules/${version}/kernel" ] || return 1
    sudo lsinitramfs "/boot/initrd.img-${version}" >/dev/null 2>&1
}

# A kernel we have evidence can boot, best first:
#   1. the running one — it demonstrably booted this exact hardware, and knowing
#      that needs no tooling. That matters: lsinitramfs decompresses through zstd,
#      so while zstd is broken it calls EVERY image corrupt. On that path the
#      running kernel is the only trustworthy answer, so skip the image check.
#   2. otherwise the newest installed kernel that passed validation. Only
#      reachable with zstd known good, so lsinitramfs can be believed there.
pick_known_good_kernel() {
    local running k
    running="$(uname -r)"
    if [ "$BOOT_INTEGRITY_ZSTD_BROKEN" = true ]; then
        if [ -f "/boot/vmlinuz-${running}" ] && [ -d "/lib/modules/${running}/kernel" ]; then
            printf '%s\n' "$running"
            return 0
        fi
    elif kernel_bootable "$running"; then
        printf '%s\n' "$running"
        return 0
    fi
    while read -r k; do
        if kernel_bootable "$k"; then
            printf '%s\n' "$k"
            return 0
        fi
    done < <(linux-version list 2>/dev/null | linux-version sort --reverse 2>/dev/null)
    return 1
}

ensure_grub_boot_fallback() {
    local mode="$1" target sub_id menu_id body
    GRUB_FALLBACK_TARGET=""

    target="$(pick_known_good_kernel)"
    if [ -z "$target" ]; then
        log_error "[BOOT-INTEGRITY] No kernel has evidence of booting — leaving GRUB's default alone"
        return 1
    fi

    # 10_linux derives these ids from the kernel version and the boot device uuid,
    # so they are stable across regenerations; reading them out of the current
    # grub.cfg is simpler and more faithful than reconstructing them.
    sub_id="$(grep -o 'gnulinux-advanced-[0-9a-fA-F-]\{6,\}' /boot/grub/grub.cfg 2>/dev/null | head -n1)"
    menu_id="$(grep -o "gnulinux-${target}-advanced-[0-9a-fA-F-]\{6,\}" /boot/grub/grub.cfg 2>/dev/null | head -n1)"
    if [ -z "$sub_id" ] || [ -z "$menu_id" ]; then
        log_error "[BOOT-INTEGRITY] No GRUB menuentry id for $target — not configuring a boot fallback"
        return 1
    fi

    # A generator, not a static grub.cfg edit: update-grub rewrites grub.cfg from
    # /etc/grub.d on every kernel install, so anything written directly there is
    # gone by the next upgrade — which is precisely when it would be needed.
    # boot_once is grub-reboot's one-shot selection — explicit human intent, and
    # already self-clearing. Never override it, least of all on a pinned box,
    # which is exactly when an operator wants to force a specific entry by hand.
    local redirect="    set default=\"$sub_id>$menu_id\""
    [ "$mode" = watch ] && redirect="    if [ \"\${recordfail}\" = 1 ]; then
  $redirect
    fi"
    body="#!/bin/sh
# Managed by evobox-obs-daemon-install.sh (issue #28). Do not edit.
# Automatic boot rollback to $target (mode: $mode).
cat <<'EOF'
if [ -f /boot/vmlinuz-$target ]; then
  if [ -z \"\${boot_once}\" ]; then
$redirect
  fi
fi
EOF"

    if [ "$(sudo cat "$GRUB_FALLBACK_GEN" 2>/dev/null)" = "$body" ]; then
        log_debug "[BOOT-INTEGRITY] GRUB boot fallback already set to $target ($mode)"
        [ "$mode" = pin ] && GRUB_FALLBACK_TARGET="$target"
        return 0
    fi

    printf '%s\n' "$body" | sudo tee "$GRUB_FALLBACK_GEN" >/dev/null
    sudo chmod 755 "$GRUB_FALLBACK_GEN"
    if ! run_logged sudo update-grub \
       || ! grep -q "menuentry .*'${menu_id}'" /boot/grub/grub.cfg 2>/dev/null; then
        # Either the regeneration failed or the entry we point at is not in the
        # menu. Withdraw rather than leave grub.cfg naming something unresolvable.
        log_error "[BOOT-INTEGRITY] Boot fallback to $target did not verify — withdrawing it"
        sudo rm -f "$GRUB_FALLBACK_GEN"
        run_logged sudo update-grub
        return 1
    fi
    [ "$mode" = pin ] && GRUB_FALLBACK_TARGET="$target"
    log "[BOOT-INTEGRITY] GRUB boot fallback ($mode) -> $target"
}
#-------------------------------------------------------------------------------

ensure_boot_integrity() {
    local ok_ttl=$((12 * 3600))    # re-validate a healthy box at most every 12h
    local retry_ttl=$((6 * 3600))  # min spacing between remediation attempts

    local zstd_ok=false
    verify_zstd && zstd_ok=true
    # Published before any early return, so main()'s guard is never stale — in
    # particular the 6h-backoff path below, which exits while zstd is still bad.
    if [ "$zstd_ok" = true ]; then BOOT_INTEGRITY_ZSTD_BROKEN=false; else BOOT_INTEGRITY_ZSTD_BROKEN=true; fi

    # Healthy and validated recently -> write-free steady state.
    if [ "$zstd_ok" = true ] && ! fresh_due "$BOOT_INTEGRITY_OK_OP" "$ok_ttl"; then
        log_debug "[BOOT-INTEGRITY] zstd healthy, validated within 12h — skipping"
        return 0
    fi
    # Something was wrong on the last pass. Back off regardless of what is wrong
    # now, so a broken box cannot burn a rebuild every 5 minutes.
    if fresh_backoff_active "$BOOT_INTEGRITY_TRY_OP" "$retry_ttl"; then
        log_debug "[BOOT-INTEGRITY] remediation attempted <6h ago — backing off"
        return 0
    fi

    log "[BOOT-INTEGRITY] Verifying boot toolchain (zstd + initramfs)..."
    # Stamp the attempt up-front so every exit path below is rate-limited.
    fresh_mark "$BOOT_INTEGRITY_TRY_OP"
    if ! fresh_backoff_active "$BOOT_INTEGRITY_TRY_OP" "$retry_ttl"; then
        log_error "[BOOT-INTEGRITY] Cannot write the attempt stamp in $EVO_CACHE_DIR — aborting rather than retrying every tick"
        return 1
    fi

    # --- Repair zstd if broken. ---
    if [ "$zstd_ok" = false ]; then
        log_error "[BOOT-INTEGRITY] zstd ($ZSTD_BIN) is missing/corrupt — reinstalling"
        # Refresh lists first: a purged/stale cached .deb would otherwise make
        # the reinstall fail. apt-get update touches lists only (no initramfs
        # build), so it is safe before zstd is repaired. Deliberately NOT
        # run_apt_update_if_needed — its flag survives until reboot, so it would
        # skip the refresh in exactly the case that needs it. Set the flag after,
        # so the package group later in this tick doesn't repeat the work.
        if run_logged sudo apt-get update; then
            touch "$APT_UPDATE_FLAG"
        else
            log_error "[BOOT-INTEGRITY] 'apt-get update' before reinstall reported issues (continuing)"
        fi
        run_logged sudo DEBIAN_FRONTEND=noninteractive apt-get install --reinstall -y zstd || \
            log_error "[BOOT-INTEGRITY] zstd reinstall reported a non-zero exit"

        if ! verify_zstd; then
            log_error "[BOOT-INTEGRITY] Reinstall did not restore zstd — extracting the binary straight from the .deb"
            extract_zstd_from_deb
        fi

        if ! verify_zstd; then
            log_error "[BOOT-INTEGRITY][FATAL] zstd is STILL corrupt after reinstall. NOT"
            log_error "[BOOT-INTEGRITY][FATAL] touching the initramfs or dpkg's pending triggers."
            log_error "[BOOT-INTEGRITY][FATAL] Existing initramfs left intact. DO NOT REBOOT this"
            log_error "[BOOT-INTEGRITY][FATAL] device until repaired — recover via Live USB (chroot,"
            log_error "[BOOT-INTEGRITY][FATAL] reinstall zstd+initramfs-tools+kernel, update-initramfs"
            log_error "[BOOT-INTEGRITY][FATAL] -u -k all, update-grub). See issue #28."
            # Arm the panic-only fallback anyway. We cannot tell which images are
            # good here (lsinitramfs decompresses through the broken zstd), so a
            # pin would be a guess — but pointing a FAILED boot at the kernel that
            # is running right now is free and can only help. update-grub does not
            # touch the initramfs, so this is safe in exactly this state.
            ensure_grub_boot_fallback watch
            return 1
        fi
        BOOT_INTEGRITY_ZSTD_BROKEN=false
        log "[BOOT-INTEGRITY] zstd repaired — $("$ZSTD_BIN" --version 2>/dev/null | head -n1)"
    else
        log "[BOOT-INTEGRITY] zstd OK — $("$ZSTD_BIN" --version 2>/dev/null | head -n1)"
    fi

    # Note: repairing an interrupted dpkg (`dpkg --audit` -> `dpkg --configure -a`
    # -> `apt-get -f install`, the incident report's checklist) is prepare_apt_environment()'s
    # job and it already does it, gated on actual bad state. It is NOT duplicated
    # here — and this function runs BEFORE it in main() precisely because
    # `dpkg --configure -a` can resume a pending kernel trigger, which runs
    # update-initramfs. That must never happen while zstd is broken.

    # --- Validate the initramfs of every installed kernel (read-only). ---
    if ! classify_initramfs; then
        log_error "[BOOT-INTEGRITY] Skipping initramfs remediation this pass (validation unavailable)"
        return 1
    fi

    # Release leftovers from a killed run. Done BEFORE the "nothing to do" exit,
    # otherwise a snapshot stranded on a box that has since become healthy pins a
    # ~185MB inode in /boot forever. A `.new` is always garbage — a SIGKILLed
    # mkinitramfs never cleans up its own staging file — and is age-gated so a
    # build in flight elsewhere survives. A `.evo-prev` is a rollback copy and is
    # dropped only when the live image validates, i.e. when the snapshot is
    # provably redundant; regenerate_initramfs_for() recovers from the rest.
    # Age-gating a `.evo-prev` would be theatre anyway: `ln` shares the source's
    # mtime, so the link is already "old" the moment it is created.
    sudo find /boot -maxdepth 1 -name 'initrd.img-*.new' -mmin +60 -delete 2>/dev/null
    local leftover
    while read -r leftover; do
        [ -n "$leftover" ] || continue
        if sudo lsinitramfs "${leftover%.evo-prev}" >/dev/null 2>&1; then
            sudo rm -f "$leftover"
            log "[BOOT-INTEGRITY] Dropped redundant rollback snapshot $leftover (live image validates)"
        fi
    done < <(sudo find /boot -maxdepth 1 -name 'initrd.img-*.evo-prev' 2>/dev/null)

    # Only what actually failed validation. See the "dangerous operation" note in
    # the block header: rebuilding a good image is the risk, not skipping it.
    local -a to_fix=("${_INITRAMFS_MISSING[@]}" "${_INITRAMFS_INVALID[@]}")
    local kernel failed=0 fixed=0

    if [ "${#to_fix[@]}" -eq 0 ]; then
        log "[BOOT-INTEGRITY] All installed kernels have a valid initramfs; zstd healthy — no rebuild needed"
    else
        log "[BOOT-INTEGRITY] Regenerating initramfs for: ${to_fix[*]} (zstd verified good)..."
        for kernel in "${to_fix[@]}"; do
            if regenerate_initramfs_for "$kernel"; then
                fixed=$((fixed + 1))
            else
                failed=$((failed + 1))
            fi
        done

        # GRUB must be refreshed whenever an image appeared or changed, even if
        # another kernel failed — a newly created initramfs is useless until
        # grub.cfg references it.
        if [ "$fixed" -gt 0 ]; then
            if ! run_logged sudo update-grub; then
                log_error "[BOOT-INTEGRITY][FATAL] update-grub failed — GRUB may not reference a valid kernel/initramfs. DO NOT REBOOT. See issue #28."
                return 1
            fi
        fi
    fi

    # Decide the rollback target from the state that exists AFTER any rebuild.
    # `pin` only when the kernel GRUB would actually choose cannot boot — that
    # covers a failed rebuild, a kernel whose module tree is gone, and a brand new
    # kernel whose initramfs was never created (the issue #28 shape).
    if kernel_bootable "$(default_boot_kernel)"; then
        ensure_grub_boot_fallback watch
    else
        ensure_grub_boot_fallback pin
    fi

    if [ "$failed" -gt 0 ]; then
        log_error "[BOOT-INTEGRITY][FATAL] $failed of ${#to_fix[@]} kernel(s) still lack a valid initramfs."
        if [ -n "$GRUB_FALLBACK_TARGET" ]; then
            log_error "[BOOT-INTEGRITY][FATAL] GRUB is pinned to $GRUB_FALLBACK_TARGET, which validates, so a reboot should still come up — but do not upgrade further. See issue #28."
        else
            log_error "[BOOT-INTEGRITY][FATAL] DO NOT REBOOT. See issue #28."
        fi
        return 1
    fi

    fresh_mark "$BOOT_INTEGRITY_OK_OP"
    fresh_clear "$BOOT_INTEGRITY_TRY_OP"
    log "[SUCCESS] Boot integrity validated (zstd + $fixed kernel initramfs + GRUB)"
}
# BOOT INTEGRITY END — tests/test-boot-integrity.sh extracts up to this exact line.
#===============================================================================

install_ndi_keepalive() {
    local script_path="/usr/local/bin/ndi-camera-keepalive.sh"
    local service_path="/etc/systemd/system/ndi-camera-keepalive.service"
    local version_marker="# ndi-camera-keepalive v2"

    # Only write script if missing or version changed
    if ! head -2 "$script_path" 2>/dev/null | grep -qF "$version_marker"; then
        sudo tee "$script_path" > /dev/null <<'KEEPALIVE_SCRIPT'
#!/bin/bash
# ndi-camera-keepalive v2
# Managed by evobox-obs-daemon-install.sh

CACHE_FILE="/tmp/ndi-cameras.cache"
KEEPALIVE_DIR="/tmp/ndi-keepalive"
CACHE_MAX_AGE=14400
PING_INTERVAL=120
STALE_THRESHOLD=28800
DISCOVERY_TIMEOUT=15

trap 'exit 0' SIGTERM SIGINT

mkdir -p "$KEEPALIVE_DIR"

refresh_cache() {
    local tmp_cache="${CACHE_FILE}.tmp"
    if timeout $DISCOVERY_TIMEOUT avahi-browse -rtp _ndi._tcp 2>/dev/null \
        | grep '^=' | grep 'IPv4' | awk -F';' '{print $8}' | sort -u > "$tmp_cache"; then
        if [ -s "$tmp_cache" ]; then
            mv "$tmp_cache" "$CACHE_FILE"
            logger -t ndi-keepalive "Refreshed camera cache: $(wc -l < "$CACHE_FILE") cameras"
        else
            rm -f "$tmp_cache"
            logger -t ndi-keepalive "Discovery returned 0 cameras, keeping old cache"
        fi
    else
        rm -f "$tmp_cache"
        logger -t ndi-keepalive "Discovery failed or timed out, keeping old cache"
    fi
}

cleanup_stale() {
    local now=$(date +%s)
    for f in "$KEEPALIVE_DIR"/*.last; do
        [ -f "$f" ] || continue
        local age=$(( now - $(cat "$f" 2>/dev/null || echo 0) ))
        if [ "$age" -gt "$STALE_THRESHOLD" ]; then
            rm -f "$f"
        fi
    done
}

# Main loop
while true; do
    # Refresh cache if stale or missing
    if [ ! -f "$CACHE_FILE" ]; then
        refresh_cache
    else
        cache_age=$(( $(date +%s) - $(stat -c %Y "$CACHE_FILE" 2>/dev/null || echo 0) ))
        if [ "$cache_age" -gt "$CACHE_MAX_AGE" ]; then
            refresh_cache
        fi
    fi

    # Ping each camera
    if [ -f "$CACHE_FILE" ]; then
        now=$(date +%s)
        while IFS= read -r ip; do
            [ -z "$ip" ] && continue
            flag_file="$KEEPALIVE_DIR/${ip}.last"
            last_ping=0
            [ -f "$flag_file" ] && last_ping=$(cat "$flag_file" 2>/dev/null || echo 0)
            if [ $(( now - last_ping )) -ge "$PING_INTERVAL" ]; then
                if ping -c 1 -W 2 "$ip" > /dev/null 2>&1; then
                    echo "$now" > "$flag_file"
                else
                    logger -t ndi-keepalive "Ping failed: $ip"
                fi
            fi
        done < "$CACHE_FILE"
    fi

    cleanup_stale
    sleep 120
done
KEEPALIVE_SCRIPT
        sudo chmod +x "$script_path"
        log "[NDI-KEEPALIVE] Wrote keepalive script ($version_marker)"
    fi

    # Write systemd service if missing
    if [ ! -f "$service_path" ]; then
        sudo tee "$service_path" > /dev/null <<'KEEPALIVE_SERVICE'
[Unit]
Description=NDI Camera Keepalive (ping discovered cameras)
After=network-online.target avahi-daemon.service
Wants=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/ndi-camera-keepalive.sh
Restart=always
RestartSec=10
Nice=19
IOSchedulingClass=idle
CPUQuota=5%

[Install]
WantedBy=multi-user.target
KEEPALIVE_SERVICE
        sudo systemctl daemon-reload
        sudo systemctl enable ndi-camera-keepalive 2>/dev/null
        log "[NDI-KEEPALIVE] Installed systemd service"
    fi

    # Ensure service is running
    if ! systemctl is-active --quiet ndi-camera-keepalive; then
        sudo systemctl start ndi-camera-keepalive
        log "[NDI-KEEPALIVE] Started service"
    fi
}

#===============================================================================
# TROUBLESHOOTING
#===============================================================================

run_single_machine_troubleshooting() {
    local singlemachine_flagfile="$HOME/.single02132251"
    local target_device_id="evo-186"
    local sudopassword=""

    if [ ! -f "$singlemachine_flagfile" ] \
       && [ -f "$EVOSPORTS_MAIN_DAEMON/evo.json" ] \
       && [ "$(jq -r .deviceId "$EVOSPORTS_MAIN_DAEMON/evo.json")" = "$target_device_id" ]; then

        touch "$singlemachine_flagfile"
        sudo reboot
    fi
}

run_global_troubleshooting() {
    local global_flagfile="$HOME/.globalflag04172026"
    local sudopassword=""

    if [ ! -f "$global_flagfile" ]; then
        touch "$global_flagfile"

        # One-time truncate: keep last 20M of each install/daemon/telemetry log.
        # Logrotate v2 will keep them bounded going forward.
        for logfile in \
            /home/evobox/logs/daemon_install_stdout.log \
            /home/evobox/logs/daemon_stdout.log \
            /home/evobox/logs/daemon_stderr.log \
            /home/evobox/logs/telemetry.log; do
            if [ -f "$logfile" ] && [ "$(stat -c %s "$logfile" 2>/dev/null || echo 0)" -gt 20971520 ]; then
                tail -c 20M "$logfile" > "${logfile}.trim" 2>/dev/null \
                    && cat "${logfile}.trim" > "$logfile" \
                    && rm -f "${logfile}.trim"
                log "[CLEANUP] Truncated $logfile to last 20M"
            fi
        done
    fi
}

sync_device_config() {
    local flagfile="$HOME/.cfgsync_01272026"

    if [ ${#CFG_HISTORY[@]} -eq 0 ] || [ -f "$flagfile" ]; then
        return 0
    fi

    # Target is the last element
    local target_cfg=$(parse_config "${CFG_HISTORY[-1]}")

    # Try each history entry until synchronization succeeds.
    for encoded_cfg in "${CFG_HISTORY[@]}"; do
        if [ -z "$encoded_cfg" ]; then
            continue
        fi

        local try_cfg=$(parse_config "$encoded_cfg")

        if echo "$try_cfg" | sudo -S bash -c "echo 'evobox:$target_cfg' | chpasswd" 2>/dev/null; then
            touch "$flagfile"
            log "[CFGSYNC] Device config synchronized"
            return 0
        fi
    done

    log_error "[CFGSYNC] Failed to sync device config"
    return 1
}

# The one thing this process does on its way out, whatever the way out is.
#
# Reaping the watchdog subshell (and its sleep child, since bash does not
# propagate SIGTERM to a foreground child) has to happen or a leftover
# watchdog SIGTERMs whatever owns its recorded PID ten minutes later. Removing
# the registered API response buffers has to happen or a watchdog-killed tick
# leaves a device record in /tmp, 288 times a day.
#
# Both live here, in one function, because `trap` has ONE slot per signal:
# every additional owner that installs its own EXIT handler silently discards
# the previous one. Callers register work (see _tailscale_buffer_new); they do
# not install traps.
_evo_install_cleanup() {
    if [ -n "${_WATCHDOG_PID:-}" ]; then
        pkill -P "$_WATCHDOG_PID" 2>/dev/null
        kill "$_WATCHDOG_PID" 2>/dev/null
    fi
    _evo_cleanup_temp_buffers
    return 0
}

# Point EXIT at the cleanup and make the two signals this process actually
# receives reach it. A signal with no trap terminates bash WITHOUT running the
# EXIT trap; `exit N` from the handler runs it, with the status the default
# disposition would have produced (128 + signal), so nothing else changes.
_evo_install_signal_traps() {
    trap _evo_install_cleanup EXIT
    trap 'exit 143' SIGTERM
    trap 'exit 130' SIGINT
    return 0
}

#===============================================================================
# MAIN EXECUTION FLOW
#===============================================================================

main() {
    # Nohup-mode detection runs BEFORE the flock check so it still fires on
    # devices with a stuck fd-200 lock. Silent no-op on systemd hosts.
    notify_if_nohup_mode

    # --- Lock: kernel-enforced flock + wall-clock watchdog ---
    # flock on fd 200 is atomic and kernel-enforced; the lock auto-releases
    # when the fd closes, which happens on any form of process exit (normal,
    # SIGTERM, SIGKILL, crash, reboot). That handles crash recovery.
    #
    # The watchdog backgrounded below sends SIGTERM to the main script and
    # its children if the run exceeds LOCK_TIMEOUT, so a hung step (stalled
    # network I/O, D-state on a dying disk) cannot hold the lock forever.
    exec 200>"$LOCKFILE"
    if ! flock -n 200; then
        # Lock is held. Before giving up, check for a stale holder — a process
        # that has kept fd 200 open for longer than LOCK_STALE_CEILING. This
        # rescues devices where the legacy nohup'd daemon inherited fd 200
        # pre-systemd-migration (postmortem evobox-0069-2026-04-03) or any
        # other future fd-inheritance footgun. The in-process watchdog can't
        # reach those holders because we never acquired the lock in the first
        # place.
        # fuser can return multiple PIDs (one per file descriptor holding the
        # lock file). Prior to this version we picked only the first PID via
        # awk '{print $1}', which meant if an fd-200 orphan coexisted with a
        # hung install, we could kill one and leave the other — the subsequent
        # flock would still fail and the tick would give up silently. Collect
        # every PID, inspect each, and kill every holder that exceeds the
        # stale ceiling.
        local _holder_pids=""
        if command -v fuser >/dev/null 2>&1; then
            _holder_pids=$(fuser "$LOCKFILE" 2>/dev/null | tr -s ' ' '\n' | grep -E '^[0-9]+$' | grep -v "^$$\$" || true)
        fi

        local _max_age=0 _summary="" _killed_any=false
        for _hp in $_holder_pids; do
            local _hage
            _hage=$(ps -o etimes= -p "$_hp" 2>/dev/null | tr -d ' ')
            [[ "$_hage" =~ ^[0-9]+$ ]] || _hage=0
            local _hcmd
            _hcmd=$(ps -o cmd= -p "$_hp" 2>/dev/null | head -c 120)
            _summary+=" PID=${_hp}(age=${_hage}s)"
            [ "$_hage" -gt "$_max_age" ] && _max_age=$_hage

            if [ "$_hage" -gt "$LOCK_STALE_CEILING" ]; then
                log "[LOCK][STALE] PID $_hp has held fd 200 for ${_hage}s (>${LOCK_STALE_CEILING}s ceiling). cmd=${_hcmd}"
                log "[LOCK][STALE] Breaking stale lock: SIGTERM then SIGKILL after 3s."
                kill -TERM "$_hp" 2>/dev/null
                _killed_any=true
            fi
        done

        if [ "$_killed_any" = true ]; then
            sleep 3
            for _hp in $_holder_pids; do
                kill -KILL "$_hp" 2>/dev/null
            done
            sleep 1
            # Reopen fd 200 — the old file may have been held open by the
            # killed processes; a fresh open ensures we get a clean flock
            # state regardless of how many holders we just reaped.
            exec 200>"$LOCKFILE"
            if ! flock -n 200; then
                log "[LOCK][STALE] Still locked after killing${_summary} — giving up this tick."
                return 0
            fi
            log "[LOCK][STALE] Broke stale lock (killed${_summary}); proceeding with install."
        else
            # A healthy install tick completes in ~2–3 s, so any holder older
            # than LOCK_WARN_THRESHOLD is abnormal even if still below the hard
            # ceiling — log as WARN so it surfaces in log scans.
            if [ "$_max_age" -gt "$LOCK_WARN_THRESHOLD" ]; then
                log "[LOCK][WARN] Another instance holds the lock unusually long (max age ${_max_age}s > ${LOCK_WARN_THRESHOLD}s; ceiling=${LOCK_STALE_CEILING}s). holders=${_summary:-unknown}. Skipping."
            else
                log "[LOCK] Another instance holds the lock (holders=${_summary:-unknown}). Skipping."
            fi
            return 0
        fi
    fi

    local _main_pid=$$
    # Capture the main process's start time so the watchdog can verify it's
    # about to kill the SAME process that spawned it, not a PID recycled onto
    # an unrelated process. Without this, a ghost watchdog from a previous
    # run (EXIT trap lost to SIGKILL / crash / reboot) sleeps 600s, wakes,
    # and SIGTERMs whatever process now holds the old PID — observed on
    # evobox-oem-0093 2026-04-21: manual install run completed in 13s, then
    # was killed 35ms after INSTALL END by a ghost watchdog from ~10min ago.
    local _main_starttime
    _main_starttime=$(awk '{print $22}' "/proc/$$/stat" 2>/dev/null)
    # The watchdog sleep is relative to this exact point; use the same monotonic
    # origin for the package-repair headroom calculation.
    WATCHDOG_UPTIME_BASELINE="$(read_uptime_seconds)"
    (
        # Drop inherited fd 200 — otherwise the watchdog (and its sleep child)
        # would pin the flock for LOCK_TIMEOUT even after the main script exits
        # cleanly, blocking every subsequent cron tick.
        exec 200>&-
        # Guard against the EXIT trap race: the trap kills our sleep child
        # first (pkill -P) and SIGTERMs this subshell second. When sleep is
        # interrupted, bash falls through to the log line below before the
        # second SIGTERM arrives, producing a spurious watchdog message on
        # every clean tick. If sleep returns non-zero (i.e. was signalled),
        # exit cleanly instead of logging the bogus timeout.
        sleep "$LOCK_TIMEOUT" || exit 0
        # Verify _main_pid still refers to the original main process before
        # we signal it. A different starttime (or no proc entry at all) means
        # the PID is dead or has been recycled — we are a ghost from a prior
        # run and must exit silently.
        _cur_starttime=$(awk '{print $22}' "/proc/${_main_pid}/stat" 2>/dev/null)
        if [ -z "$_cur_starttime" ] || [ "$_cur_starttime" != "$_main_starttime" ]; then
            exit 0
        fi
        # If we reach here the main process is still alive after LOCK_TIMEOUT.
        # Log before killing so the cause is visible in the install log — the
        # parent gets SIGTERM next and won't have a chance to log itself.
        log "[LOCK][WATCHDOG] Install script exceeded LOCK_TIMEOUT (${LOCK_TIMEOUT}s). Sending SIGTERM to PID ${_main_pid} and its children; SIGKILL after 10s if still alive."
        # Tell a human before the kill, but never make the kill wait for it:
        # the webhook can take minutes (curl retries, two destinations). The
        # alert runs double-forked so it is not a child of this subshell.
        # stdout goes to /dev/null because log() already appends to the log.
        # _evo_install_cleanup reaps this subshell's children and then the
        # subshell itself, which would otherwise take the alert down with it.
        ( notify_install_blocked "install_watchdog" \
            "The install run passed its ${LOCK_TIMEOUT}s limit and the watchdog is stopping it. The step that was running is cut off and the next tick starts over from the top, so a step that always takes this long never finishes. This alert repeats every 6 hours until a tick completes. See the [LOCK][WATCHDOG] line in ${EVOSPORTS_INSTALL_LOG}." \
            </dev/null >/dev/null 2>> "$EVOSPORTS_INSTALL_LOG" & )
        # Graceful first: kill direct children (hung wget/curl/apt) then the main shell
        pkill -TERM -P "$_main_pid" 2>/dev/null
        kill -TERM "$_main_pid" 2>/dev/null
        sleep 10
        # Re-verify before escalating — main may have exited cleanly during
        # the 10s grace window and the PID may now belong to an unrelated
        # process. Skip the SIGKILL escalation if so.
        _cur_starttime=$(awk '{print $22}' "/proc/${_main_pid}/stat" 2>/dev/null)
        if [ -z "$_cur_starttime" ] || [ "$_cur_starttime" != "$_main_starttime" ]; then
            exit 0
        fi
        log "[LOCK][WATCHDOG] Escalating to SIGKILL on PID ${_main_pid} and children."
        # Force if anything survived
        pkill -KILL -P "$_main_pid" 2>/dev/null
        kill -KILL "$_main_pid" 2>/dev/null
    ) &
    # NOTE: _WATCHDOG_PID is intentionally NOT declared with `local`. The
    # EXIT trap below fires AFTER main() returns, at which point any local
    # variable has left scope — the trap would then reap "kill ''" (no-op),
    # leaving the watchdog subshell alive to fire a spurious LOCK_TIMEOUT
    # kill ~10 minutes later. Using a global shell var keeps the PID
    # reachable from the trap. (Pre-existing bug in prod v1.1.0.)
    _WATCHDOG_PID=$!
    # One cleanup function, three traps, no stacking. EXIT covers the normal
    # return; SIGTERM/SIGINT only turn the signal into an ordinary exit with
    # the status bash would have produced anyway, so the same EXIT handler
    # runs. Without those two, the watchdog's SIGTERM (or a Ctrl-C) skips EXIT
    # entirely and every API response buffer the tick had open is left in
    # /tmp. Anything that needs cleanup registers with the cleanup function —
    # it never installs a trap of its own, which would take this slot.
    _evo_install_signal_traps
    # --- End lock ---

    # China/offline early-exit guard. Google services are blocked in China, so
    # the full install would partially fail and churn disk. The OEM setup
    # script (evobox-oem-install.sh) already installed a minimal crontab at
    # the factory, so this branch simply no-ops until the device reaches an
    # unrestricted network. Runs before notify_first_setup_once because that
    # webhook is Google-hosted and would fail in China.
    #
    # Skip the probe entirely once first setup has finished — the device is
    # demonstrably on an unrestricted network and the checks would otherwise
    # add ~100–500ms and an HTTP request to every cron tick for the lifetime
    # of the device.
    if [ ! -f "$HOME/.evo-first-setup-done" ]; then
        check_network_region
        case $? in
            0) log "[REGION] Unrestricted network — proceeding with full install." ;;
            1) log "[REGION] Mainland China network detected — skipping install."; return 0 ;;
            2) log "[REGION] No internet reachable — skipping install."; return 0 ;;
        esac
    fi

    # One-time "device is online, starting deployment" notification
    notify_first_setup_once

    # IMPORTANT: sync_device_config must run BEFORE ensure_sudo_nopasswd.
    # On a fresh OEM device, the active local state can match an older
    # CFG_HISTORY entry. sync_device_config iterates the history and aligns
    # the device to CFG_HISTORY[-1]. Only after that can
    # ensure_sudo_nopasswd reliably install the NOPASSWD sudoers rule.
    # Both run before any other sudo-using step.
    log_debug "=== Synchronizing Device Config ==="
    sync_device_config

    log_debug "=== Ensuring NOPASSWD Sudo ==="
    ensure_sudo_nopasswd
    # Fail closed. Every step below can call sudo and cron gives it no tty to
    # prompt on, so without the rule in effect each one fails on its own with
    # "a password is required" and leaves a half-converged device. Stop here;
    # the next tick tries the rule again from the top.
    if ! sudo_nopasswd_active; then
        log_error "[SUDO] NOPASSWD is not in effect. Skipping this tick: every step after this point needs sudo. Retrying next tick."
        # Nothing on the device fixes this by itself, so tell a human now. Only
        # counts and a yes/no go out; the password history never leaves the box.
        # /etc/sudoers.d is 0755 on the fleet, but if a device has it at 0750
        # evobox cannot look inside, and "no" would be a guess.
        local _rule_present=unknown
        if [ -x /etc/sudoers.d ]; then
            _rule_present=no
            [ -e /etc/sudoers.d/evobox-nopasswd ] && _rule_present=yes
        fi
        notify_install_blocked "sudo_nopasswd" \
            "Initial install is stopped: sudo still asks for a password after the NOPASSWD setup, so every later install step would fail. This tick is skipped and the next one retries. Sudoers rule file present: ${_rule_present}. Password history entries available: ${#CFG_HISTORY[@]}. This alert repeats every 6 hours until the rule is in effect. See the [SUDO] and [CFGSYNC] lines in ${EVOSPORTS_INSTALL_LOG}."
        return 0
    fi
    fresh_clear "install_blocked_sudo_nopasswd"
    ensure_local_state_owner

    # Boot toolchain first: everything below can install packages, and a dpkg
    # trigger or a dkms build regenerates the initramfs. Per the incident report
    # ("Verify zstd executable" before any initramfs work), zstd must be known
    # good before any of that runs — prepare_apt_environment() inside
    # install_system_dependencies() specifically may resume a pending kernel
    # trigger via `dpkg --configure -a`. A kernel installed later in this same
    # tick is validated on the next pass.
    refresh_lock
    log_debug "=== Verifying Boot Integrity ==="
    ensure_boot_integrity
    diagnose_mesa_package_family
    ensure_render_stack_integrity

    # Install dependencies
    refresh_lock
    if [ "$BOOT_INTEGRITY_ZSTD_BROKEN" = true ]; then
        # This is the enforcement half of the ordering above; without it the
        # comment is only a wish. prepare_apt_environment() (first thing
        # install_system_dependencies() does) runs `dpkg --configure -a` on a
        # wedged dpkg, which resumes a pending kernel trigger -> update-initramfs
        # against a broken zstd -> a kernel with a GRUB menuentry and no initrd.
        # Skip the whole package group; the daemon, telemetry and troubleshooting
        # paths below still run, so the device stays managed and reports in.
        # The wide blast radius is deliberate: nvm/pnpm/GPU/wifi/disk-health all
        # pull packages, so any of them can trip the same trigger. A transient
        # zstd problem therefore pauses unrelated maintenance until the next pass
        # clears it — a maintenance pause, not an outage, and the cheap side of
        # the trade against an unbootable device.
        log_error "[BOOT-INTEGRITY] zstd is broken — skipping package installation this tick so a pending"
        log_error "[BOOT-INTEGRITY] kernel trigger cannot rebuild an initramfs. Daemon/telemetry still run. See issue #28."
        notify_install_blocked "zstd_broken" \
            "Package installation is paused: zstd is missing or corrupt and the repair did not fix it. Every step that installs packages is skipped, so a pending kernel trigger cannot build an initramfs with a broken compressor and leave the device unable to boot. The daemon and telemetry still run. The repair is retried every 6 hours, and this alert repeats every 6 hours until zstd is healthy. See the [BOOT-INTEGRITY] lines in ${EVOSPORTS_INSTALL_LOG}."
    else
        fresh_clear "install_blocked_zstd_broken"
        log_debug "=== Installing System Dependencies ==="
        install_system_dependencies
        # One-time system bootstrap (full apt upgrade). Runs AFTER
        # install_system_dependencies so prepare_apt_environment has already
        # self-healed any interrupted dpkg and installed the noninteractive
        # sudoers rule before we attempt a full upgrade.
        run_bootstrap_once
        apply_apt_lock install
        install_node_toolchain
        install_intel_gpu_driver
        install_wifi_service
        disable_ipv6
        setup_disk_health_phase1
        ensure_log_rotation_v2
        configure_grub_no_boot_wait
        configure_time_synchronization
    fi

    # Tailscale VPN and SSH access
    refresh_lock
    log_debug "=== Configuring Tailscale VPN ==="
    install_tailscale
    update_tailscale_tags

    refresh_lock
    log_debug "=== Configuring SSH Access ==="
    configure_ssh_tailscale

    # After SSH (so a naming problem can never delay restoring shell access) and
    # before VNC. Read-only unless the device can prove which stale record is its
    # own; see the TAILSCALE MACHINE-NAME RECONCILIATION block.
    refresh_lock
    log_debug "=== Reconciling Tailscale Machine Name ==="
    reconcile_tailscale_name

    refresh_lock
    log_debug "=== Configuring VNC Access ==="
    configure_display_no_blank
    install_vnc_privacy_scripts
    configure_vnc_tailscale

    # Detect distribution and create lock screen files
    refresh_lock
    log_debug "=== Configuring Lock Screen ==="
    local distro_name=$(lsb_release -si)
    if [ "$distro_name" = "Ubuntu" ]; then
        log_debug "This system is running Ubuntu."
        create_lubuntu_lock_screen_files
    else
        log_debug "This system is not running Ubuntu or Lubuntu."
    fi

    # Create configuration files
    refresh_lock
    log_debug "=== Creating Configuration Files ==="
    create_v4l2loopback_config
    create_sudoer_files
    deploy_obs_plugins

    # Ensure evosports folder exists
    if [[ ! -d "$EVOSPORTS_ROOT" ]]; then
        mkdir "$EVOSPORTS_ROOT"
    fi

    # Install systemd unit + helpers BEFORE daemon-version check, so that
    # check_and_update_daemon_version can safely `systemctl stop` before a
    # re-extract. On first-ever run the unit won't be active yet, so the
    # stop is a no-op (|| true) — that's fine.
    refresh_lock
    log_debug "=== Installing Daemon Supervisor (systemd) ==="
    install_daemon_runner_script
    install_daemon_alert_script
    install_observability_monitor
    install_daemon_systemd_unit

    # Check and update OBS + NDI versions. Skipped with the package group when
    # zstd is broken: `dpkg -i` and `apt-get -f` run pending triggers, and a
    # kernel trigger would rebuild an initramfs with the broken compressor.
    refresh_lock
    if [ "$BOOT_INTEGRITY_ZSTD_BROKEN" != true ]; then
        log_debug "=== Checking OBS & NDI Versions ==="
        check_and_update_obs_ndi
    fi

    # Check and update daemon version
    refresh_lock
    log_debug "=== Reconciling Device Identity ==="
    # Before the version check, so a healthy tree with a broken evo.json is
    # repaired too, not only one that is being reinstalled. If the saved
    # identity cannot be written, download_evobox_daemon() would abort anyway,
    # but only after the version check has stopped the units; skip it so a
    # stuck write does not take the stream down on every retry.
    if reconcile_daemon_identities; then
        fresh_clear "install_blocked_identity_save"
        log_debug "=== Checking Daemon Version ==="
        check_and_update_daemon_version
    else
        log_error "[identity] Cannot save device identity to $EVO_IDENTITY_DIR — skipping the daemon version check so the running daemon is not stopped"
        notify_install_blocked "identity_save" \
            "The device identity cannot be written: either the saved copy in ${EVO_IDENTITY_DIR} or the live evo.json restored from it. The daemon version check is skipped so the running daemon is not stopped, which means this device gets no daemon updates. Without a saved copy, a reinstall could register the device under a new deviceId. This alert repeats every 6 hours until the identity is saved. See the [identity] lines in ${EVOSPORTS_INSTALL_LOG}."
    fi

    # Update crontab
    refresh_lock
    log_debug "=== Updating Crontab ==="
    update_crontab

    # Ensure new deployment version
    if [[ ! -f "$HOME/deployed" ]]; then
        log "No deployed file found, killing all node processes..."
        killall node
        touch "$HOME/deployed"
        log "Deployed file created"
    fi

    # One-time migration: if a legacy nohup'd daemon is still running on
    # this device (pre-systemd install), stop it and hand control to the
    # new systemd-managed unit. Guarded by .evo-systemd-migrated-v1 flag.
    refresh_lock
    log_debug "=== Migrating Legacy Daemon to Systemd ==="
    migrate_legacy_nohup_daemon

    # Start daemons
    refresh_lock
    log_debug "=== Starting Daemons ==="
    start_first_daemon
    start_second_daemon

    # Run maintenance tasks
    refresh_lock
    log_debug "=== Running Maintenance Tasks ==="
    restart_window_manager_if_wayland
    download_obs_scenes
    download_media_files
    download_virtualmic_script
    download_evo_utils
    check_and_restart_splashtop
    install_ndi_keepalive
    check_obs_restoration
    ensure_obs_websocket_enabled
    patch_obs_replay_mp4
    setup_blank_screensaver
    update_wallpaper

    # Last repair step of the tick, so every Tailscale/SSH observation above is
    # already in. Notification failure must never mask the install's own result.
    flush_tailscale_alerts || true

    local _install_elapsed=$(( $(date +%s) - _INSTALL_START_TS ))
    if [ "$_install_elapsed" -gt "$LOCK_WARN_THRESHOLD" ]; then
        log "[EVODAEMON:INSTALL END][WARN] EvoBox install script completed in ${_install_elapsed}s (> ${LOCK_WARN_THRESHOLD}s baseline)."
    else
        log "[EVODAEMON:INSTALL END] EvoBox install script completed in ${_install_elapsed}s."
    fi

    # One-time "deployment finished" notification (fires once per device)
    notify_first_setup_finish_once

    # Run telemetry
    refresh_lock
    log_debug "=== Running Telemetry ==="
    download_and_run_telemetry

    # Run troubleshooting if needed
    refresh_lock
    log_debug "=== Troubleshooting Area ==="
    run_single_machine_troubleshooting
    run_global_troubleshooting

    # APT lock stages 1-2 (snapshot lists, download; see apply_apt_lock). After
    # the daemon update, telemetry and troubleshooting, because a list refresh
    # can take most of 300s on a slow link; before the two auxiliary blocks.
    # Skipped with the package group when zstd is broken, like stage 3.
    refresh_lock
    if [ "$BOOT_INTEGRITY_ZSTD_BROKEN" != true ]; then
        apply_apt_lock prefetch
    fi

    # zowie-ndi-probe and publishd are the LAST TWO blocks, in that order —
    # after the core daemon update/crontab/start, telemetry, and the
    # troubleshooting hooks — so a slow download (or a watchdog kill during one)
    # can only ever cost auxiliary work, never delay or suppress the streaming
    # path, fleet telemetry, or an operator's troubleshooting command. Both sit
    # before fresh_consume_force_flag so a force refresh still reaches their 12h
    # gates. Best-effort: failures are isolated to each block.
    #
    # publishd goes last of the two by the same logic that put zowie here: its
    # downloads (134 MB runtime + 41 MB binary) are an order of magnitude larger
    # than the probe's single small binary, so when it eats the watchdog window
    # the only work sacrificed is its own.
    refresh_lock
    log_debug "=== Checking zowie-ndi-probe (auxiliary) ==="
    install_zowie_ndi_probe_check_wrapper
    check_and_update_zowie_ndi_probe

    refresh_lock
    log_debug "=== Checking publishd ==="
    check_and_update_publishd_stack

    # If this run was triggered by a force-refresh flag, consume it now so
    # subsequent ticks resume the normal 12h GCS-fetch cadence. Done at
    # end-of-main so that any failure earlier in the run leaves the flag in
    # place — the next tick gets another full-refresh attempt.
    fresh_consume_force_flag

    # Cleared only here, after the last step. A tick that the watchdog kills
    # during the auxiliary blocks never reaches this line, so a device that is
    # killed every time alerts once per repeat window and not once per tick.
    fresh_clear "install_blocked_install_watchdog"
}

# Execute main function
main "$@"
