#!/usr/bin/env bash
# ══════════════════════════════════════════════════════════════════════════════
#  NYLIX HOST — Premium VPS Bootstrap v2.0
#  Docker installation · diagnostics · troubleshooting · safe automatic repair
#  Debian 12/13 · Ubuntu 22.04+ · KVM · bare metal · LXC / Incus / LXD / Proxmox
#
#  Usage: bash installer.sh [--diagnose | --repair] [--yes] [--verbose] [--report]
#  Logs:  /var/log/nylix-host/
# ══════════════════════════════════════════════════════════════════════════════
set -uo pipefail
umask 022
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l
if locale -a 2>/dev/null | grep -qiE '^c\.utf-?8$'; then export LC_ALL=C.UTF-8; else export LC_ALL=C; fi

VERSION="2.0"
MODE="install"      # install (default, interactive) | diagnose | repair
ASSUME_YES=0; VERBOSE=0; SHOW_REPORT=0; FORCE_OS=0

usage() {
  cat <<'EOF'
NYLIX HOST — Premium VPS Bootstrap v2.0

Usage: bash installer.sh [options]

  (no options)   Install Docker if missing, diagnose, repair (asks first), verify
  --diagnose     Diagnostics only: no packages, configuration or services changed
                 (test images are pulled and temporary test containers are run)
  --repair       Diagnose and apply safe repairs to an existing Docker install
  --yes, -y      Approve SAFE repairs without prompting. Never approves dangerous
                 operations (stopping processes, restarting Docker with running
                 containers, changing the storage driver, removing packages)
  --verbose, -v  Show command output in the terminal
  --report       Print the full diagnostic report at the end (always saved)
  --force-os     Continue on an unsupported OS (not recommended)
  --help, -h     Show this help

Exit codes: 0 containers run · 2 containers run, networking degraded ·
            3 daemon up, containers cannot run · 4 daemon not operational ·
            1 precondition failed · 130 interrupted
EOF
}
for a in "$@"; do
  case $a in
    --diagnose) MODE=diagnose ;;
    --repair) MODE=repair ;;
    -y|--yes) ASSUME_YES=1 ;;
    -v|--verbose) VERBOSE=1 ;;
    --report) SHOW_REPORT=1 ;;
    --force-os) FORCE_OS=1 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown option: $a (see --help)"; exit 1 ;;
  esac
done
[[ ${NYLIX_LIB_ONLY:-0} == 1 ]] || [[ $EUID -eq 0 ]] || { echo "NYLIX HOST: please run as root (sudo bash installer.sh)"; exit 1; }

RUN_ID=$(date +%Y%m%d-%H%M%S)
LOG_DIR=/var/log/nylix-host
mkdir -p "$LOG_DIR" 2>/dev/null || LOG_DIR=/tmp/nylix-host
mkdir -p "$LOG_DIR"; chmod 0750 "$LOG_DIR" 2>/dev/null
LOG="$LOG_DIR/install-$RUN_ID.log"; : >"$LOG"; chmod 0640 "$LOG" 2>/dev/null
REPORT="$LOG_DIR/report-$RUN_ID.txt"
RUNC_CAPTURE="$LOG_DIR/runc-failure-$RUN_ID.txt"
BACKUP_DIR=/var/backups/nylix-host/$RUN_ID
TMP=$(mktemp -d /tmp/nylix.XXXXXX)
DAEMON_JSON=/etc/docker/daemon.json
TEST_PREFIX="nylix-test-$RUN_ID"
HELLO=hello-world; BUSYBOX=busybox:stable

declare -a REPAIR_OK=() REPAIR_FAIL=() REPAIR_SKIP=() LIMITS=() HOST_ACTIONS=() ISSUES=()
declare -A RES=() CAT=() ERRF=() BEFORE=() BEFORE_CAT=()

# ── Colours & glyphs ──────────────────────────────────────────────────────────
if [[ -t 1 && ${TERM:-dumb} != dumb ]]; then
  TTY=1; R=$'\e[0m'; B=$'\e[1m'; RED=$'\e[38;5;203m'; GRN=$'\e[38;5;48m'; YEL=$'\e[38;5;221m'
  CYN=$'\e[38;5;51m'; BLU=$'\e[38;5;39m'; DIM=$'\e[38;5;245m'; WHT=$'\e[38;5;255m'; LINE=$'\e[38;5;24m'
  GRAD=(51 51 45 45 39 39 33 33 27); SHAD=(30 30 24 24 24 24 18 18 18)
else
  TTY=0; R=""; B=""; RED=""; GRN=""; YEL=""; CYN=""; BLU=""; DIM=""; WHT=""; LINE=""; GRAD=(); SHAD=()
fi
W=$(tput cols 2>/dev/null || echo 80); [[ $W =~ ^[0-9]+$ ]] || W=80; (( W > 90 )) && W=90; (( W < 64 )) && W=64
SPIN=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')

rep() { local s="" i; for ((i=0;i<$2;i++)); do s+=$1; done; printf '%s' "$s"; }
now_ms() { local t=${EPOCHREALTIME/[.,]/}; echo $(( t / 1000 )); }
fmt() { local ms=$1; ((ms<60000)) && printf '%d.%ds' $((ms/1000)) $((ms%1000/100)) || printf '%dm%02ds' $((ms/60000)) $((ms/1000%60)); }
clock() { local s=$(( $1 / 1000 )); printf '%02d:%02d:%02d' $((s/3600)) $((s%3600/60)) $((s%60)); }
# Mask credentials (proxy URLs, tokens, passwords) before anything reaches the log or report.
redact() { sed -E 's#(://)[^/@[:space:]]+:[^/@[:space:]]+@#\1***:***@#g; s#(("|\b)(password|passwd|token|secret|auth)("|\b)[[:space:]]*[:=][[:space:]]*)"?[^",[:space:]]+"?#\1***#Ig'; }
log() { printf '%(%F %T)T %s\n' -1 "$*" | redact >>"$LOG"; }
logfile() { { printf '%(%F %T)T ┌─ %s\n' -1 "$1"; sed 's/^/    │ /' "$2" | redact; printf '    └─\n'; } >>"$LOG" 2>/dev/null; }
rule() { printf '  %s%s%s\n' "$LINE" "$(rep ─ $((W-4)))" "$R"; }
line() { local g=$1 c=$2 t=$3 d=${4:-}; local max=$((W-16)); ((${#t}>max)) && t="${t:0:max-1}…"
         [[ $TTY == 1 ]] && printf '\r\e[2K'
         printf '    %s%s%s  %s%-*s%s %s%s%s\n' "$c" "$g" "$R" "$c" "$max" "$t" "$R" "$DIM" "$d" "$R"; log "[$g] $t $d"; }
ok()   { line "✔" "$GRN" "$1" "${2:-}"; }
fail() { line "✖" "$RED" "$1" "${2:-}"; }
warn() { line "▲" "$YEL" "$1" "${2:-}"; }
skip() { line "•" "$DIM" "$1" "${2:-}"; }
info() { printf '    %s•%s  %s%-20s%s %s\n' "$BLU" "$R" "$DIM" "$1" "$R" "$2"; log "$1: $2"; }
note() { printf '       %s› %s%s\n' "$DIM" "$1" "$R"; log "  › $1"; }
sub()  { printf '\n    %s%s%s\n' "$B$BLU" "$1" "$R"; log "-- $1"; }
issue() { ISSUES+=("[$1] $2"); log "ISSUE [$1] $2"; }                     # issue CATEGORY text
limit() { LIMITS+=("$1"); warn "Host restriction: $1"; [[ -n ${2:-} ]] && note "$2"; }
has() { command -v "$1" >/dev/null 2>&1; }
tty_ok() { { : </dev/tty; } 2>/dev/null; }

cleanup() {
  [[ $TTY == 1 ]] && printf '\e[?25h'
  if [[ -n ${DOCKER_TESTS_RAN:-} ]] && has docker; then test_cleanup_quiet; fi
  rm -rf "$TMP"
}
trap cleanup EXIT
trap 'printf "\n"; fail "Interrupted — safe to re-run. Log: $LOG"; exit 130' INT TERM

# ── Logo ──────────────────────────────────────────────────────────────────────
L_N=("███╗   ██╗" "████╗  ██║" "██╔██╗ ██║" "██║╚██╗██║" "██║ ╚████║" "╚═╝  ╚═══╝")
L_Y=("██╗   ██╗" "╚██╗ ██╔╝" " ╚████╔╝ " "  ╚██╔╝  " "   ██║   " "   ╚═╝   ")
L_L=("██╗     " "██║     " "██║     " "██║     " "███████╗" "╚══════╝")
L_I=("██╗" "██║" "██║" "██║" "██║" "╚═╝")
L_X=("██╗  ██╗" "╚██╗██╔╝" " ╚███╔╝ " " ██╔██╗ " "██╔╝ ██╗" "╚═╝  ╚═╝")
L_H=("██╗  ██╗" "██║  ██║" "███████║" "██╔══██║" "██║  ██║" "╚═╝  ╚═╝")
L_O=(" ██████╗ " "██╔═══██╗" "██║   ██║" "██║   ██║" "╚██████╔╝" " ╚═════╝ ")
L_S=("███████╗" "██╔════╝" "███████╗" "╚════██║" "███████║" "╚══════╝")
L_T=("████████╗" "╚══██╔══╝" "   ██║   " "   ██║   " "   ██║   " "   ╚═╝   ")

logo() {
  local row letter seg fg sh c letters=(N Y L I X _ H O S T) g
  printf '\n'
  for row in 0 1 2 3 4 5; do
    printf '  '; g=0
    for letter in "${letters[@]}"; do
      [[ $letter == _ ]] && { printf '   '; continue; }
      local -n arr="L_$letter"; seg=${arr[$row]}
      if [[ $TTY == 1 ]]; then
        fg=$'\e[38;5;'"${GRAD[g]}m"; sh=$'\e[38;5;'"${SHAD[g]}m"; seg="$fg$seg"
        for c in '╗' '╔' '╝' '╚' '║' '═'; do seg=${seg//"$c"/"$sh$c$fg"}; done
      fi
      printf '%s' "$seg"; g=$((g+1))
    done
    printf '%s\n' "$R"
  done
  printf '\n  %s%sPREMIUM VPS BOOTSTRAP • SYSTEM PROVISIONING%s\n' "$B" "$BLU" "$R"
  rule
  printf '  %sv%s%s  %s│%s  %sNylix Host%s  %s│%s  host %s%s%s  %s│%s  mode %s%s%s\n' "$WHT" "$VERSION" "$R" "$LINE" "$R" "$DIM" "$R" \
    "$LINE" "$R" "$WHT" "$(hostname)" "$R" "$LINE" "$R" "$CYN" "$MODE" "$R"
  printf '  %slog %s%s\n' "$DIM" "$LOG" "$R"
  rule
}

# ── Stages & live tasks ───────────────────────────────────────────────────────
TOTAL=9; START=$(now_ms); STAGE_T=0
stage() {
  STAGE_T=$(now_ms)
  local tag="[$1/$TOTAL]" title=${2^^} ck; ck="⏱ $(clock $(( STAGE_T - START )))"
  local fill=$(( W - ${#tag} - ${#title} - ${#ck} - 9 )); (( fill < 3 )) && fill=3
  printf '\n  %s%s%s%s  %s%s%s %s%s%s %s%s%s\n' "$B" "$CYN" "$tag" "$R" "$B$WHT" "$title" "$R" "$LINE" "$(rep ─ $fill)" "$R" "$DIM" "$ck" "$R"
  log "==== STAGE $1: $2"
}
stage_done() {
  local n=$1 bw=$((W-36)); local f=$(( n * bw / TOTAL ))
  printf '  %s▕%s%s%s%s▏%s %s%3d%%%s  %sstage %s · total %s%s\n' "$LINE" "$CYN" "$(rep █ $f)" "$LINE" "$(rep ░ $((bw-f)))" "$R" \
    "$B$WHT" $(( n * 100 / TOTAL )) "$R" "$DIM" "$(fmt $(( $(now_ms) - STAGE_T )))" "$(clock $(( $(now_ms) - START )))" "$R"
}

# run "<label>" <timeout s> cmd...  — runs a real command with a live spinner,
# a real timer and a real result. apt shows its true percentage (Status-Fd);
# everything else shows an activity pulse. Full output always goes to the log.
OUT=""; RC=0; LAST_MS=0
run() {
  local label=$1 t=$2; shift 2
  case $1 in apt_get|dpkg) ensure_unlocked ;; esac
  OUT="$TMP/out.$RANDOM$RANDOM"; local prog="$OUT.p" t0 f=0 pct bar el pos
  : >"$prog"; t0=$(now_ms)
  log "RUN [$label]: $*"
  if [[ $(type -t "$1") == file ]]; then
    ( trap '' HUP; exec timeout -k 10 "$t" "$@" ) >"$OUT" 2>&1 3>"$prog" </dev/null &
  else
    ( trap '' HUP; "$@" ) >"$OUT" 2>&1 3>"$prog" </dev/null &
  fi
  local pid=$!
  [[ $TTY == 1 ]] && printf '\e[?25l'
  while kill -0 "$pid" 2>/dev/null; do
    el=$(( $(now_ms) - t0 ))
    if (( el > (t + 15) * 1000 )); then pkill -TERM -P "$pid" 2>/dev/null; kill -TERM "$pid" 2>/dev/null; fi
    if [[ $TTY == 1 ]]; then
      pct=$(tail -n1 "$prog" 2>/dev/null | awk -F: '/^(pm|dl)status/ {printf "%d", $3}')
      if [[ -n $pct ]]; then
        local fl=$(( pct * 20 / 100 )); bar="$CYN$(rep █ $fl)$LINE$(rep ░ $((20-fl)))$R $(printf '%3d%%' "$pct")"
      else
        pos=$(( f % 32 )); ((pos > 16)) && pos=$((32 - pos))
        bar="$LINE$(rep ░ $pos)$BLU████$LINE$(rep ░ $((16-pos)))$R     "
      fi
      local l=$label; ((${#l} > W-46)) && l="${l:0:W-47}…"
      printf '\r\e[2K    %s%s%s  %-*s %s▕%s%s▏%s %s%02d:%02d%s' "$CYN" "${SPIN[f%10]}" "$R" $((W-46)) "$l" "$LINE" "$bar" "$LINE" "$R" "$DIM" $((el/60000)) $((el/1000%60)) "$R"
      f=$((f+1)); sleep 0.1
    else sleep 0.2; fi
  done
  wait "$pid"; RC=$?
  LAST_MS=$(( $(now_ms) - t0 ))
  logfile "output of [$label] (exit $RC)" "$OUT"
  local d; d=$(fmt "$LAST_MS")
  if (( RC == 0 )); then ok "$label" "$d"
  elif (( RC == 124 || RC == 137 || RC == 143 )); then fail "$label — timed out" "$d"
  else fail "$label (exit $RC)" "$d"; fi
  if (( VERBOSE )) && [[ -s $OUT ]]; then tail -n 12 "$OUT" | redact | while IFS= read -r l; do printf '       %s│ %s%s\n' "$DIM" "${l:0:$((W-12))}" "$R"; done; fi
  return $RC
}
last_err() { grep -Ei 'error|fail|denied|invalid|cannot|not found|E:' "$OUT" | awk '!s[$0]++' | tail -n "${1:-2}" | redact | while IFS= read -r l; do note "${l:0:$((W-12))}"; done; }

# ── Approvals ─────────────────────────────────────────────────────────────────
ask() {  # y/N on the terminal; no terminal → No
  tty_ok || return 1
  [[ $TTY == 1 ]] && printf '\e[?25h'
  printf '\r\e[2K\n    %s?%s  %s%s%s %s[y/N]%s ' "$B$YEL" "$R" "$B" "$1" "$R" "$DIM" "$R" >/dev/tty
  local a; read -r a </dev/tty || a=""; log "asked: $1 → ${a:-no}"; [[ ${a,,} == y || ${a,,} == yes ]]
}
confirm() {  # SAFE operations: --yes approves
  ((ASSUME_YES)) && { log "auto-approved (--yes): $1"; return 0; }
  tty_ok || { note "Skipped (no terminal) — re-run with --yes to approve safe repairs"; return 1; }
  ask "$1"
}
ask_danger() {  # DANGEROUS operations: always a human decision, --yes never applies
  tty_ok || { note "Skipped: needs an interactive confirmation (never auto-approved)"; return 1; }
  ask "$1"
}

backup() {  # backup <file> — first copy per run wins; records how to restore it
  local f=$1; mkdir -p "$BACKUP_DIR" || return 1
  [[ -f $BACKUP_DIR/rollback.sh ]] || printf '#!/bin/sh\n# NYLIX HOST rollback for run %s (configuration only — never touches Docker data)\n' "$RUN_ID" >"$BACKUP_DIR/rollback.sh"
  grep -qxF -- "$f" "$BACKUP_DIR/.done" 2>/dev/null && return 0
  echo "$f" >>"$BACKUP_DIR/.done"
  if [[ -e $f ]]; then
    mkdir -p "$BACKUP_DIR$(dirname "$f")" && cp -a "$f" "$BACKUP_DIR$f" || return 1
    printf 'cp -a "%s" "%s"\n' "$BACKUP_DIR$f" "$f" >>"$BACKUP_DIR/rollback.sh"
    echo "backed up $f → $BACKUP_DIR$f"
  else
    printf 'rm -f "%s"\n' "$f" >>"$BACKUP_DIR/rollback.sh"
  fi
  log "backup: $f"
}

apt_get() { apt-get -o Acquire::Retries=3 -o DPkg::Lock::Timeout=120 -o APT::Status-Fd=3 \
            -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold "$@"; }
installed() { [[ $(dpkg-query -W -f='${db:Status-Status}' "$1" 2>/dev/null) == installed ]]; }
docker_ok() { has docker && timeout 20 docker info >/dev/null 2>&1; }
systemd_up() { [[ -d /run/systemd/system ]]; }
img_ok() { timeout 15 docker image inspect "$1" >/dev/null 2>&1; }
running_containers() { timeout 15 docker ps -q 2>/dev/null | wc -l; }

# ── Package-lock handling: ask to stop the blocker, or wait for it ─────────────
LOCKS="/var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock"
lock_holders() {
  {
    has fuser && { fuser $LOCKS 2>/dev/null | tr -s ' ' '\n'; echo; }
    has lslocks && lslocks -n -r -o PID,PATH 2>/dev/null | awk '$2 ~ /^\/var\/(lib\/dpkg|lib\/apt\/lists|cache\/apt\/archives)\/lock/ {print $1}'
    if ! has fuser && ! has lslocks; then
      pgrep -x 'apt|apt-get|aptitude|dpkg|packagekitd'; pgrep -f 'bin/unattended-upgrade($| )'
    fi
  } | grep -E '^[0-9]+$' | grep -vx "$$" | sort -un
}
wait_unlocked() { local i; for ((i=0; i<$1; i+=3)); do [[ -z $(lock_holders) ]] && return 0; sleep 3; done; return 1; }
stop_holders() {  # graceful first (systemd stop / SIGTERM), SIGKILL only if ignored
  local p i alive
  systemd_up && timeout 45 systemctl stop apt-daily.service apt-daily-upgrade.service packagekit.service 2>/dev/null
  for p in "$@"; do kill -0 "$p" 2>/dev/null && { echo "SIGTERM → PID $p"; kill -TERM "$p" 2>/dev/null; }; done
  for i in $(seq 20); do
    alive=0; for p in "$@"; do kill -0 "$p" 2>/dev/null && alive=1; done
    (( alive )) || break; sleep 1
  done
  for p in "$@"; do kill -0 "$p" 2>/dev/null && { echo "PID $p ignored SIGTERM — sending SIGKILL"; kill -KILL "$p" 2>/dev/null; }; done
  sleep 1; [[ -z $(lock_holders) ]]
}
ensure_unlocked() {
  local h pids p
  while h=$(lock_holders | tr '\n' ' ') && [[ -n ${h// } ]]; do
    read -ra pids <<<"$h"
    warn "Package manager is busy — locked by ${#pids[@]} process(es)"
    for p in "${pids[@]}"; do note "$(ps -o pid=,etime=,args= -p "$p" 2>/dev/null | awk '{$1=$1; print}' | cut -c1-$((W-14)))"; done
    if ask "Stop the blocking process(es) safely and continue? (No = wait for them to finish)"; then
      if run "Stopping blocking process(es) (SIGTERM, then SIGKILL if ignored)" 90 stop_holders "${pids[@]}"; then
        REPAIR_OK+=("Stopped process(es) blocking apt/dpkg: PID ${pids[*]}")
        run "Repairing package state after the interruption" 900 dpkg --configure -a
      else
        fail "The package lock is still held"
      fi
    else
      tty_ok || note "No terminal to ask — waiting instead."
      if ! run "Waiting for the blocking process(es) to finish" 615 wait_unlocked 600; then
        tty_ok || { fail "Package manager still busy after 10 min — re-run later"; exit 1; }
        note "Still busy after 10 minutes."
      fi
    fi
  done
}

# ── Docker service control (never touches Wings or unrelated services) ───────
start_docker() {
  if systemd_up; then
    systemctl daemon-reload 2>/dev/null
    systemctl reset-failed docker.service docker.socket containerd.service 2>/dev/null
    systemctl enable --now containerd docker 2>&1 || return 1
  elif ! service docker start 2>&1; then
    pgrep -x dockerd >/dev/null || { echo "no service manager — starting dockerd directly"; setsid dockerd >>"$LOG_DIR/dockerd.log" 2>&1 </dev/null & }
  fi
  local i; for i in $(seq 25); do docker_ok && return 0; (( i > 3 )) && ! pgrep -x dockerd >/dev/null && return 1; sleep 2; done; return 1
}
restart_docker() {  # restarts dockerd only (containerd only when asked)
  if [[ ${1:-} == --containerd ]]; then
    if systemd_up; then systemctl restart containerd 2>&1; else service containerd restart 2>&1; fi
  fi
  if systemd_up; then systemctl reset-failed docker.service 2>/dev/null; systemctl restart docker 2>&1 || return 1
  elif ! service docker restart 2>&1; then
    local p; p=$(pgrep -x dockerd | head -n1)
    if [[ -n $p ]]; then kill -TERM "$p"; for _ in $(seq 30); do kill -0 "$p" 2>/dev/null || break; sleep 1; done; fi
    start_docker; return
  fi
  local i; for i in $(seq 25); do docker_ok && return 0; sleep 2; done; return 1
}
restart_allowed() {  # restarting Docker with running workloads is a dangerous operation
  docker_ok || return 0
  local n; n=$(running_containers)
  (( n == 0 )) && return 0
  ask_danger "Docker must restart: $n running container(s)$( ((WINGS)) && echo ' (Pterodactyl Wings servers)') will be restarted. Continue?"
}
daemon_log() {
  { systemd_up && journalctl -u docker -u containerd -n 120 --no-pager -o cat 2>/dev/null
    [[ -r $LOG_DIR/dockerd.log ]] && tail -n 120 "$LOG_DIR/dockerd.log"; } 2>/dev/null
  return 0
}

# ══════════════════════════════════════════════════════════════════════════════
#  Error classification
# ══════════════════════════════════════════════════════════════════════════════
classify() {  # classify <file> → CATEGORY
  local f=$1
  if   grep -qiE 'ip_unprivileged_port_start|reopen fd [0-9]+: permission denied|unsafe procfs detected|procfs.*(not permitted|denied)' "$f"; then echo APPARMOR_RUNC
  elif grep -qiE 'apparmor_parser.*(not found|executable file)|docker-default profile could not be loaded' "$f"; then echo APPARMOR_PARSER
  elif grep -qiE 'apparmor failed to apply|attr/(apparmor/)?exec|apparmor="DENIED"|unable to apply apparmor' "$f"; then echo APPARMOR
  elif grep -qiE 'seccomp' "$f"; then echo SECCOMP
  elif grep -qiE 'session keyring' "$f"; then echo KEYRING
  elif grep -qiE 'lchown .*invalid argument|insufficient uids or gids' "$f"; then echo UIDMAP
  elif grep -qiE 'no space left on device' "$f"; then echo DISK
  elif grep -qiE 'failed to mount overlay|overlay.*(not permitted|invalid argument|not supported)|mount callback failed|error initializing graphdriver|driver not supported|prior storage driver|snapshotter .* (not|unavailable)' "$f"; then echo STORAGE
  elif grep -qiE 'cgroup.*(permission denied|read-only file system)|unable to apply cgroup|cgroup mountpoint does not exist|cannot enter cgroupv2' "$f"; then echo CGROUP
  elif grep -qiE '(mount|mounting) .*proc.*(permission denied|not permitted)|rootfs_linux\.go.*(denied|not permitted)|apply rootfs propagation' "$f"; then echo NESTING
  elif grep -qiE 'unable to configure the docker daemon|invalid character .* looking for|directives (are specified both|don.t match)' "$f"; then echo CONFIG
  elif grep -qiE 'pid file found' "$f"; then echo PIDFILE
  elif grep -qiE 'iptables|nf_tables|failed to create nat chain|failed to (set up|setup) ip ?tables|failed to create bridge|failed to create endpoint|veth|netlink' "$f"; then echo NETWORK
  elif grep -qiE 'sh: [0-9]*:? ?[a-z]+: not found|executable file not found in \$path' "$f"; then echo TEST_IMAGE
  elif grep -qiE 'NX_DNS_FAIL' "$f"; then echo DNS
  elif grep -qiE 'NX_HTTP_FAIL' "$f"; then echo EGRESS
  elif grep -qiE 'toomanyrequests|pull rate limit' "$f"; then echo REGISTRY_RATE
  elif grep -qiE 'forbidden|status(:| code) 403|proxyconnect' "$f"; then echo REGISTRY_BLOCKED
  elif grep -qiE 'no such host|temporary failure in name resolution|server misbehaving|lookup .*(i/o timeout|refused)' "$f"; then echo REGISTRY_DNS
  elif grep -qiE 'tls handshake timeout|i/o timeout|connection (refused|reset)|network is unreachable|dial tcp|client\.timeout' "$f"; then echo REGISTRY_NET
  elif grep -qiE 'permission denied while trying to connect to the docker' "$f"; then echo SOCKET
  elif grep -qiE 'cannot connect to the docker daemon|failed to connect to the docker api|is the docker daemon running' "$f"; then echo DAEMON
  elif grep -qiE 'containerd|shim|oci runtime|runc' "$f"; then echo RUNTIME
  else echo UNKNOWN; fi
}
explain() {
  case $1 in
    APPARMOR_RUNC)   echo "runc's procfs hardening (CVE-2025-52881 fix) is blocked by the OUTER container's AppArmor profile — host-side" ;;
    APPARMOR_PARSER) echo "AppArmor is enabled but apparmor_parser is missing, so Docker cannot load docker-default" ;;
    APPARMOR)        echo "AppArmor denied the container process (nested AppArmor restriction)" ;;
    SECCOMP)         echo "a seccomp filter could not be applied inside this environment" ;;
    KEYRING)         echo "runc cannot create a session keyring (keyctl blocked by the host)" ;;
    UIDMAP)          echo "the container's UID/GID map is too small for files in this image — host-side" ;;
    DISK)            echo "the filesystem holding Docker data is full" ;;
    STORAGE)         echo "the storage driver / snapshotter cannot mount layers here" ;;
    CGROUP)          echo "cgroups are not delegated / writable for nested containers — host-side" ;;
    NESTING)         echo "nested container features (mounting /proc in a new namespace) are blocked — host-side" ;;
    CONFIG)          echo "Docker's daemon configuration is invalid" ;;
    PIDFILE)         echo "a stale /var/run/docker.pid blocks the daemon" ;;
    NETWORK)         echo "Docker networking (bridge/veth/iptables) could not be set up" ;;
    DNS)             echo "name resolution fails inside containers" ;;
    EGRESS)          echo "containers resolve names but cannot connect out (NAT/forwarding)" ;;
    REGISTRY_RATE)   echo "Docker Hub pull rate limit reached" ;;
    REGISTRY_BLOCKED) echo "a proxy or firewall rejects Docker Hub (HTTP 403)" ;;
    REGISTRY_DNS)    echo "the daemon cannot resolve the registry hostname" ;;
    REGISTRY_NET)    echo "the registry is unreachable (timeout / refused)" ;;
    SOCKET)          echo "the user cannot access /var/run/docker.sock" ;;
    DAEMON)          echo "the Docker daemon is not reachable" ;;
    RUNTIME)         echo "the container runtime (containerd/runc) reported an error" ;;
    TEST_IMAGE)      echo "the test image lacks a command used by this test — not a Docker fault" ;;
    *)               echo "unrecognised error — full output is in the log" ;;
  esac
}
# Evidence files: the failing command's own output first, then "### …" context sections.
# The command output decides; the daemon log only refines a generic result and
# can never introduce registry/DNS categories (old pull errors live there too).
evidence_primary() { awk '/^### / {exit} {print}' "$1"; }   # stops at the first context section
classify_evidence() {
  local f=$1 p="$TMP/prim.$RANDOM" c c2
  evidence_primary "$f" >"$p"; c=$(classify "$p")
  if [[ $c =~ ^(UNKNOWN|RUNTIME|DAEMON)$ ]]; then
    c2=$(classify "$f")
    [[ $c2 =~ ^(REGISTRY_|DNS$|EGRESS$|UNKNOWN$) ]] || c=$c2
  fi
  rm -f "$p"; echo "$c"
}
with_daemon_log() { { echo "### daemon log"; daemon_log | tail -n "${2:-80}"; } >>"$1"; }
host_side() { case $1 in APPARMOR_RUNC|APPARMOR|KEYRING|UIDMAP|CGROUP|NESTING|SECCOMP) return 0 ;; *) return 1 ;; esac; }

# ══════════════════════════════════════════════════════════════════════════════
#  1. System detection
# ══════════════════════════════════════════════════════════════════════════════
stage_system() {
  stage 1 "System detection"
  OS_ID=""; OS_VER=""; OS_CODE=""; OS_NAME=""
  if [[ -r /etc/os-release ]]; then
    OS_ID=$(. /etc/os-release; echo "${ID:-}"); OS_VER=$(. /etc/os-release; echo "${VERSION_ID:-}")
    OS_CODE=$(. /etc/os-release; echo "${VERSION_CODENAME:-${UBUNTU_CODENAME:-}}"); OS_NAME=$(. /etc/os-release; echo "${PRETTY_NAME:-}")
  fi
  ARCH=$(dpkg --print-architecture 2>/dev/null || uname -m)
  KERNEL=$(cat /proc/sys/kernel/osrelease 2>/dev/null || uname -r)
  KMAJ=${KERNEL%%.*}; KMIN=${KERNEL#*.}; KMIN=${KMIN%%.*}; [[ $KMAJ =~ ^[0-9]+$ ]] || KMAJ=0; [[ $KMIN =~ ^[0-9]+$ ]] || KMIN=0
  info "Operating system" "${OS_NAME:-unknown}"
  info "Kernel / arch" "$KERNEL · $ARCH"
  info "Init system" "$(systemd_up && echo systemd || echo "$(cat /proc/1/comm 2>/dev/null) (no systemd)")"
  local major=${OS_VER%%.*} minor=${OS_VER#*.}; [[ $major =~ ^[0-9]+$ ]] || major=0; [[ $minor =~ ^[0-9]+$ ]] || minor=0
  local os_ok=0
  if [[ $OS_ID == ubuntu ]] && (( major > 22 || (major == 22 && minor >= 4) )); then os_ok=1; ok "Supported: Ubuntu $OS_VER"
  elif [[ $OS_ID == debian ]] && (( major == 12 || major == 13 )); then os_ok=1; ok "Supported: Debian $OS_VER ($OS_CODE)"
  elif [[ $OS_ID == debian ]] && (( major > 13 )); then os_ok=1; warn "Debian $OS_VER is newer than tested (12/13)"
  fi
  if (( ! os_ok )); then
    if [[ $MODE == diagnose ]] || (( FORCE_OS )); then warn "Unsupported OS (${OS_NAME:-unknown}) — continuing ($( [[ $MODE == diagnose ]] && echo 'diagnose mode' || echo '--force-os'))"
    else fail "Unsupported OS: ${OS_NAME:-unknown} — supported: Ubuntu 22.04+, Debian 12/13 (use --diagnose or --force-os)"; exit 1; fi
  fi
  case $ARCH in amd64|arm64|armhf|ppc64el|s390x) ;; *) warn "Architecture $ARCH has no official Docker packages" ;; esac
  info "Memory" "$(awk '/^MemTotal:/ {print int($2/1024)}' /proc/meminfo 2>/dev/null) MB"
  WINGS=0
  if [[ -f /etc/pterodactyl/config.yml ]] || { systemd_up && systemctl list-unit-files wings.service 2>/dev/null | grep -q '^wings'; }; then
    WINGS=1; warn "Pterodactyl Wings detected — it is never touched; Docker restarts need your confirmation"
  fi
  stage_done 1
}

# ══════════════════════════════════════════════════════════════════════════════
#  2. Virtualization analysis
# ══════════════════════════════════════════════════════════════════════════════
stage_virtualization() {
  stage 2 "Virtualization analysis"
  local sdv sdvc sdvv envc cg1 rootfs hyper=0 vmx=0 lxcfs=0 fullmap=0
  sdv=$(systemd-detect-virt 2>/dev/null || true); sdvc=$(systemd-detect-virt -c 2>/dev/null || true); sdvv=$(systemd-detect-virt -v 2>/dev/null || true)
  envc=$( { tr '\0' '\n' </proc/1/environ; } 2>/dev/null | sed -n 's/^container=//p' | head -n1)
  cg1=$(head -c 400 /proc/1/cgroup 2>/dev/null | tr '\n' ' ')
  rootfs=$(awk '$5 == "/" {for (i=7;i<=NF;i++) if ($i == "-") {print $(i+1); exit}}' /proc/self/mountinfo 2>/dev/null)
  grep -q 'lxcfs' /proc/self/mountinfo 2>/dev/null && lxcfs=1
  grep -qw hypervisor /proc/cpuinfo 2>/dev/null && hyper=1
  grep -qwE 'vmx|svm' /proc/cpuinfo 2>/dev/null && vmx=1
  AALABEL=$(cat /proc/self/attr/apparmor/current 2>/dev/null || cat /proc/self/attr/current 2>/dev/null || true); AALABEL=${AALABEL//$'\0'/}
  UIDMAP=$(awk '{printf "%s→%s(%s) ", $1, $2, $3}' /proc/self/uid_map 2>/dev/null)
  GIDMAP=$(awk '{printf "%s→%s(%s) ", $1, $2, $3}' /proc/self/gid_map 2>/dev/null)
  [[ $(awk 'NR==1{print $1,$2,$3}' /proc/self/uid_map 2>/dev/null) == "0 0 4294967295" ]] && fullmap=1
  UIDCOUNT=$(awk '{s+=$3} END{print s+0}' /proc/self/uid_map 2>/dev/null)
  log "virt evidence: sdv=$sdv sdvc=$sdvc sdvv=$sdvv env=$envc cgroup1=[$cg1] rootfs=$rootfs lxcfs=$lxcfs hyper=$hyper vmx=$vmx label=[$AALABEL]"

  CTECH="none"; PRIV="n/a"; VKIND="unknown"
  if [[ -d /proc/vz && ! -d /proc/bc ]]; then CTECH=openvz
  elif [[ $sdvc == lxc* || $envc == lxc* || $cg1 == *lxc.payload* ]] || { (( lxcfs )) && [[ $sdvc != docker && ! -f /.dockerenv ]]; }; then
    CTECH=lxc
    [[ -S /dev/incus/sock || $AALABEL == incus-* || $cg1 == *incus* ]] && CTECH=incus
    [[ -S /dev/lxd/sock || $AALABEL == lxd-* ]] && CTECH=lxd
    { grep -qs 'BEGIN PVE' /etc/hosts /etc/hostname /etc/network/interfaces || [[ $AALABEL =~ ^lxc-[0-9]+_ ]]; } && CTECH=proxmox
  elif [[ -f /.dockerenv || $sdvc == docker || $cg1 == */docker/* ]]; then CTECH=docker
  elif [[ -f /run/.containerenv || $sdvc == podman ]]; then CTECH=podman
  elif [[ $sdvc == wsl ]] || grep -qsi microsoft /proc/sys/kernel/osrelease; then CTECH=wsl
  fi
  if [[ $CTECH != none ]]; then
    VKIND=container
    if [[ $CTECH =~ ^(lxc|incus|lxd|proxmox)$ ]]; then (( fullmap )) && PRIV=privileged || PRIV=unprivileged; fi
  elif [[ -n $sdvv && $sdvv != none ]] || (( hyper )); then VKIND=vm
  else VKIND=bare-metal; fi
  case $CTECH in
    incus)   VIRT="Incus container ($PRIV)" ;;
    lxd)     VIRT="LXD container ($PRIV)" ;;
    proxmox) VIRT="Proxmox LXC container ($PRIV)" ;;
    lxc)     VIRT="LXC container ($PRIV)" ;;
    docker)  VIRT="Docker container (Docker-in-Docker)" ;;
    podman)  VIRT="Podman container" ;;
    openvz)  VIRT="OpenVZ container" ;;
    wsl)     VIRT="WSL" ;;
    none)
      case ${sdvv:-} in
        kvm) VIRT="KVM virtual machine" ;; qemu) VIRT="QEMU virtual machine (emulated)" ;;
        vmware) VIRT="VMware virtual machine" ;; microsoft) VIRT="Hyper-V virtual machine" ;; xen) VIRT="Xen virtual machine" ;;
        ""|none) [[ $VKIND == vm ]] && VIRT="Virtual machine (unknown hypervisor)" || VIRT="Bare metal" ;;
        *) VIRT="$sdvv virtual machine" ;;
      esac ;;
  esac
  [[ $VKIND == container && $CTECH =~ ^(lxc|incus|lxd|proxmox)$ ]] && has dockerd && VIRT+=" · Docker inside LXC"
  info "Platform" "$CYN$VIRT$R"
  info "Classification" "$VKIND$( [[ $VKIND == container ]] && (( hyper )) && echo ' · the host itself is a VM')"
  [[ $VKIND == vm ]] && info "Nested virtualization" "$( ((vmx)) && echo 'VMX/SVM exposed (nested VMs possible)' || echo 'not exposed')"
  [[ $KERNEL == *-pve* ]] && info "Host kernel" "Proxmox VE kernel"
  info "PID 1 cgroup" "${cg1:0:$((W-30))}"
  info "Root filesystem" "${rootfs:-?}$( ((lxcfs)) && echo ' · lxcfs present')"
  info "UID map" "$UIDMAP"
  info "GID map" "$GIDMAP"
  if [[ $VKIND == container && $PRIV == unprivileged ]] && (( UIDCOUNT < 65536 )); then
    limit "Only $UIDCOUNT UIDs mapped" "Images with files owned by higher UIDs cannot be extracted; the host must map 65536+ IDs."
  fi
  [[ $CTECH == openvz ]] && limit "OpenVZ rarely supports Docker" "Ask the provider for Docker support or use a KVM VPS."
  [[ $CTECH == docker ]] && note "Docker-in-Docker requires the outer container to be privileged or specially configured."
  stage_done 2
}

# ══════════════════════════════════════════════════════════════════════════════
#  3. Security restrictions
# ══════════════════════════════════════════════════════════════════════════════
cap_bit() { [[ $1 =~ ^[0-9a-fA-F]+$ ]] && (( (16#$1 >> $2) & 1 )); }
runc_has_cve_fix() {  # runc 1.2.8+, 1.3.3+, 1.4.0+ contain the CVE-2025-52881 procfs hardening
  local v=${1%%[-+]*} ma mi pa; IFS=. read -r ma mi pa <<<"$v"; pa=${pa:-0}
  [[ $ma =~ ^[0-9]+$ && $mi =~ ^[0-9]+$ && $pa =~ ^[0-9]+$ ]] || return 2
  (( ma > 1 || mi >= 4 || (mi == 3 && pa >= 3) || (mi == 2 && pa >= 8) ))
}
host_nesting_cmd() {
  case ${CTECH:-} in
    incus)   echo "On the host: incus config set <instance> security.nesting=true && incus restart <instance>" ;;
    lxd)     echo "On the host: lxc config set <instance> security.nesting=true && lxc restart <instance>" ;;
    proxmox) echo "On the host: pct set <CTID> --features nesting=1,keyctl=1 && pct reboot <CTID>" ;;
    *)       echo "Ask the provider to enable nesting for this container." ;;
  esac
}
stage_security() {
  stage 3 "Security restrictions"
  sub "AppArmor"
  AA=$( [[ $(cat /sys/module/apparmor/parameters/enabled 2>/dev/null) == Y ]] && echo enabled || echo disabled )
  local pid1label mode="" secfs="not mounted" load="no" macadmin="no"
  pid1label=$(cat /proc/1/attr/apparmor/current 2>/dev/null || cat /proc/1/attr/current 2>/dev/null || true); pid1label=${pid1label//$'\0'/}
  [[ $AALABEL =~ \((enforce|complain|kill|unconfined)\)$ ]] && mode=${BASH_REMATCH[1]}
  awk '$5 == "/sys/kernel/security" {f=1} END {exit !f}' /proc/self/mountinfo 2>/dev/null && secfs="mounted"
  [[ -w /sys/kernel/security/apparmor/.load ]] && load="yes"
  CAPEFF=$(awk '/^CapEff:/{print $2}' /proc/self/status); CAPBND=$(awk '/^CapBnd:/{print $2}' /proc/self/status)
  cap_bit "${CAPEFF:-0}" 33 && macadmin=yes
  DOCKER_DEFAULT_LOADED=unknown
  [[ -r /sys/kernel/security/apparmor/profiles ]] && { grep -q '^docker-default' /sys/kernel/security/apparmor/profiles && DOCKER_DEFAULT_LOADED=yes || DOCKER_DEFAULT_LOADED=no; }
  info "AppArmor module" "$AA"
  info "This process label" "${AALABEL:-n/a}"
  info "PID 1 label" "${pid1label:-n/a}"
  info "securityfs" "$secfs · profile load writable: $load · CAP_MAC_ADMIN: $macadmin"
  info "apparmor_parser" "$(has apparmor_parser && { apparmor_parser --version 2>/dev/null | head -n1; } || echo missing)"
  info "docker-default" "$DOCKER_DEFAULT_LOADED"
  OUTER_AA=0
  if [[ $AA == enabled && -n $AALABEL && $AALABEL != unconfined && $VKIND == container ]]; then
    OUTER_AA=1
    warn "Confined by an outer AppArmor profile (${mode:-enforce}) set by the host"
    note "The guest cannot change or remove this profile — only the host administrator can."
    [[ $AALABEL == *"//&:"* ]] && note "Stacked AppArmor namespace: the guest may load its own profiles (docker-default) beneath it."
  elif [[ $AA == enabled ]]; then ok "AppArmor available; no outer confinement on this system"
  else ok "AppArmor not enabled on this kernel"; fi
  if [[ $AA == enabled ]] && ! has apparmor_parser; then warn "AppArmor enabled but apparmor_parser missing"; issue APPARMOR_PARSER "apparmor_parser missing"; fi

  sub "Seccomp & capabilities"
  local sc scf nnp c
  sc=$(awk '/^Seccomp:/{print $2}' /proc/self/status); scf=$(awk '/^Seccomp_filters:/{print $2}' /proc/self/status); nnp=$(awk '/^NoNewPrivs:/{print $2}' /proc/self/status)
  info "Seccomp" "$( [[ -n $sc ]] && echo "kernel support · mode $sc · inherited filters ${scf:-0} · NoNewPrivs ${nnp:-0}" || echo 'not supported by kernel')"
  [[ -z $sc ]] && issue SECCOMP "kernel without seccomp"
  MISSING=""
  for c in CHOWN:0 DAC_OVERRIDE:1 FOWNER:3 KILL:5 SETGID:6 SETUID:7 SETPCAP:8 NET_BIND_SERVICE:10 NET_ADMIN:12 NET_RAW:13 SYS_CHROOT:18 SYS_ADMIN:21 MKNOD:27 AUDIT_WRITE:29 SETFCAP:31; do
    cap_bit "${CAPBND:-0}" "${c#*:}" || MISSING+="${c%%:*} "
  done
  MISSING=${MISSING% }
  info "Capability bounding" "${CAPBND:-?}${MISSING:+ · missing: $MISSING}"
  if [[ -n $MISSING ]]; then limit "Missing capabilities: $MISSING" "Only the host can grant these."; issue CAPS "missing $MISSING"
  else ok "All capabilities Docker needs are in the bounding set"; fi

  sub "Cgroups & nesting"
  case $(stat -fc %T /sys/fs/cgroup 2>/dev/null) in cgroup2fs) CG=v2 ;; tmpfs) CG=v1 ;; *) CG=none ;; esac
  info "Cgroups" "$CG $( [[ $CG == v2 ]] && cat /sys/fs/cgroup/cgroup.controllers 2>/dev/null)"
  if [[ $CG == v2 ]]; then
    if mkdir "/sys/fs/cgroup/nylix-probe-$$" 2>/dev/null && rmdir "/sys/fs/cgroup/nylix-probe-$$"; then ok "Cgroup v2 tree is delegated (writable)"
    else limit "Cgroup tree is not writable" "The host must delegate cgroups to this container (enabled with nesting)."; issue CGROUP "cgroup tree not writable"; fi
  elif [[ $CG == none ]]; then limit "No cgroup filesystem mounted" ""; issue CGROUP "no cgroupfs"; fi
  NEST=unknown
  if has unshare; then
    if timeout 15 unshare --mount --pid --fork --mount-proc true 2>"$TMP/ns"; then NEST=yes; ok "Nested namespaces allowed (mount/pid + /proc)"
    else NEST=no; limit "Nested containers blocked: $(head -n1 "$TMP/ns")" "$(host_nesting_cmd)"; issue NESTING "unshare/mount-proc denied"; fi
    if timeout 15 unshare --net sh -c 'v=$(cat /proc/sys/net/ipv4/ip_unprivileged_port_start) && echo "$v" > /proc/sys/net/ipv4/ip_unprivileged_port_start' 2>"$TMP/sysctl"; then
      ok "Network sysctl write in a new netns (direct /proc path) allowed"
    else warn "Network sysctl write in a new netns denied: $(head -n1 "$TMP/sysctl")"; fi
  else warn "unshare (util-linux) missing — namespace probes skipped"; fi
  [[ -c /dev/fuse ]] && FUSE=yes || FUSE=no
  info "/dev/fuse" "$FUSE"

  sub "Runtime security compatibility"
  RUNC_V=$(runc --version 2>/dev/null | awk 'NR==1{print $3}'); CTRD_V=$(containerd --version 2>/dev/null | awk '{print $3}')
  info "runc / containerd" "${RUNC_V:-not installed} / ${CTRD_V:-not installed}"
  RUNC_RISK=0
  if [[ -n $RUNC_V ]] && runc_has_cve_fix "$RUNC_V"; then
    note "runc $RUNC_V includes the CVE-2025-52881 procfs hardening."
    if (( OUTER_AA )); then RUNC_RISK=1; warn "Known incompatibility: this runc + an outer AppArmor profile fails unless the host is updated"; fi
  fi
  stage_done 3
}

# ══════════════════════════════════════════════════════════════════════════════
#  4. Package manager health
# ══════════════════════════════════════════════════════════════════════════════
stage_packages() {
  stage 4 "Package manager health"
  if [[ $MODE == diagnose ]]; then
    local h; h=$(lock_holders | tr '\n' ' ')
    if [[ -n ${h// } ]]; then warn "apt/dpkg locked by PID $h (diagnose mode: not touched)"; else ok "No process is blocking apt/dpkg"; fi
    if [[ -n $(dpkg --audit 2>/dev/null) ]]; then warn "Interrupted dpkg operations pending"; issue PACKAGES "dpkg --configure -a needed"; else ok "dpkg database consistent"; fi
    if timeout 60 apt-get check >/dev/null 2>&1; then ok "Package dependencies consistent"; else warn "Broken package dependencies"; issue PACKAGES "apt-get -f install needed"; fi
    note "Diagnose mode: package index not refreshed, nothing installed."
    stage_done 4; return
  fi
  ensure_unlocked
  ok "No process is blocking apt/dpkg"
  if [[ -n $(dpkg --audit 2>/dev/null) ]]; then
    warn "Interrupted dpkg operations found"
    if run "Repair: finishing interrupted dpkg operations" 900 dpkg --configure -a && [[ -z $(dpkg --audit 2>/dev/null) ]]; then
      ok "Verified: dpkg database consistent"; REPAIR_OK+=("Completed interrupted dpkg operations")
    else REPAIR_FAIL+=("dpkg --configure -a did not complete"); last_err; fi
  else ok "dpkg database consistent"; fi
  if ! timeout 60 apt-get check >/dev/null 2>&1; then
    warn "Broken package dependencies"
    if run "Repair: fixing broken dependencies" 900 apt_get -f install -y && timeout 60 apt-get check >/dev/null 2>&1; then
      ok "Verified: dependencies consistent"; REPAIR_OK+=("Repaired broken apt dependencies")
    else REPAIR_FAIL+=("apt-get -f install did not fix dependencies"); last_err; fi
  else ok "Package dependencies consistent"; fi
  if ! run "Refreshing package index" 600 apt_get update; then
    grep -qi 'Conflicting values set for option Signed-By' "$OUT" && note "Duplicate Docker repository entries with different keys — keep one file in /etc/apt/sources.list.d/"
    grep -qiE 'not valid yet|expired' "$OUT" && note "System clock looks wrong: $(date -u)"
    grep -qiE 'Temporary failure resolving' "$OUT" && note "DNS is failing — check /etc/resolv.conf"
    last_err 2
  fi
  local need="" p
  for p in curl:curl jq:jq gpg:gnupg; do has "${p%%:*}" || need+="${p#*:} "; done
  [[ -r /etc/ssl/certs/ca-certificates.crt ]] || need+="ca-certificates "
  if [[ -n $need ]]; then
    if ! run "Installing prerequisites: $need" 900 apt_get install -y $need; then
      last_err
      has dockerd || [[ $MODE == repair ]] || { fail "Cannot install Docker without: $need"; exit 1; }
      warn "Continuing without: $need (some repairs need jq)"
    fi
  else ok "Prerequisites present (curl, jq, gnupg, CA certificates)"; fi
  stage_done 4
}

# ══════════════════════════════════════════════════════════════════════════════
#  5. Docker installation
# ══════════════════════════════════════════════════════════════════════════════
docker_get_key() {
  install -m 0755 -d /etc/apt/keyrings
  curl -fsSL --retry 3 --max-time 60 "https://download.docker.com/linux/$OS_ID/gpg" -o "$TMP/docker.asc" || return 1
  local fpr; fpr=$(gpg --batch --with-colons --show-keys "$TMP/docker.asc" 2>/dev/null | awk -F: '/^fpr/{print $10; exit}')
  [[ $fpr == 9DC858229FC7DD38854AE2D88D81803C0EBFCD88 ]] || { echo "Docker key fingerprint mismatch: ${fpr:-none}"; return 1; }
  install -m 0644 "$TMP/docker.asc" /etc/apt/keyrings/docker.asc
  if ! grep -rqsE '^[^#]*download\.docker\.com' /etc/apt/sources.list /etc/apt/sources.list.d/; then
    printf 'Types: deb\nURIs: https://download.docker.com/linux/%s\nSuites: %s\nComponents: stable\nArchitectures: %s\nSigned-By: /etc/apt/keyrings/docker.asc\n' \
      "$OS_ID" "$OS_CODE" "$ARCH" >/etc/apt/sources.list.d/docker.sources
  fi
}
stage_install() {
  stage 5 "Docker installation"
  if has dockerd || installed docker-ce || installed docker.io; then
    ok "Docker already installed ($(docker --version 2>/dev/null | cut -d, -f1)) — not reinstalling"
  elif [[ $MODE != install ]]; then
    fail "Docker is not installed ($MODE mode does not install — run without options to install)"
    issue DAEMON "Docker not installed"
  else
    local conflict="" p done=0
    for p in containerd runc podman-docker; do installed "$p" && conflict+="$p "; done
    if [[ -n $conflict ]]; then
      warn "Packages conflicting with Docker's containerd.io: $conflict"
      if ask_danger "Remove (not purge) $conflict so Docker can be installed?"; then
        run "Removing $conflict" 600 apt_get remove -y $conflict || { fail "Could not remove $conflict"; exit 1; }
      else fail "Cannot install Docker alongside $conflict"; exit 1; fi
    fi
    if run "Adding Docker repository (key fingerprint verified)" 120 docker_get_key && run "Refreshing package index" 600 apt_get update \
       && [[ -n $(apt-cache policy docker-ce 2>/dev/null | awk '/Candidate:/ && $2 != "(none)" {print $2}') ]]; then
      run "Installing Docker Engine, containerd, Buildx, Compose" 1800 apt_get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin && done=1
    else warn "Docker's official repository has no package for $OS_ID $OS_CODE/$ARCH"; fi
    if (( ! done )) && confirm "Install the distribution's docker.io package instead?"; then
      run "Installing docker.io (distribution package)" 1800 apt_get install -y docker.io && done=1
    fi
    (( done )) || { last_err 3; fail "Docker installation failed — see $LOG"; exit 1; }
    run "Starting containerd and Docker" 120 start_docker || note "Startup is analysed in the next stages."
  fi
  RUNC_V=$(runc --version 2>/dev/null | awk 'NR==1{print $3}'); CTRD_V=$(containerd --version 2>/dev/null | awk '{print $3}')
  DOCKER_V=$(docker --version 2>/dev/null | sed -n 's/^Docker version \([^,]*\).*/\1/p')
  info "Versions" "Docker ${DOCKER_V:-n/a} · containerd ${CTRD_V:-n/a} · runc ${RUNC_V:-n/a}"
  if [[ -n $RUNC_V ]] && runc_has_cve_fix "$RUNC_V" && (( OUTER_AA )); then RUNC_RISK=1; fi
  stage_done 5
}

# ══════════════════════════════════════════════════════════════════════════════
#  6. Docker daemon & storage
# ══════════════════════════════════════════════════════════════════════════════
stage_daemon() {
  stage 6 "Docker daemon & storage"
  DAEMON_UP=0; HAS_DATA=1; DRIVER=""; DRIVER_TYPE=""; DATA_ROOT=/var/lib/docker; SECOPTS=""; DJ_BAD=0
  sub "Daemon"
  if ! has docker; then fail "Docker CLI not installed"; stage_done 6; return; fi
  if run "Daemon connectivity (docker info)" 30 docker info; then DAEMON_UP=1
  else
    cp "$OUT" "$TMP/daemon.err"; with_daemon_log "$TMP/daemon.err"
    local dc; dc=$(classify_evidence "$TMP/daemon.err"); issue "$dc" "daemon not reachable"
    note "[$dc] $(explain "$dc")"
    systemd_up && note "docker.service: $(systemctl is-active docker 2>/dev/null) · containerd.service: $(systemctl is-active containerd 2>/dev/null)"
  fi
  if [[ -s $DAEMON_JSON ]]; then
    if has jq && ! jq -e . "$DAEMON_JSON" >/dev/null 2>&1; then
      fail "daemon.json is not valid JSON: $(jq . "$DAEMON_JSON" 2>&1 >/dev/null | head -n1)"; issue CONFIG "daemon.json syntax"; DJ_BAD=1
    else
      has jq && info "daemon.json keys" "$(jq -r 'keys | join(", ")' "$DAEMON_JSON" 2>/dev/null)"
      if has dockerd && dockerd --help 2>&1 | grep -q -- '--validate'; then
        if timeout 30 dockerd --validate --config-file "$DAEMON_JSON" >"$TMP/validate" 2>&1; then ok "daemon.json validated by dockerd"
        else fail "dockerd rejects daemon.json: $(head -n1 "$TMP/validate" | redact)"; issue CONFIG "daemon.json invalid value"; DJ_BAD=2; fi
      fi
    fi
  else ok "daemon.json: not present (Docker defaults)"; fi
  if [[ -f /var/run/docker.pid ]] && ! pgrep -x dockerd >/dev/null; then warn "Stale /var/run/docker.pid (no dockerd running)"; issue PIDFILE "stale pid file"; fi
  if [[ -d /var/run/docker.sock ]]; then fail "/var/run/docker.sock is a directory"; issue SOCKET "socket path is a directory"
  elif [[ -S /var/run/docker.sock ]]; then
    local sp; sp=$(stat -c '%U:%G %a' /var/run/docker.sock)
    info "Docker socket" "$sp"
    if getent group docker >/dev/null && [[ $sp != "root:docker 660" ]]; then warn "Unexpected socket permissions ($sp, expected root:docker 660)"; issue SOCKET "socket perms $sp"; fi
    if [[ -n ${SUDO_USER:-} && $SUDO_USER != root ]] && ! id -nG "$SUDO_USER" 2>/dev/null | tr ' ' '\n' | grep -qx docker; then
      note "User $SUDO_USER is not in the docker group (needs sudo; membership would be root-equivalent)."
    fi
  fi
  if (( DAEMON_UP )); then
    local o sv ds cgd cgv lr nc ni nv
    o=$(timeout 20 docker info --format '{{.ServerVersion}}|{{.Driver}}|{{json .DriverStatus}}|{{.DockerRootDir}}|{{.CgroupDriver}}|{{.CgroupVersion}}|{{join .SecurityOptions ","}}|{{.LiveRestoreEnabled}}' 2>/dev/null)
    IFS='|' read -r sv DRIVER ds DATA_ROOT cgd cgv SECOPTS lr <<<"$o"
    DATA_ROOT=${DATA_ROOT:-/var/lib/docker}
    [[ $ds == *io.containerd.snapshotter* ]] && DRIVER_TYPE="containerd snapshotter" || DRIVER_TYPE="graph driver"
    info "Server" "Docker $sv · cgroup ${cgd:-?}/v${cgv:-?} · live-restore ${lr:-?}"
    info "Security options" "${SECOPTS//name=/}"
    [[ $AA == enabled && $SECOPTS != *apparmor* ]] && note "Docker does not report AppArmor support although the kernel module is enabled."
    nc=$(timeout 20 docker ps -aq | wc -l); ni=$(timeout 20 docker images -q | wc -l); nv=$(timeout 20 docker volume ls -q | wc -l)
    info "Existing data" "$nc containers ($(running_containers) running) · $ni images · $nv volumes"
    (( nc + ni + nv == 0 )) && HAS_DATA=0
  elif [[ -z $(ls -A /var/lib/docker/containers /var/lib/docker/volumes /var/lib/docker/image 2>/dev/null | grep -v -e '^metadata.db$' -e '^backingFsBlockDev$' -e ':$' -e '^$') ]]; then
    HAS_DATA=0
  else info "Existing data" "present on disk (daemon down — not counted)"; fi
  sub "Storage"
  info "Driver" "${DRIVER:-unknown}${DRIVER_TYPE:+ ($DRIVER_TYPE)}"
  info "Data root" "$DATA_ROOT"
  local pd fs dfp dfi
  pd=$DATA_ROOT; while [[ ! -d $pd && $pd != / ]]; do pd=$(dirname "$pd"); done
  fs=$(stat -fc %T "$pd" 2>/dev/null)
  dfp=$(df -P "$pd" 2>/dev/null | awk 'NR==2{gsub("%","",$5); print $5}'); dfi=$(df -Pi "$pd" 2>/dev/null | awk 'NR==2{gsub("%","",$5); print $5}')
  info "Filesystem" "$fs · disk ${dfp:-?}% used · inodes ${dfi:-?}% used · $(df -Pm "$pd" 2>/dev/null | awk 'NR==2{print $4}') MB free"
  if [[ $dfp =~ ^[0-9]+$ ]] && (( dfp >= 95 )); then fail "Disk almost full (${dfp}%) — free space manually; nothing is pruned"; issue DISK "disk ${dfp}%"
  elif [[ $dfp =~ ^[0-9]+$ ]] && (( dfp >= 85 )); then warn "Disk ${dfp}% used"; fi
  if [[ $dfi =~ ^[0-9]+$ ]] && (( dfi >= 95 )); then fail "Inodes exhausted (${dfi}%)"; issue DISK "inodes ${dfi}%"; fi
  OVERLAY=unknown
  if has unshare; then
    OVERLAY=fail
    local P o; P=$(mktemp -d "$pd/.nylix-ovl.XXXXXX" 2>/dev/null || mktemp -d /var/lib/.nylix-ovl.XXXXXX)
    mkdir -p "$P"/{l,u,w,m}; echo x >"$P/l/f"; : >"$TMP/ovl"
    for o in "" ",userxattr"; do
      if timeout 15 unshare --mount sh -c 'mount -t overlay o -o "lowerdir=$1/l,upperdir=$1/u,workdir=$1/w$2" "$1/m" && touch "$1/m/g" && [ -f "$1/u/g" ]' _ "$P" "$o" 2>>"$TMP/ovl"; then OVERLAY=pass; break; fi
      rm -rf "$P/u" "$P/w"; mkdir -p "$P/u" "$P/w"
    done
    [[ $P == */.nylix-ovl.* ]] && rm -rf -- "$P"
  fi
  if [[ $OVERLAY == pass ]]; then ok "OverlayFS mounts on $fs (overlay2 / overlayfs snapshotter usable)"
  elif [[ $OVERLAY == fail ]]; then
    warn "OverlayFS cannot mount on $fs: $(tail -n1 "$TMP/ovl")"
    [[ $DRIVER == overlay* ]] && issue STORAGE "driver $DRIVER but overlay probe fails"
    note "Alternatives: $( [[ $FUSE == yes ]] && echo 'fuse-overlayfs (via /dev/fuse), ')vfs (always works, full copy per layer)."
  else note "OverlayFS probe skipped (unshare missing)"; fi
  sub "Host networking (read-only checks)"
  info "IPv4 forwarding" "$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null || echo '?')"
  if has ip; then
    if ip link show docker0 >/dev/null 2>&1; then info "docker0 bridge" "$(ip -br addr show docker0 2>/dev/null | awk '{print $2, $3}')"
    elif (( DAEMON_UP )); then warn "docker0 bridge not present"; fi
  fi
  if has iptables; then
    info "iptables" "$(iptables --version 2>/dev/null)"
    if (( DAEMON_UP )); then
      if timeout 10 iptables -t nat -S POSTROUTING 2>/dev/null | grep -q MASQUERADE; then ok "Docker NAT (MASQUERADE) rule present"
      elif has nft && timeout 10 nft list ruleset 2>/dev/null | grep -qi masquerade; then ok "Docker NAT present (nftables)"
      else warn "No MASQUERADE rule found — containers may lack outbound access"; fi
    fi
  else warn "iptables not installed"; fi
  if timeout 10 getent hosts registry-1.docker.io >/dev/null 2>&1; then ok "Host DNS resolves registry-1.docker.io"; HOST_DNS=1
  else warn "Host DNS cannot resolve registry-1.docker.io"; HOST_DNS=0; issue REGISTRY_DNS "host DNS"; fi
  stage_done 6
}

# ══════════════════════════════════════════════════════════════════════════════
#  7. Container execution tests (independent; each records pass/fail/skip)
# ══════════════════════════════════════════════════════════════════════════════
TESTS=(daemon pull_hello pull_busybox create start exec exit network dns internet c2c bind volume cleanup)
declare -A TLABEL=([daemon]="Daemon connectivity" [pull_hello]="Image pull (hello-world)" [pull_busybox]="Image pull (busybox)"
  [create]="Container creation" [start]="Container start" [exec]="Process execution" [exit]="Exit status"
  [network]="Container networking" [dns]="DNS inside container" [internet]="Internet from container"
  [c2c]="Container-to-container" [bind]="Bind mount" [volume]="Named volume" [cleanup]="Test cleanup")

tres()  { RES[$1]=$2; CAT[$1]=""; log "TEST $1 = $2"; }
tskip() { RES[$1]=skip; CAT[$1]=""; skip "${TLABEL[$1]} — skipped: $2"; log "TEST $1 = skip ($2)"; }
tfail() {  # tfail <id> <evidence file>
  local f="$TMP/err.$1.$RANDOM" first; cp "$2" "$f"; ERRF[$1]=$f
  RES[$1]=fail; CAT[$1]=$(classify_evidence "$f"); log "TEST $1 = fail [${CAT[$1]}]"
  first=$(evidence_primary "$f" | grep -Ei 'error|denied|fail|cannot|not found|NX_' | grep -v '^###' | tail -n1 | redact)
  [[ -n $first ]] && note "${first:0:$((W-12))}"
  note "[${CAT[$1]}] $(explain "${CAT[$1]}")"
}
tname() { echo "$TEST_PREFIX-$1-$RANDOM"; }
pull_img() {  # retry only transient failures
  local i o; for i in 1 2 3; do
    o=$(docker pull "$1" 2>&1) && { echo "$o"; return 0; }
    echo "$o"; grep -qiE 'forbidden|denied|not found|toomanyrequests|no space|unauthorized' <<<"$o" && return 1; sleep $((i*5))
  done; return 1
}
capture_runc_failure() {  # <container> <start output file> → complete evidence file
  local n=$1 f="$TMP/runc.$RANDOM"
  {
    cat "$2"
    echo "### container state"; timeout 15 docker inspect -f 'Status={{.State.Status}} ExitCode={{.State.ExitCode}} Error={{.State.Error}}' "$n" 2>&1
    echo "### docker logs"; timeout 15 docker logs "$n" 2>&1 | tail -n 20
    echo "### versions"; docker --version 2>&1; containerd --version 2>&1; runc --version 2>&1
    echo "### security"; echo "process label: $AALABEL"; echo "docker security options: $SECOPTS"
    echo "### kernel AppArmor messages (usually hidden inside containers — check the host's kernel log)"
    { journalctl -k --no-pager -n 400 2>/dev/null || dmesg 2>/dev/null; } | grep -i 'apparmor="DENIED"' | tail -n 15
    echo "### daemon log"; daemon_log | tail -n 80
  } >"$f" 2>&1
  { echo "=== $(date) — run $RUN_ID — $n"; redact <"$f"; echo; } >>"$RUNC_CAPTURE"
  printf '%s' "$f"
}
t_daemon() {
  if run "${TLABEL[daemon]}" 30 docker info; then tres daemon pass; return 0; fi
  with_daemon_log "$OUT"; tfail daemon "$OUT"; return 1
}
t_pull() {  # t_pull <id> <image>
  if run "${TLABEL[$1]}" 300 pull_img "$2"; then tres "$1" pass; return 0; fi
  tfail "$1" "$OUT"
  img_ok "$2" && note "$2 is already present locally — dependent tests still run."
  return 1
}
t_container() {  # create → start → exec → exit, each reported separately
  local x n ev code logs
  if ! img_ok "$HELLO"; then for x in create start exec exit; do tskip "$x" "hello-world image not available"; done; return 1; fi
  n=$(tname hello)
  if ! run "${TLABEL[create]}" 60 docker create --name "$n" "$HELLO"; then
    tfail create "$OUT"; for x in start exec exit; do tskip "$x" "container was not created"; done; return 1
  fi
  tres create pass
  if ! run "${TLABEL[start]}" 90 docker start "$n"; then
    ev=$(capture_runc_failure "$n" "$OUT"); tfail start "$ev"
    note "Full runc error capture: $RUNC_CAPTURE"
    tskip exec "container did not start"; tskip exit "container did not start"
    timeout 30 docker rm -f "$n" >/dev/null 2>&1; return 1
  fi
  tres start pass
  code=$(timeout 60 docker wait "$n" 2>&1 | tail -n1); logs=$(timeout 15 docker logs "$n" 2>&1)
  if grep -q 'Hello from Docker!' <<<"$logs"; then tres exec pass; ok "${TLABEL[exec]} (expected output received)"
  else printf '%s\nwait: %s\n' "$logs" "$code" >"$TMP/exec"; fail "${TLABEL[exec]} — expected output missing"; tfail exec "$TMP/exec"; fi
  if [[ $code == 0 ]]; then tres exit pass; ok "${TLABEL[exit]} (code 0)"
  else echo "exit code: $code" >"$TMP/exitc"; fail "${TLABEL[exit]} — code ${code:-unknown}"; tfail exit "$TMP/exitc"; fi
  timeout 30 docker rm "$n" >/dev/null 2>&1
  [[ ${RES[exec]} == pass && ${RES[exit]} == pass ]]
}
bb_run() {  # bb_run <id> [docker run options…] -- <command…>   (busybox, auto-removed)
  local id=$1 opts=(); shift
  if ! img_ok "$BUSYBOX"; then tskip "$id" "busybox image not available"; return 2; fi
  while (( $# )) && [[ $1 != -- ]]; do opts+=("$1"); shift; done; shift
  if run "${TLABEL[$id]}" 90 docker run --rm --name "$(tname "$id")" "${opts[@]}" "$BUSYBOX" "$@"; then tres "$id" pass; return 0; fi
  with_daemon_log "$OUT" 40; tfail "$id" "$OUT"; return 1
}
t_network() { bb_run network -- sh -c 'ip -4 addr show eth0 | grep -q "inet " && echo eth0-ok'; }
t_dns() {
  bb_run dns -- sh -c 'o=$(nslookup registry-1.docker.io 2>&1); if echo "$o" | grep -q "^Name:"; then echo NX_DNS_OK; else echo "$o"; echo NX_DNS_FAIL; exit 1; fi'
}
t_internet() {
  [[ ${RES[dns]:-} == fail ]] && { tskip internet "DNS inside containers fails"; return 2; }
  bb_run internet -- sh -c 'if wget -q -T 10 -O /dev/null http://deb.debian.org/debian/; then echo NX_HTTP_OK; else echo NX_HTTP_FAIL; exit 1; fi'
}
c2c_test() {  # $1 network, $2 server name
  docker network create "$1" >/dev/null || return 1
  docker run -d --name "$2" --network "$1" "$BUSYBOX" httpd -f -p 8080 -h /etc >/dev/null || return 1
  sleep 1
  local o; o=$(docker run --rm --network "$1" "$BUSYBOX" wget -q -T 10 -O - "http://$2:8080/passwd" 2>&1); echo "$o" | tail -n 3
  grep -q '^root:' <<<"$o"
}
t_c2c() {
  if ! img_ok "$BUSYBOX"; then tskip c2c "busybox image not available"; return 2; fi
  local net="$TEST_PREFIX-net" srv; srv=$(tname srv)
  if run "${TLABEL[c2c]}" 90 c2c_test "$net" "$srv"; then tres c2c pass; else with_daemon_log "$OUT" 40; tfail c2c "$OUT"; fi
  timeout 30 docker rm -f "$srv" >/dev/null 2>&1; timeout 30 docker network rm "$net" >/dev/null 2>&1
  [[ ${RES[c2c]} == pass ]]
}
t_bind() {
  local d="$TMP/bind.$RANDOM"; mkdir -p "$d"; chmod 0777 "$d"
  bb_run bind -v "$d:/nylix" -- sh -c 'echo nylix-bind-ok > /nylix/probe' || return 1
  if [[ $(cat "$d/probe" 2>/dev/null) != nylix-bind-ok ]]; then
    echo "container wrote to the bind mount but nothing is visible on the host ($d/probe)" >"$TMP/bindf"
    fail "Bind mount — data not visible on the host"; tfail bind "$TMP/bindf"; return 1
  fi
}
vol_test() {  # $1 volume
  docker volume create "$1" >/dev/null || return 1
  docker run --rm -v "$1:/data" "$BUSYBOX" sh -c 'echo nylix-volume-ok > /data/probe' || return 1
  local o; o=$(docker run --rm -v "$1:/data" "$BUSYBOX" cat /data/probe 2>&1); echo "$o"
  grep -q nylix-volume-ok <<<"$o"
}
t_volume() {
  if ! img_ok "$BUSYBOX"; then tskip volume "busybox image not available"; return 2; fi
  local v="$TEST_PREFIX-vol"
  if run "${TLABEL[volume]}" 90 vol_test "$v"; then tres volume pass; else with_daemon_log "$OUT" 40; tfail volume "$OUT"; fi
  timeout 30 docker volume rm "$v" >/dev/null 2>&1   # only this run's own test volume
  [[ ${RES[volume]} == pass ]]
}
test_cleanup_quiet() {  # removes ONLY objects whose names carry this run's unique prefix
  local ids; ids=$(timeout 20 docker ps -aq --filter "name=$TEST_PREFIX" 2>/dev/null)
  [[ -n $ids ]] && timeout 30 docker rm -f $ids >/dev/null 2>&1
  timeout 20 docker network ls -q --filter "name=$TEST_PREFIX" 2>/dev/null | xargs -r timeout 20 docker network rm >/dev/null 2>&1
  timeout 20 docker volume ls -q --filter "name=$TEST_PREFIX" 2>/dev/null | xargs -r timeout 20 docker volume rm >/dev/null 2>&1
  return 0
}
t_cleanup() {
  test_cleanup_quiet
  local left; left=$( { timeout 20 docker ps -aq --filter "name=$TEST_PREFIX"; timeout 20 docker network ls -q --filter "name=$TEST_PREFIX"; timeout 20 docker volume ls -q --filter "name=$TEST_PREFIX"; } 2>/dev/null | wc -l)
  if (( left == 0 )); then tres cleanup pass; ok "${TLABEL[cleanup]} (no test containers, networks or volumes left)"
  else echo "$left test objects remain" >"$TMP/cl"; fail "${TLABEL[cleanup]} — $left objects remain"; tfail cleanup "$TMP/cl"; fi
}
run_all_tests() {
  local t
  RES=(); CAT=(); ERRF=(); DOCKER_TESTS_RAN=1
  if ! has docker; then for t in "${TESTS[@]}"; do tskip "$t" "Docker not installed"; done; return; fi
  if ! t_daemon; then for t in "${TESTS[@]:1}"; do tskip "$t" "daemon unreachable"; done; return; fi
  t_pull pull_hello "$HELLO"
  t_pull pull_busybox "$BUSYBOX"
  t_container
  t_network; t_dns; t_internet; t_c2c; t_bind; t_volume
  t_cleanup
}
workaround_probes() {  # diagnostics only — nothing here changes configuration
  PROBE_HOSTNET=""; PROBE_AAUNCONF=""
  [[ ${RES[start]:-} == fail ]] && img_ok "$HELLO" || return 0
  sub "Diagnostic probes (one-off test containers — no settings are changed)"
  if run "Probe: hello-world with --network host" 90 docker run --rm --network host "$HELLO" && grep -q 'Hello from Docker!' "$OUT"; then
    PROBE_HOSTNET=works; note "Containers WITHOUT their own network namespace start (Docker writes no network sysctls for them)."
  else PROBE_HOSTNET=fails; fi
  if [[ $AA == enabled ]]; then
    if run "Probe: hello-world without Docker's inner AppArmor profile" 90 docker run --rm --security-opt apparmor=unconfined "$HELLO" && grep -q 'Hello from Docker!' "$OUT"; then
      PROBE_AAUNCONF=works; note "Docker's own docker-default profile is the blocker (guest-side)."
    else PROBE_AAUNCONF=fails; note "Still blocked without Docker's own profile → the restriction is the OUTER host profile."; fi
  fi
  test_cleanup_quiet
}
stage_tests() {
  stage 7 "Container execution tests"
  run_all_tests
  local k; for k in "${!RES[@]}"; do BEFORE[$k]=${RES[$k]}; BEFORE_CAT[$k]=${CAT[$k]:-}; done
  workaround_probes
  stage_done 7
}

# ══════════════════════════════════════════════════════════════════════════════
#  8. Automatic repair engine
#  repair <title> <diagnosis> <check fn> <apply fn> <retest fn> <safe|danger> [restart]
#  1 diagnose · 2 check the fix fits · 3 back up · 4 apply · 5 restart only what
#  is needed · 6 re-run the original failing test · 7 report
# ══════════════════════════════════════════════════════════════════════════════
REPAIRS_TRIED=0; CHECK_MSG=""
repair() {
  local title=$1 diag=$2 check=$3 apply=$4 retest=$5 kind=$6 restart=${7:-}
  sub "Repair: $title"
  note "Diagnosis: $diag"
  REPAIRS_TRIED=$((REPAIRS_TRIED+1))
  if [[ $MODE == diagnose ]]; then note "Diagnose mode — not applied."; REPAIR_SKIP+=("$title (diagnose mode)"); return 1; fi
  CHECK_MSG=""
  if ! $check; then note "Not applicable: $CHECK_MSG"; REPAIR_SKIP+=("$title — $CHECK_MSG"); return 1; fi
  note "Check: ${CHECK_MSG:-fix is appropriate}"
  if [[ $kind == danger ]]; then ask_danger "$title?" || { REPAIR_SKIP+=("$title (not confirmed)"); return 1; }
  else confirm "$title?" || { REPAIR_SKIP+=("$title (not approved)"); return 1; }; fi
  if [[ $restart == restart ]] && ! restart_allowed; then REPAIR_SKIP+=("$title (Docker restart not approved)"); return 1; fi
  if ! run "Applying: $title" 600 "$apply"; then last_err 3; REPAIR_FAIL+=("$title — apply step failed"); return 1; fi
  grep -h '^backed up' "$OUT" 2>/dev/null | while IFS= read -r l; do note "$l"; done
  note "Re-running the original failing test…"
  if $retest; then ok "Verified: $title"; REPAIR_OK+=("$title"); return 0; fi
  fail "Not fixed: $title (verification still fails)"; REPAIR_FAIL+=("$title — applied, verification still fails")
  return 1
}

chk_service() { { systemd_up || has service || has dockerd; } || { CHECK_MSG="no way to start dockerd"; return 1; }; CHECK_MSG="dockerd is installed but not answering"; }
fix_service() { start_docker; }

chk_json() {
  [[ ${DJ_BAD:-0} == 1 ]] || { CHECK_MSG="daemon.json syntax is valid"; return 1; }
  if grep -qE '"(storage-driver|data-root|graph|userns-remap|features)"' "$DAEMON_JSON"; then
    CHECK_MSG="file contains storage/data settings — fix it by hand so existing data stays visible"; return 1; fi
  CHECK_MSG="invalid JSON without storage/data settings — safe to set aside"
}
fix_json() { backup "$DAEMON_JSON" && mv -f "$DAEMON_JSON" "$DAEMON_JSON.invalid-$RUN_ID" && echo "moved to $DAEMON_JSON.invalid-$RUN_ID" && start_docker; }

chk_pid() { { [[ -f /var/run/docker.pid ]] && ! pgrep -x dockerd >/dev/null; } || { CHECK_MSG="no stale PID file"; return 1; }; CHECK_MSG="PID file exists but no dockerd process is running"; }
fix_pid() { backup /var/run/docker.pid && rm -f /var/run/docker.pid && start_docker; }

chk_ctrd() { { [[ -f /etc/containerd/config.toml ]] && has containerd && ! timeout 15 containerd config dump >/dev/null 2>&1; } || { CHECK_MSG="containerd configuration parses"; return 1; }; CHECK_MSG="config.toml does not parse"; }
fix_ctrd() { backup /etc/containerd/config.toml && mv -f /etc/containerd/config.toml "/etc/containerd/config.toml.invalid-$RUN_ID" && restart_docker --containerd; }

IPT_ALT=""
chk_ipt() {
  daemon_log | grep -qiE 'iptables|nf_tables|NAT chain' || { CHECK_MSG="no iptables errors in the daemon log"; return 1; }
  has update-alternatives || { CHECK_MSG="update-alternatives missing"; return 1; }
  local cur; cur=$(iptables --version 2>/dev/null); IPT_ALT=""
  [[ $cur == *nf_tables* ]] && has iptables-legacy && timeout 10 iptables-legacy -t nat -S >/dev/null 2>&1 && IPT_ALT=legacy
  [[ $cur == *legacy* ]] && has iptables-nft && timeout 10 iptables-nft -t nat -S >/dev/null 2>&1 && IPT_ALT=nft
  [[ -n $IPT_ALT ]] || { CHECK_MSG="no working alternative iptables backend"; return 1; }
  CHECK_MSG="current backend fails, iptables-$IPT_ALT works (reversible; no rules are flushed)"
}
fix_ipt() {
  mkdir -p "$BACKUP_DIR"; echo "update-alternatives --set iptables $(readlink -f "$(command -v iptables)")" >>"$BACKUP_DIR/rollback.sh"
  update-alternatives --set iptables "/usr/sbin/iptables-$IPT_ALT" && update-alternatives --set ip6tables "/usr/sbin/ip6tables-$IPT_ALT" && restart_docker
}

chk_socket() {
  { [[ -S /var/run/docker.sock ]] && getent group docker >/dev/null; } || { CHECK_MSG="no socket or no docker group"; return 1; }
  [[ $(stat -c '%U:%G %a' /var/run/docker.sock) != "root:docker 660" ]] || { CHECK_MSG="permissions already correct"; return 1; }
  CHECK_MSG="socket is $(stat -c '%U:%G %a' /var/run/docker.sock), expected root:docker 660"
}
fix_socket() { chown root:docker /var/run/docker.sock && chmod 0660 /var/run/docker.sock; }
rt_socket() { [[ $(stat -c '%U:%G %a' /var/run/docker.sock) == "root:docker 660" ]] && t_daemon; }

chk_aaparser() { { [[ $AA == enabled ]] && ! has apparmor_parser; } || { CHECK_MSG="apparmor_parser present or AppArmor off"; return 1; }; CHECK_MSG="AppArmor on, parser missing"; }
fix_aaparser() { apt_get install -y apparmor && restart_docker; }
rt_container() { t_container; }

STORAGE_TARGET=""
chk_storage() {
  (( HAS_DATA )) && { CHECK_MSG="Docker holds existing images/containers/volumes — switching drivers would hide them; change it manually if intended"; return 1; }
  has jq || { CHECK_MSG="jq is required to edit daemon.json safely"; return 1; }
  [[ ${DJ_BAD:-0} == 0 ]] || { CHECK_MSG="daemon.json must be valid first"; return 1; }
  STORAGE_TARGET=$( [[ $FUSE == yes ]] && echo fuse-overlayfs || echo vfs )
  [[ $DRIVER == "$STORAGE_TARGET" ]] && { CHECK_MSG="already using $STORAGE_TARGET"; return 1; }
  CHECK_MSG="no existing Docker data; '$STORAGE_TARGET' works where overlay cannot$( [[ $STORAGE_TARGET == vfs ]] && echo ' (vfs: no copy-on-write, more disk, slower pulls)')"
}
fix_storage() {
  if [[ $STORAGE_TARGET == fuse-overlayfs ]] && ! has fuse-overlayfs; then apt_get install -y fuse-overlayfs || return 1; fi
  mkdir -p /etc/docker && backup "$DAEMON_JSON" || return 1
  local cur='{}'; [[ -s $DAEMON_JSON ]] && cur=$(cat "$DAEMON_JSON")
  jq --arg d "$STORAGE_TARGET" '."storage-driver" = $d | .features = ((.features // {}) + {"containerd-snapshotter": false})' <<<"$cur" >"$TMP/dj.new" || return 1
  if dockerd --help 2>&1 | grep -q -- '--validate'; then dockerd --validate --config-file "$TMP/dj.new" || return 1; fi
  install -m 0644 "$TMP/dj.new" "$DAEMON_JSON" && restart_docker
}
rt_storage() {
  [[ $(timeout 20 docker info --format '{{.Driver}}' 2>/dev/null) == "$STORAGE_TARGET" ]] || { fail "Active driver is not $STORAGE_TARGET"; return 1; }
  DRIVER=$STORAGE_TARGET; t_pull pull_hello "$HELLO"; t_container
}

DNS_SERVERS=""
chk_dns() {
  [[ ${HOST_DNS:-0} == 1 ]] || { CHECK_MSG="host DNS fails too — fix the host resolver first"; return 1; }
  has jq || { CHECK_MSG="jq required"; return 1; }
  [[ ${DJ_BAD:-0} == 0 ]] || { CHECK_MSG="daemon.json must be valid first"; return 1; }
  if [[ -s $DAEMON_JSON ]] && jq -e '.dns' "$DAEMON_JSON" >/dev/null 2>&1; then CHECK_MSG="daemon.json already sets dns — not overriding"; return 1; fi
  DNS_SERVERS=$(for f in /run/systemd/resolve/resolv.conf /etc/resolv.conf; do [[ -r $f ]] && awk '/^nameserver/ && $2 !~ /^127\./ && $2 != "::1" {print $2}' "$f"; done | awk '!s[$0]++' | head -n 3 | tr '\n' ' ')
  [[ -n ${DNS_SERVERS// } ]] || { CHECK_MSG="host only has loopback resolvers"; return 1; }
  CHECK_MSG="containers will use the host's upstream resolvers: $DNS_SERVERS"
}
fix_dns() {
  mkdir -p /etc/docker && backup "$DAEMON_JSON" || return 1
  local cur='{}' list; [[ -s $DAEMON_JSON ]] && cur=$(cat "$DAEMON_JSON")
  list=$(printf '%s\n' $DNS_SERVERS | jq -R . | jq -sc .)
  jq --argjson d "$list" '.dns = $d' <<<"$cur" >"$TMP/dj.new" && install -m 0644 "$TMP/dj.new" "$DAEMON_JSON" && restart_docker
}
rt_dns() { t_dns && t_internet; }

chk_fwd() {
  [[ $(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null) == 0 ]] || { CHECK_MSG="IPv4 forwarding already enabled"; return 1; }
  [[ -w /proc/sys/net/ipv4/ip_forward ]] || { CHECK_MSG="ip_forward is read-only here — host-side"; return 1; }
  CHECK_MSG="ip_forward=0 blocks container NAT; enable at runtime (not persisted)"
}
fix_fwd() { mkdir -p "$BACKUP_DIR"; echo "sysctl -w net.ipv4.ip_forward=0" >>"$BACKUP_DIR/rollback.sh"; sysctl -w net.ipv4.ip_forward=1; }

has_issue() { local i; for i in "${ISSUES[@]}"; do [[ $i == "[$1]"* ]] && return 0; done; return 1; }

stage_repair() {
  stage 8 "Automatic repair"
  [[ $MODE == diagnose ]] && note "Diagnose mode: applicable repairs are listed but not applied."
  # Daemon startup
  if [[ ${RES[daemon]:-} == fail ]]; then
    local dc=${CAT[daemon]:-DAEMON}
    [[ ${DJ_BAD:-0} == 1 ]] && repair "Set aside invalid daemon.json and start Docker" "daemon.json is not valid JSON" chk_json fix_json t_daemon safe
    [[ ${RES[daemon]} == fail && -f /var/run/docker.pid ]] && repair "Remove stale docker.pid and start Docker" "PID file blocks the daemon" chk_pid fix_pid t_daemon safe
    [[ ${RES[daemon]} == fail && -f /etc/containerd/config.toml ]] && repair "Move invalid containerd config aside and restart" "containerd configuration" chk_ctrd fix_ctrd t_daemon safe
    [[ ${RES[daemon]} == fail && $dc == NETWORK ]] && repair "Switch iptables backend and start Docker" "daemon fails to set up iptables" chk_ipt fix_ipt t_daemon safe
    [[ ${RES[daemon]} == fail ]] && repair "Start the Docker service" "daemon not answering ($(explain "$dc"))" chk_service fix_service t_daemon safe
    [[ ${RES[daemon]} == fail && ${DJ_BAD:-0} == 2 ]] && note "dockerd rejects a value in daemon.json — fix it by hand (validate: dockerd --validate --config-file $DAEMON_JSON)."
    if [[ ${RES[daemon]} == pass ]]; then DAEMON_UP=1; note "Daemon is up — running the remaining container tests now."; run_all_tests; workaround_probes; fi
  fi
  if has_issue SOCKET && [[ -S /var/run/docker.sock ]]; then
    repair "Restore Docker socket permissions (root:docker 660)" "socket ownership/permissions are unexpected" chk_socket fix_socket rt_socket safe
  fi
  local sc=${CAT[start]:-} cc=${CAT[create]:-} pc=${CAT[pull_hello]:-}
  if [[ ${RES[start]:-} != pass ]] && { [[ $sc == APPARMOR_PARSER ]] || has_issue APPARMOR_PARSER; }; then
    repair "Install apparmor (parser) and restart Docker" "Docker cannot load its AppArmor profile" chk_aaparser fix_aaparser rt_container safe restart
  fi
  if [[ $sc == STORAGE || $cc == STORAGE || $pc == STORAGE ]] || { [[ $OVERLAY == fail && $DRIVER == overlay* && ${RES[start]:-} != pass ]]; }; then
    repair "Switch Docker storage driver for this environment" "layers cannot be mounted with ${DRIVER:-the current driver}" chk_storage fix_storage rt_storage danger restart
  fi
  if [[ ${RES[dns]:-} == fail && ${CAT[dns]:-} == DNS ]]; then
    repair "Give containers the host's upstream DNS servers" "containers cannot resolve names" chk_dns fix_dns rt_dns safe restart
  fi
  if [[ ${RES[internet]:-} == fail && ${CAT[internet]:-} == EGRESS ]]; then
    repair "Enable IPv4 forwarding (runtime)" "containers have no outbound connectivity" chk_fwd fix_fwd t_internet safe
  fi
  if [[ ${RES[network]:-} == fail && ${CAT[network]:-} == NETWORK ]]; then
    repair "Switch iptables backend" "container networking cannot be set up" chk_ipt fix_ipt t_network safe restart
  fi
  host_report
  (( REPAIRS_TRIED == 0 )) && ok "No guest-side repair needed"
  stage_done 8
}

host_report() {
  local cats=" " t i c
  for t in "${TESTS[@]}"; do [[ ${RES[$t]:-} == fail ]] && cats+="${CAT[$t]:-} "; done
  for i in "${ISSUES[@]}"; do c=${i#\[}; cats+="${c%%\]*} "; done
  HOST_ACTIONS=()
  if [[ $cats == *" APPARMOR_RUNC "* ]] || { (( RUNC_RISK )) && [[ ${RES[start]:-} == fail ]]; }; then
    sub "HOST-SIDE: outer AppArmor profile blocks runc"
    fail "Container start is blocked outside this VPS — it cannot be repaired from inside the guest"
    note "runc ${RUNC_V:-?} hardened its procfs handling (CVE-2025-52881 fix). The AppArmor profile the host applies"
    note "to this container (${AALABEL:-unknown}) denies that access, so containers with their own network namespace fail."
    case $CTECH in
      incus)
        HOST_ACTIONS+=("Update Incus on the HOST to a build that includes lxc/incus PR #2624 (support for the new runc behaviour). The Zabbly stable packages include it; Incus 6.0.0 from Ubuntu's own archive has been reported as still affected."
                       "Keep nesting enabled: incus config set <instance> security.nesting=true"
                       "Restart the instance after the host update: incus restart <instance>"
                       "There is no raw.lxc workaround on Incus — Incus generates the AppArmor rules itself.") ;;
      lxd)
        HOST_ACTIONS+=("Update LXD on the HOST to 6.6 or newer, which carries a workaround (snap refresh lxd --channel=6/stable)."
                       "Keep security.nesting=true on the instance and restart it after the update.") ;;
      proxmox)
        HOST_ACTIONS+=("Upgrade the Proxmox HOST (reported fixed in Proxmox VE 9.1) and restart the CT."
                       "Keep features nesting=1,keyctl=1 on the CT.") ;;
      *)
        HOST_ACTIONS+=("Update LXC / the container manager on the HOST to a release whose AppArmor profile supports runc's new procfs handling, then restart the container.") ;;
    esac
    HOST_ACTIONS+=("Not applied by this script because it weakens security: downgrading/holding containerd.io (e.g. 1.7.28-1) or runc reintroduces CVE-2025-52565/52881/31133.")
    [[ ${PROBE_HOSTNET:-} == works ]] && HOST_ACTIONS+=("Verified interim option (per container, reduces network isolation): containers started with --network host run. Nothing was changed.")
    LIMITS+=("Outer AppArmor profile blocks runc ${RUNC_V:-} (host update required)")
  elif [[ $cats == *" APPARMOR "* ]]; then
    sub "HOST-SIDE: nested AppArmor restriction"
    HOST_ACTIONS+=("Enable nesting for this container: $(host_nesting_cmd)")
    [[ ${PROBE_AAUNCONF:-} == works ]] && HOST_ACTIONS+=("Verified: the inner docker-default profile is the blocker; per-container --security-opt apparmor=unconfined runs (weakens isolation — not applied).")
  fi
  [[ $cats == *" NESTING "* || $cats == *" CGROUP "* ]] && HOST_ACTIONS+=("Allow nested containers / cgroup delegation: $(host_nesting_cmd)")
  [[ $cats == *" KEYRING "* ]] && HOST_ACTIONS+=("Allow keyctl for this container (Proxmox: features keyctl=1; Incus/LXD: security.nesting=true).")
  [[ $cats == *" UIDMAP "* ]] && HOST_ACTIONS+=("Map at least 65536 UIDs/GIDs to this container.")
  [[ $cats == *" SECCOMP "* ]] && HOST_ACTIONS+=("Allow nested seccomp filters for this container (host kernel / container manager setting).")
  [[ $cats == *" CAPS "* ]] && HOST_ACTIONS+=("Grant the missing capabilities: $MISSING")
  for t in "${HOST_ACTIONS[@]}"; do note "$t"; done
  [[ $cats == *" DISK "* ]] && note "Disk/inode pressure: free space manually (inspect with: docker system df). Nothing is deleted automatically."
  [[ $cats == *" REGISTRY_BLOCKED "* ]] && note "Allow outbound HTTPS to registry-1.docker.io, auth.docker.io and production.cloudflare.docker.com."
  [[ $cats == *" REGISTRY_RATE "* ]] && note "Docker Hub rate limit: wait, or run 'docker login'."
  return 0
}

# ══════════════════════════════════════════════════════════════════════════════
#  9. Final verification, summary and report
# ══════════════════════════════════════════════════════════════════════════════
stage_final() {
  stage 9 "Final verification"
  local t core=pass netbad=0
  if docker_ok; then DRIVER=$(timeout 20 docker info --format '{{.Driver}}' 2>/dev/null); fi
  if (( ${#REPAIR_OK[@]} > 0 )); then note "Repairs were applied — re-running every container test."; run_all_tests
  else note "No repair changed the system — stage 7 results are final (not re-run)."; fi
  for t in "${TESTS[@]}"; do [[ -n ${RES[$t]:-} ]] || RES[$t]=skip; done
  for t in daemon create start exec exit; do [[ ${RES[$t]} == pass ]] || core=fail; done
  local skipped=0
  for t in pull_hello pull_busybox network dns internet c2c bind volume; do
    [[ ${RES[$t]} == fail ]] && netbad=1; [[ ${RES[$t]} == skip ]] && skipped=$((skipped+1))
  done
  if [[ ${RES[daemon]} != pass ]]; then VC=$RED; VERDICT="DOCKER DAEMON NOT OPERATIONAL"; CODE=4
  elif [[ $core == pass && $netbad == 0 && $skipped == 0 ]]; then VC=$GRN; VERDICT="DOCKER FULLY OPERATIONAL"; CODE=0
  elif [[ $core == pass && $netbad == 0 ]]; then VC=$GRN; VERDICT="CONTAINERS RUN - $skipped TEST(S) NOT RUN"; CODE=0
  elif [[ $core == pass ]]; then VC=$YEL; VERDICT="CONTAINERS RUN - SOME FEATURES DEGRADED"; CODE=2
  elif [[ ${RES[start]} == fail ]] && host_side "${CAT[start]:-}"; then VC=$RED; VERDICT="CONTAINERS BLOCKED BY HOST RESTRICTION"; CODE=3
  else VC=$RED; VERDICT="CONTAINERS CANNOT RUN"; CODE=3; fi
  summary
  write_report
  stage_done 9
}
cell() { case $1 in pass) printf '%s✔ pass  %s' "$GRN" "$R" ;; fail) printf '%s✖ fail  %s' "$RED" "$R" ;; *) printf '%s• skip  %s' "$DIM" "$R" ;; esac; }
box() { printf '  %s%s%s%s%s\n' "$1" "$2" "$(rep ─ $((W-6)))" "$3" "$R"; }
summary() {
  local t c cw=$((W-53))
  printf '\n'; box "$LINE" "┌" "┐"
  printf '  %s│%s  %s%sNYLIX HOST  ◆  %-*s%s%s│%s\n' "$LINE" "$R" "$B" "$VC" $((W-23)) "$VERDICT" "$R" "$LINE" "$R"
  box "$LINE" "├" "┤"
  printf '  %s│%s  %s%-26s %-8s %-8s %-*s%s%s│%s\n' "$LINE" "$R" "$DIM" "Test" "Before" "After" "$cw" "Category" "$R" "$LINE" "$R"
  for t in "${TESTS[@]}"; do
    c=""; [[ ${RES[$t]} == fail ]] && c=${CAT[$t]:-}
    printf '  %s│%s  %-26s %s %s %s%-*s%s%s│%s\n' "$LINE" "$R" "${TLABEL[$t]}" "$(cell "${BEFORE[$t]:-skip}")" "$(cell "${RES[$t]}")" "$DIM" "$cw" "${c:0:$cw}" "$R" "$LINE" "$R"
  done
  box "$LINE" "└" "┘"
  info "Platform" "$VIRT · ${OS_NAME:-?} · kernel $KERNEL"
  info "Docker stack" "Docker ${DOCKER_V:-n/a} · containerd ${CTRD_V:-n/a} · runc ${RUNC_V:-n/a} · ${DRIVER:-?}"
  info "Total time" "$(clock $(( $(now_ms) - START )))"
  for t in "${REPAIR_OK[@]}"; do printf '    %s✔%s  repaired & verified: %s\n' "$GRN" "$R" "$t"; done
  for t in "${REPAIR_FAIL[@]}"; do printf '    %s✖%s  repair failed: %s\n' "$RED" "$R" "$t"; done
  for t in "${REPAIR_SKIP[@]}"; do printf '    %s•%s  not applied: %s\n' "$DIM" "$R" "$t"; done
  if (( ${#HOST_ACTIONS[@]} )); then
    printf '\n    %s%sACTION REQUIRED BY THE HOST ADMINISTRATOR / PROVIDER%s\n' "$B" "$YEL" "$R"
    for t in "${HOST_ACTIONS[@]}"; do printf '    %s▲%s  %s\n' "$YEL" "$R" "$t"; done
  fi
  printf '\n'
  info "Report" "$REPORT"
  info "Log" "$LOG"
  [[ -s $RUNC_CAPTURE ]] && info "runc failure capture" "$RUNC_CAPTURE"
  [[ -f $BACKUP_DIR/rollback.sh ]] && info "Rollback" "sh $BACKUP_DIR/rollback.sh"
  return 0
}
write_report() {
  local t
  {
    echo "NYLIX HOST — Docker Diagnostic Report  (installer v$VERSION, run $RUN_ID, mode $MODE)"
    echo "Generated: $(date '+%F %T %Z')   Host: $(hostname)"
    echo "Verdict: $VERDICT (exit $CODE)"
    echo
    echo "[System]"; echo "  ${OS_NAME:-?} · kernel $KERNEL · $ARCH · Pterodactyl Wings: $( ((WINGS)) && echo detected || echo no)"
    echo "[Virtualization]"; echo "  $VIRT · kind $VKIND · technology $CTECH · privilege $PRIV"; echo "  UID map: $UIDMAP"; echo "  GID map: $GIDMAP"
    echo "[Security]"
    echo "  AppArmor $AA · label ${AALABEL:-n/a} · outer confinement $( ((OUTER_AA)) && echo yes || echo no) · docker-default $DOCKER_DEFAULT_LOADED"
    echo "  Capability bounding ${CAPBND:-?} · missing ${MISSING:-none} · cgroups $CG · nesting probe $NEST · /dev/fuse $FUSE"
    echo "  runc ${RUNC_V:-n/a} (CVE-2025-52881 hardening: $( [[ -n $RUNC_V ]] && runc_has_cve_fix "$RUNC_V" && echo yes || echo no)) · containerd ${CTRD_V:-n/a} · known incompatibility risk: $( ((RUNC_RISK)) && echo HIGH || echo no)"
    echo "[Docker]"
    echo "  Docker ${DOCKER_V:-n/a} · driver ${DRIVER:-?} (${DRIVER_TYPE:-?}) · data root $DATA_ROOT · overlay probe $OVERLAY · existing data $( ((HAS_DATA)) && echo yes || echo no)"
    echo "  Security options: ${SECOPTS:-n/a}"
    echo "[Tests]  before → after  (category of a final failure)"
    for t in "${TESTS[@]}"; do printf '  %-26s %-5s → %-5s %s\n' "${TLABEL[$t]}" "${BEFORE[$t]:-skip}" "${RES[$t]}" "$( [[ ${RES[$t]} == fail ]] && echo "${CAT[$t]:-} — $(explain "${CAT[$t]:-}")")"; done
    [[ -n ${PROBE_HOSTNET:-} ]] && echo "  Diagnostic probes: --network host → $PROBE_HOSTNET · inner apparmor=unconfined → ${PROBE_AAUNCONF:-not run} (nothing applied)"
    echo "[Issues detected]"; for t in "${ISSUES[@]}"; do echo "  - $t"; done; (( ${#ISSUES[@]} )) || echo "  (none)"
    echo "[Repairs]"
    for t in "${REPAIR_OK[@]}"; do echo "  OK      $t"; done
    for t in "${REPAIR_FAIL[@]}"; do echo "  FAILED  $t"; done
    for t in "${REPAIR_SKIP[@]}"; do echo "  SKIPPED $t"; done
    (( ${#REPAIR_OK[@]} + ${#REPAIR_FAIL[@]} + ${#REPAIR_SKIP[@]} )) || echo "  (none)"
    echo "[Host-side restrictions]"; for t in "${LIMITS[@]}"; do echo "  - $t"; done; (( ${#LIMITS[@]} )) || echo "  (none)"
    echo "[Required administrator action]"; for t in "${HOST_ACTIONS[@]}"; do echo "  - $t"; done; (( ${#HOST_ACTIONS[@]} )) || echo "  (none)"
    echo "[Files]"; echo "  Log: $LOG"
    [[ -s $RUNC_CAPTURE ]] && echo "  runc failure capture: $RUNC_CAPTURE"
    [[ -f $BACKUP_DIR/rollback.sh ]] && echo "  Rollback: sh $BACKUP_DIR/rollback.sh"
  } | redact >"$REPORT"
  chmod 0640 "$REPORT" 2>/dev/null
  ln -sfn "$REPORT" "$LOG_DIR/latest-report.txt" 2>/dev/null
  log "report: $REPORT"
}

# ══════════════════════════════════════════════════════════════════════════════
main() {
  AA=disabled; OUTER_AA=0; RUNC_RISK=0; RUNC_V=""; CTRD_V=""; DOCKER_V=""; FUSE=no; CG=none; NEST=unknown
  MISSING=""; CAPBND=""; DOCKER_DEFAULT_LOADED=unknown; DJ_BAD=0; HOST_DNS=0; DRIVER=""; DRIVER_TYPE=""
  DATA_ROOT=/var/lib/docker; SECOPTS=""; HAS_DATA=1; OVERLAY=unknown; VERDICT=""; CODE=1; VC=$RED; WINGS=0
  AALABEL=""; UIDMAP=""; GIDMAP=""; VIRT="unknown"; VKIND=unknown; CTECH=none; PRIV=n/a; DAEMON_UP=0
  PROBE_HOSTNET=""; PROBE_AAUNCONF=""
  [[ $TTY == 1 ]] && printf '\e[2J\e[H'
  logo
  [[ $MODE == diagnose ]] && note "Diagnose mode: no packages, configuration or services will be changed."
  stage_system
  stage_virtualization
  stage_security
  stage_packages
  stage_install
  stage_daemon
  stage_tests
  stage_repair
  stage_final
  (( SHOW_REPORT )) && { printf '\n'; cat "$REPORT"; }
  log "VERDICT: $VERDICT"
  exit "$CODE"
}

[[ ${NYLIX_LIB_ONLY:-0} == 1 ]] || main
