#!/usr/bin/env bash
###############################################################################
#  TuxWall unified installer
#  ---------------------------------------------------------------------------
#  One script for every way of installing TuxWall. It replaces setup.sh,
#  install.sh + stage.sh (first-boot wizard), install-repo.sh and the manual
#  .deb steps.
#
#    sudo bash tuxwall-install.sh               guided install (recommended)
#    sudo bash tuxwall-install.sh --dry-run     show the plan, change nothing
#    sudo bash tuxwall-install.sh --console     run the guided install on the
#                                               next console login (headless /
#                                               fresh appliance installs)
#    sudo bash tuxwall-install.sh --help        every option
#
#  Install sources:
#    local  build a package from this folder and install it (test your changes)
#    apt    the signed TuxWall APT repository (latest release)
#    deb    a tuxwall_*.deb file you already have
#
#  Roles:
#    gateway    TuxWall routes the network: WAN/LAN, DHCP, DNS, IPv6 RA, NAT
#    dashboard  install TuxWall but leave this machine's network config alone
#
#  Every path goes through the same .deb (maintainer scripts included), so a
#  source install and an APT install end up identical. Safe to re-run.
#  Full log: /var/log/tuxwall-install.log
###############################################################################
set -Eeuo pipefail
umask 022

INSTALLER_VERSION="1.0.0"
SELF="$(readlink -f "${BASH_SOURCE[0]}")"
REPO_DIR="$(dirname "$SELF")"
# The canonical location is the repository root. If someone runs an
# older checkout where the script sits in scripts/, climb one level so
# --source local works from both layouts.
if [[ "$(basename "$REPO_DIR")" == "scripts" && -f "$REPO_DIR/../pkg/DEBIAN/control" ]]; then
    REPO_DIR="$(dirname "$REPO_DIR")"
fi

LOG=/var/log/tuxwall-install.log
LOCK=/run/tuxwall-install.lock
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP_DIR="/var/backups/tuxwall-install/$STAMP"
PROFILE_JSON=/etc/tuxwall/install-profile.json
MARKER=/etc/tuxwall/.appliance-configured
PENDING=/etc/tuxwall/.console-setup-pending
APPLIANCE_DIR=/opt/tuxwall-appliance
CONSOLE_HOOK=/etc/profile.d/zz-tuxwall-console-setup.sh
INSTALLER_MARK="Generated by the TuxWall installer"
KEA_EDIT_MARK="Edited from the TuxWall dashboard"   # = kea_conf.EDIT_MARK
KEA_LEASE_CMDS_LIB=/usr/lib/x86_64-linux-gnu/kea/hooks/libdhcp_lease_cmds.so   # = pkg/DEBIAN/postinst

APT_REPO_URL="https://rezzonance.github.io/tuxwall"
APT_KEYRING=/usr/share/keyrings/tuxwall.gpg
APT_LIST=/etc/apt/sources.list.d/tuxwall.list
APT_KEY_FPR="5D79B9082DCAEB9CCB731382F5D8235716BDBDD1"

export DEBIAN_FRONTEND=noninteractive
export NEEDRESTART_MODE=a NEEDRESTART_SUSPEND=1
APT_OPTS=(-y -q --no-install-recommends
          -o DPkg::Lock::Timeout=600
          -o Dpkg::Options::=--force-confdef
          -o Dpkg::Options::=--force-confold)

# ── Options (defaults; most are asked interactively) ─────────────────────────
SOURCE=""            # local | apt | deb
DEB_FILE=""
ROLE=""              # gateway | dashboard
WAN="" LAN=""
WAN_MODE=""          # keep | dhcp
LAN_SUBNET=""        # e.g. 192.168.1.1/24 (host part = gateway address)
DOMAIN=""
WITH_CROWDSEC=1 WITH_AGENT=1 WITH_SPEEDTEST=1 WITH_GEOIP=1 WITH_APT_REPO=1
ASSUME_YES=0 DRY_RUN=0 CONSOLE_STAGE=0 FROM_CONSOLE=0 DISABLE_MULTIPATH=0
AGENT_EDIT_WEBROOT=0 FORCE_NET=0 SSH_WAN=0
APPLY_NET="auto"     # auto | now | reboot

# ── Derived state ───────────────────────────────────────────────────────────
INTERACTIVE=0
WARNINGS=()
PHYS_IFACES=()
DEF_IF=""
SSH_CONN="" SSH_CLIENT_IP="" SSH_SERVER_IP="" SSH_SERVER_PORT="" SSH_IFACE=""
SSH_PORTS=()
SSH_SCOPE=""         # lan | wan (gateway: LAN + rate-limited WAN, --ssh-wan) | any (dashboard role)
SSH_EXTRA_IFACE=""   # gateway: the non-LAN, non-WAN interface of the installer's SSH session
NET_CIDR="" NET_GW="" NET_MASK="" NET_PREFIX="" NET_POOL_LO="" NET_POOL_HI=""
ULA=""
KEA_ACTION="" RADVD_ACTION="" UNBOUND_ACTION=""
NET_APPLY_DECISION="" NET_APPLY_REASON=""
PKG_VERSION=""
CRIT_FAIL=0
STEP_N=0 STEP_TOTAL=0

# ── Terminal styling ────────────────────────────────────────────────────────
if [[ -t 1 && -z "${NO_COLOR:-}" ]]; then
    C_R=$'\e[31m' C_G=$'\e[32m' C_Y=$'\e[33m' C_B=$'\e[34m' C_C=$'\e[36m'
    C_BOLD=$'\e[1m' C_DIM=$'\e[2m' C_0=$'\e[0m'
else
    C_R="" C_G="" C_Y="" C_B="" C_C="" C_BOLD="" C_DIM="" C_0=""
fi

log()   { [[ -w "$LOG" ]] && printf '%s %s\n' "$(date '+%F %T')" "$*" >>"$LOG" || true; }
ok()    { printf '  %s✓%s %s\n' "$C_G" "$C_0" "$*"; log "OK   $*"; }
info()  { printf '  %s•%s %s\n' "$C_DIM" "$C_0" "$*"; log "INFO $*"; }
warn()  { printf '  %s!%s %s\n' "$C_Y" "$C_0" "$*"; log "WARN $*"; WARNINGS+=("$*"); }
note()  { printf '    %s%s%s\n' "$C_DIM" "$*" "$C_0"; log "     $*"; }
die()   {
    printf '\n  %s✗ %s%s\n' "$C_R" "$*" "$C_0" >&2
    log "FATAL $*"
    if [[ -s "$LOG" && -r "$LOG" && $EUID -eq 0 ]]; then
        printf '\n  %sLast lines of %s:%s\n' "$C_DIM" "$LOG" "$C_0" >&2
        tail -n 15 "$LOG" | sed 's/^/    │ /' >&2
    fi
    exit 1
}
hr()    { printf '  %s%s%s\n' "$C_DIM" "────────────────────────────────────────────────────────────────" "$C_0"; }
kv()    { printf '  %s%-15s%s %s\n' "$C_DIM" "$1" "$C_0" "$2"; }

step() {
    STEP_N=$((STEP_N + 1))
    printf '\n%s[%2d/%d]%s %s%s%s\n' "$C_C" "$STEP_N" "$STEP_TOTAL" "$C_0" "$C_BOLD" "$*" "$C_0"
    log "===== [$STEP_N/$STEP_TOTAL] $*"
}

# Run a command with its output going to the log only.
q() { "$@" >>"$LOG" 2>&1; }

# Run a long command with a spinner and elapsed time; output goes to the log.
# TERM=dumb NO_COLOR=1: the output is a log file, and apt hands maintainer
# scripts a pty with our TERM. On a serial console (TERM=vt220, no colours)
# CrowdSec's bouncer postinst (set -e; FG_RED=$(tput setaf 1)) dies silently
# with exit 1, which left dpkg broken for every later apt-get.
run_long() {
    local msg="$1"; shift
    log "RUN  $*"
    if [[ ! -t 1 ]]; then
        TERM=dumb NO_COLOR=1 "$@" >>"$LOG" 2>&1
        return
    fi
    ( trap - ERR; TERM=dumb NO_COLOR=1 "$@" ) >>"$LOG" 2>&1 &
    # shellcheck disable=SC1003
    local pid=$! i=0 rc=0 start=$SECONDS frames='|/-\' every=1 tty
    # Braille frames only on a UTF-8 terminal emulator: the Linux text console
    # font (TERM=linux) and serial terminals (vt*) show them as '0'.
    if [[ "${LC_ALL:-${LC_CTYPE:-${LANG:-}}}" =~ [Uu][Tt][Ff]-?8 ]]; then
        case "${TERM:-dumb}" in
            linux|vt*|dumb|ansi|cons*) ;;
            *) frames='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' ;;
        esac
    fi
    # Serial console (first-boot wizard on ttyS0): a spinner frame every
    # 0.15 s floods the line and console logs - redraw every ~10 s instead.
    tty="$(readlink "/proc/$$/fd/1" 2>/dev/null || true)"
    if [[ $tty == /dev/ttyS* || $tty == /dev/ttyAMA* || $tty == /dev/ttyUSB* || $tty == /dev/hvc* ]]; then
        frames='.' every=67
    fi
    while kill -0 "$pid" 2>/dev/null; do
        if (( i % every == 0 )); then
            printf '\r  %s%s%s %s %s(%ss)%s' "$C_C" "${frames:i/every%${#frames}:1}" "$C_0" "$msg" "$C_DIM" "$((SECONDS - start))" "$C_0"
        fi
        i=$((i + 1))
        sleep 0.15
    done
    wait "$pid" || rc=$?
    printf '\r\033[K'
    return "$rc"
}

on_err() {
    local rc=$? line=$1 cmd=$2
    trap - ERR
    log "ERROR rc=$rc line=$line cmd=$cmd"
    die "Step failed (line $line, exit $rc): $cmd"
}
trap 'on_err $LINENO "$BASH_COMMAND"' ERR

ask() {   # ask VAR "prompt"
    local __v=$1 __p=$2 __a=""
    read -r -p "$__p " __a </dev/tty || __a=""
    printf -v "$__v" '%s' "$__a"
}

confirm() {   # confirm "question" default(y|n)
    local q=$1 def=${2:-n} a
    if (( ! INTERACTIVE )); then [[ $def == y ]]; return; fi
    local hint="[y/N]"; [[ $def == y ]] && hint="[Y/n]"
    ask a "  $q $hint"
    a=${a:-$def}
    [[ $a =~ ^[yY] ]]
}

user_abort() { printf '\n  %sInstallation cancelled. Nothing was changed.%s\n\n' "$C_DIM" "$C_0"; exit 0; }

menu() {   # menu VAR "title" default "label|description" ...
    local __var=$1 title=$2 def=$3; shift 3
    local n=$# i=1 o label desc mark ans
    printf '\n  %s%s%s\n' "$C_BOLD" "$title" "$C_0"
    for o in "$@"; do
        label=${o%%|*}; desc=${o#*|}
        mark=" "; [[ $i == "$def" ]] && mark="${C_G}›${C_0}"
        printf '  %s %s%d)%s %-28s %s%s%s\n' "$mark" "$C_C" "$i" "$C_0" "$label" "$C_DIM" "$desc" "$C_0"
        i=$((i + 1))
    done
    while true; do
        ask ans "    Choose 1-$n (Enter = $def, q = quit):"
        ans=${ans:-$def}
        [[ $ans =~ ^[qQ]$ ]] && user_abort
        if [[ $ans =~ ^[0-9]+$ ]] && (( ans >= 1 && ans <= n )); then
            printf -v "$__var" '%s' "$ans"
            return 0
        fi
        printf '    %sEnter a number between 1 and %d.%s\n' "$C_Y" "$n" "$C_0"
    done
}

banner() {
    printf '%s' "$C_C"
    cat <<'BANNER'

   ______          _       __      ____
  /_  __/_  ___  _| |     / /___ _/ / /
   / / / / / / |/_/ | /| / / __ `/ / /
  / / / /_/ />  < | |/ |/ / /_/ / / /
 /_/  \__,_/_/|_| |__/|__/\__,_/_/_/
BANNER
    printf '%s' "$C_0"
    printf '  %sOpen-source Linux firewall & router%s  ·  installer %s\n' "$C_DIM" "$C_0" "$INSTALLER_VERSION"
}

usage() {
    cat <<EOF
TuxWall unified installer $INSTALLER_VERSION

Usage: sudo bash tuxwall-install.sh [options]

With no options the installer asks a few questions, shows a review screen
and only then changes anything.

Source:
  --source local|apt|deb   Where TuxWall comes from (default: local when run
                           from a source checkout, otherwise apt)
  --deb FILE               Install this .deb (implies --source deb)

Role and network:
  --role gateway|dashboard Route the network, or dashboard only
  --wan IFACE              WAN (internet) interface
  --lan IFACE              LAN (internal) interface
  --wan-mode keep|dhcp     Keep the WAN's current config, or use DHCP
  --subnet CIDR            LAN network; the host part is the gateway address
                           (e.g. 192.168.1.1/24)
  --domain NAME            Local DNS domain (default home.arpa)
  --replace-configs        Overwrite existing Kea / radvd / Unbound configs
                           (a backup is kept under /var/backups/tuxwall-install)
  --apply-network now|reboot|auto
                           When to activate the LAN config (default auto:
                           deferred to a reboot if it would cut your session)
  --ssh-wan                Gateway: also allow SSH on the WAN (rate-limited).
                           Default: SSH from the LAN only (plus the VPN once
                           WireGuard is set up); an SSH session over the WAN
                           stays open, new logins must come from the LAN.

Components (all on by default):
  --no-crowdsec  --no-agent  --no-speedtest  --no-geoip  --no-apt-repo

Security:
  --agent-edit-webroot     Let the AI agent write to /var/www/html (legacy
                           behaviour; by default the web root is root-owned)

Modes:
  --dry-run                Detect, ask, show the plan; change nothing
  --console                Run the guided install on the next console login
                           (tty1, or the serial console if the kernel uses one)
  --disable-multipath      With --console: stop multipathd from claiming the
                           system disk (Launchpad #2120444)
  -y, --yes                Accept defaults, no questions (needs --wan/--lan
                           for a gateway unless they are unambiguous)
  -h, --help               This help
EOF
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --source)            SOURCE="${2:-}"; shift 2 ;;
            --deb)               DEB_FILE="${2:-}"; SOURCE=deb; shift 2 ;;
            --role)              ROLE="${2:-}"; shift 2 ;;
            --wan)               WAN="${2:-}"; shift 2 ;;
            --lan)               LAN="${2:-}"; shift 2 ;;
            --wan-mode)          WAN_MODE="${2:-}"; shift 2 ;;
            --subnet)            LAN_SUBNET="${2:-}"; shift 2 ;;
            --domain)            DOMAIN="${2:-}"; shift 2 ;;
            --replace-configs)   FORCE_NET=1; shift ;;
            --apply-network)     APPLY_NET="${2:-}"; shift 2 ;;
            --ssh-wan)           SSH_WAN=1; shift ;;
            --no-crowdsec)       WITH_CROWDSEC=0; shift ;;
            --no-agent)          WITH_AGENT=0; shift ;;
            --no-speedtest)      WITH_SPEEDTEST=0; shift ;;
            --no-geoip)          WITH_GEOIP=0; shift ;;
            --no-apt-repo)       WITH_APT_REPO=0; shift ;;
            --agent-edit-webroot) AGENT_EDIT_WEBROOT=1; shift ;;
            --dry-run)           DRY_RUN=1; shift ;;
            --console)           CONSOLE_STAGE=1; shift ;;
            --from-console)      FROM_CONSOLE=1; shift ;;
            --disable-multipath) DISABLE_MULTIPATH=1; shift ;;
            -y|--yes)            ASSUME_YES=1; shift ;;
            -h|--help)           usage; exit 0 ;;
            *)                   usage >&2; printf '\nUnknown option: %s\n' "$1" >&2; exit 1 ;;
        esac
    done
    case "$SOURCE" in ""|local|apt|deb) ;; *) die "--source must be local, apt or deb" ;; esac
    case "$ROLE" in ""|gateway|dashboard) ;; *) die "--role must be gateway or dashboard" ;; esac
    case "$WAN_MODE" in ""|keep|dhcp) ;; *) die "--wan-mode must be keep or dhcp" ;; esac
    case "$APPLY_NET" in auto|now|reboot) ;; *) die "--apply-network must be now, reboot or auto" ;; esac
}

###############################################################################
#  Detection helpers
###############################################################################
have_repo()  { [[ -f "$REPO_DIR/pkg/DEBIAN/control" && -f "$REPO_DIR/www/index.html" ]]; }
repo_version() { sed -n 's/^Version: //p' "$REPO_DIR/pkg/DEBIAN/control" 2>/dev/null | head -n1 || true; }

detect_phys_ifaces() {
    PHYS_IFACES=()
    local p n
    for p in /sys/class/net/*; do
        n=${p##*/}
        [[ $n == lo ]] && continue
        [[ -e "$p/device" ]] || continue          # physical / virtio NICs only
        [[ -d "$p/bridge" || -d "$p/bonding" ]] && continue
        PHYS_IFACES+=("$n")
    done
    DEF_IF="$(ip -4 route show default 2>/dev/null | awk '{for (i=1;i<NF;i++) if ($i=="dev") {print $(i+1); exit}}' || true)"
}

iface_v4()   { { ip -4 -o addr show dev "$1" scope global 2>/dev/null || true; } | awk '{print $4}' | paste -sd' ' -; }
iface_mac()  { cat "/sys/class/net/$1/address" 2>/dev/null || true; }
iface_link() {
    local c; c="$(cat "/sys/class/net/$1/carrier" 2>/dev/null || echo 0)"
    [[ $c == 1 ]] && echo "link up" || echo "no link"
}
iface_wireless() { [[ -d "/sys/class/net/$1/wireless" || -e "/sys/class/net/$1/phy80211" ]]; }
iface_exists()   { [[ -e "/sys/class/net/$1" ]]; }

# Networks of every interface except $1 (used for overlap checks).
other_networks() {
    { ip -4 -o addr show scope global 2>/dev/null || true; } | awk -v skip="$1" '$2 != skip {print $4}'
}

detect_ssh() {
    local c="${SSH_CONNECTION:-}" pid=$$ parent
    # sudo drops SSH_CONNECTION; recover it from the parent processes.
    while [[ -z $c && $pid -gt 1 ]]; do
        parent="$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ' || true)"
        [[ -n $parent && $parent != "$pid" ]] || break
        pid=$parent
        [[ -r /proc/$pid/environ ]] || continue
        c="$( { tr '\0' '\n' <"/proc/$pid/environ"; } 2>/dev/null | sed -n 's/^SSH_CONNECTION=//p' | head -n1 || true)"
    done
    SSH_CONN="$c"
    [[ -n $c ]] || return 0
    read -r SSH_CLIENT_IP _ SSH_SERVER_IP SSH_SERVER_PORT <<<"$c"
    log "ssh session from $SSH_CLIENT_IP to $SSH_SERVER_IP:$SSH_SERVER_PORT"
    SSH_IFACE="$(ip -o addr show 2>/dev/null | awk -v ip="$SSH_SERVER_IP" '{split($4,a,"/"); if (a[1]==ip) {print $2; exit}}' || true)"
}

detect_ssh_ports() {
    SSH_PORTS=()
    local p
    if command -v sshd >/dev/null 2>&1 || [[ -x /usr/sbin/sshd ]]; then
        while read -r p; do
            [[ $p =~ ^[0-9]+$ ]] && SSH_PORTS+=("$p")
        done < <({ /usr/sbin/sshd -T 2>/dev/null || true; } | awk '$1=="port"{print $2}' | sort -un)
        (( ${#SSH_PORTS[@]} )) || SSH_PORTS=(22)
    fi
    if [[ -n $SSH_SERVER_PORT ]] && ! printf '%s\n' "${SSH_PORTS[@]}" | grep -qx "$SSH_SERVER_PORT"; then
        SSH_PORTS+=("$SSH_SERVER_PORT")
    fi
}

# net_calc CIDR [avoid-cidr ...] -> "OK|net|gw|mask|prefix|pool_lo|pool_hi" or "ERR|reason"
net_calc() {
    python3 - "$@" <<'PY'
import ipaddress, sys
raw = sys.argv[1].strip()
avoid = [a for a in sys.argv[2:] if a]
try:
    iface = ipaddress.ip_interface(raw if "/" in raw else raw + "/24")
except ValueError:
    print("ERR|not a valid IPv4 network (example: 192.168.1.1/24)"); sys.exit()
net = iface.network
if net.version != 4:
    print("ERR|use an IPv4 network for the LAN (IPv6 is added automatically)"); sys.exit()
if not net.is_private or net.is_loopback or net.is_link_local:
    print("ERR|the LAN must use a private range (10.x, 172.16-31.x or 192.168.x)"); sys.exit()
if not 16 <= net.prefixlen <= 29:
    print("ERR|use a prefix between /16 and /29 (a /24 suits most homes)"); sys.exit()
for a in avoid:
    try:
        other = ipaddress.ip_interface(a).network
    except ValueError:
        continue
    if net.overlaps(other):
        print("ERR|%s overlaps %s, which is already in use on another interface" % (net, other)); sys.exit()
gw = iface.ip if iface.ip != net.network_address else net.network_address + 1
if gw == net.broadcast_address:
    print("ERR|the gateway address cannot be the broadcast address"); sys.exit()
hosts = net.num_addresses - 2
first, last = net.network_address + 1, net.broadcast_address - 1
if hosts >= 200:
    lo, hi = net.network_address + 100, net.network_address + 199
else:
    lo, hi = first + hosts // 2, last
if lo <= gw <= hi:
    if gw == lo:
        lo += 1
    elif gw == hi:
        hi -= 1
    else:
        print("ERR|gateway %s falls inside the DHCP pool %s-%s; use .1 for the gateway" % (gw, lo, hi)); sys.exit()
print("OK|%s|%s|%s|%d|%s|%s" % (net, gw, net.netmask, net.prefixlen, lo, hi))
PY
}

valid_domain() {
    local d=$1
    [[ ${#d} -le 253 ]] || return 1
    [[ $d =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$ ]] || return 1
    [[ $d != *.local && $d != local ]]
}

gen_ula() {
    local gid
    gid="$(od -An -tx1 -N5 /dev/urandom 2>/dev/null | tr -d ' \n')"
    [[ ${#gid} -eq 10 ]] || gid="$(printf '%010x' "$((RANDOM * RANDOM))")"
    printf 'fd%s:%s:%s' "${gid:0:2}" "${gid:2:4}" "${gid:6:4}"
}

# radvd reads /etc/tuxwall/radvd.conf through a radvd.service drop-in (the
# dashboard's sandbox cannot replace files directly in /etc); boxes without
# the drop-in still use the stock /etc/radvd.conf.
RADVD_CONF=/etc/tuxwall/radvd.conf
RADVD_CONF_LEGACY=/etc/radvd.conf
RADVD_DROPIN=/etc/systemd/system/radvd.service.d/10-tuxwall.conf
radvd_conf_in_use() { if [[ -e $RADVD_DROPIN ]]; then echo "$RADVD_CONF"; else echo "$RADVD_CONF_LEGACY"; fi; }

existing_ula() {   # reuse the ULA from an existing radvd config
    local f; f="$(radvd_conf_in_use)"
    [[ -f $f ]] || return 0
    sed -nE 's/^[[:space:]]*prefix[[:space:]]+(fd[0-9a-f]{2}:[0-9a-f]{1,4}:[0-9a-f]{1,4})::\/64.*/\1/p' "$f" | head -n1 || true
}

kea_is_replaceable() {
    local f=/etc/kea/kea-dhcp4.conf
    [[ ! -s $f ]] && return 0
    # The dashboard keeps our header on a rewrite and adds KEA_EDIT_MARK:
    # from then on the file holds reservations/DHCP edits - keep it.
    grep -q "$KEA_EDIT_MARK" "$f" && return 1
    grep -q "$INSTALLER_MARK" "$f" && return 0
    grep -q '192\.0\.2\.' "$f" && return 0          # Kea's shipped sample config
    return 1
}
radvd_is_replaceable()   { local f; f="$(radvd_conf_in_use)"; [[ ! -s $f ]] || grep -q "$INSTALLER_MARK" "$f"; }
unbound_is_replaceable() {
    local f=/etc/unbound/unbound.conf.d/router-dns.conf
    [[ ! -s $f ]] || grep -q "$INSTALLER_MARK" "$f"
}

backup_file() {
    [[ -e $1 ]] || return 0
    mkdir -p "$BACKUP_DIR$(dirname "$1")"
    cp -a "$1" "$BACKUP_DIR$1"
    log "backup $1 -> $BACKUP_DIR$1"
}

ufw_has_ssh_rule() {
    local p=$1 added
    added="$(ufw show added 2>/dev/null | grep -E '^ufw (allow|limit)' || true)"
    grep -Eq "(^|[[:space:]])${p}(/tcp)?([[:space:]]|$)|port ${p}([[:space:]]|$)" <<<"$added" && return 0
    [[ $p == 22 ]] && grep -qi 'openssh' <<<"$added" && return 0
    return 1
}

wait_dns() {
    local i
    for ((i = 0; i < ${1:-15}; i++)); do
        getent hosts archive.ubuntu.com >/dev/null 2>&1 && return 0
        sleep 1
    done
    return 1
}

wait_api() {
    local i
    for ((i = 0; i < ${1:-30}; i++)); do
        curl -fsS -m 3 -o /dev/null http://127.0.0.1:8008/api/auth/session 2>/dev/null && return 0
        sleep 1
    done
    return 1
}

###############################################################################
#  Setup: root, log, lock, preflight
###############################################################################
require_root() {
    [[ $EUID -eq 0 ]] || { printf 'Run as root:  sudo bash %s\n' "$0" >&2; exit 1; }
}

init_log() {
    touch "$LOG"; chmod 600 "$LOG"
    {
        printf '\n'
        printf '=%.0s' {1..72}; printf '\n'
        printf '%s  tuxwall-install.sh %s  args: %s\n' "$(date '+%F %T')" "$INSTALLER_VERSION" "${ORIG_ARGS:-}"
    } >>"$LOG"
}

acquire_lock() {
    exec 9>"$LOCK"
    flock -n 9 || die "Another TuxWall installer is already running."
}

preflight() {
    command -v apt-get >/dev/null 2>&1 || die "apt-get not found: TuxWall needs Ubuntu (or Debian)."
    command -v systemctl >/dev/null 2>&1 || die "systemd is required."
    command -v python3 >/dev/null 2>&1 || die "python3 is required (it ships with Ubuntu Server)."

    local id="" ver=""
    if [[ -r /etc/os-release ]]; then
        id="$(. /etc/os-release; echo "${ID:-}")"
        ver="$(. /etc/os-release; echo "${VERSION_ID:-}")"
    fi
    if [[ $id != ubuntu ]]; then
        warn "This is ${id:-an unknown OS}; TuxWall is tested on Ubuntu 24.04 and newer."
    elif [[ ${ver%%.*} -lt 24 ]]; then
        warn "Ubuntu $ver detected; TuxWall needs 24.04 or newer."
    fi

    detect_phys_ifaces
    detect_ssh
    detect_ssh_ports
    (( ${#PHYS_IFACES[@]} )) || warn "No physical network interfaces detected."

    if [[ -t 0 || -r /dev/tty ]] && (( ! ASSUME_YES )) && { : </dev/tty; } 2>/dev/null; then
        INTERACTIVE=1
    fi
}

###############################################################################
#  Questions
###############################################################################
print_iface_table() {   # print_iface_table exclude
    local i=1 n tags v4
    for n in "${PHYS_IFACES[@]}"; do
        [[ $n == "${1:-}" ]] && continue
        tags=""
        [[ $n == "$DEF_IF" ]] && tags+=" ${C_B}[internet route]${C_0}"
        [[ $n == "$SSH_IFACE" ]] && tags+=" ${C_Y}[your SSH session]${C_0}"
        iface_wireless "$n" && tags+=" ${C_DIM}[wireless]${C_0}"
        v4="$(iface_v4 "$n")"
        printf '      %s%d)%s %-12s %s%-17s %-8s %s%s%s\n' "$C_C" "$i" "$C_0" "$n" "$C_DIM" \
            "$(iface_mac "$n")" "$(iface_link "$n")" "${v4:-no IPv4}" "$C_0" "$tags"
        i=$((i + 1))
    done
}

pick_iface() {   # pick_iface VAR "title" exclude default
    local __var=$1 title=$2 excl=$3 def=$4 list=() n ans idx=1 defidx=1
    for n in "${PHYS_IFACES[@]}"; do
        [[ $n == "$excl" ]] && continue
        list+=("$n")
        [[ $n == "$def" ]] && defidx=$idx
        idx=$((idx + 1))
    done
    (( ${#list[@]} )) || die "No interface left to choose for: $title"
    printf '\n  %s%s%s\n' "$C_BOLD" "$title" "$C_0"
    print_iface_table "$excl"
    while true; do
        ask ans "    Choose 1-${#list[@]} (Enter = ${list[$((defidx - 1))]}, q = quit):"
        ans=${ans:-$defidx}
        [[ $ans =~ ^[qQ]$ ]] && user_abort
        if [[ $ans =~ ^[0-9]+$ ]] && (( ans >= 1 && ans <= ${#list[@]} )); then
            printf -v "$__var" '%s' "${list[$((ans - 1))]}"
            return 0
        fi
        printf '    %sEnter a number between 1 and %d.%s\n' "$C_Y" "${#list[@]}" "$C_0"
    done
}

default_lan_subnet() {
    local cur avoid c
    mapfile -t avoid < <(other_networks "$LAN")
    cur="$(iface_v4 "$LAN" | awk '{print $1}')"
    if [[ -n $cur && $(net_calc "$cur" "${avoid[@]}") == OK* ]]; then
        echo "$cur"; return
    fi
    for c in 192.168.1.1/24 192.168.50.1/24 10.20.30.1/24 172.20.0.1/24; do
        if [[ $(net_calc "$c" "${avoid[@]}") == OK* ]]; then echo "$c"; return; fi
    done
    echo "192.168.1.1/24"
}

toggle_components() {
    local ans
    local -a names=("CrowdSec" "AI assistant" "Speedtest" "GeoIP attack map" "APT updates")
    local -a descs=("community threat intelligence and automatic bans"
                    "opencode agent (downloads opencode from opencode.ai)"
                    "Ookla CLI for guided traffic-shaping setup"
                    "DB-IP City Lite database (CC BY 4.0)"
                    "register the signed TuxWall repository for apt upgrade")
    while true; do
        local -a vals=("$WITH_CROWDSEC" "$WITH_AGENT" "$WITH_SPEEDTEST" "$WITH_GEOIP" "$WITH_APT_REPO")
        printf '\n  %sOptional components%s %s(type a number to toggle, Enter to continue)%s\n' "$C_BOLD" "$C_0" "$C_DIM" "$C_0"
        local i box
        for i in 0 1 2 3 4; do
            if [[ $i == 4 && $SOURCE == apt ]]; then continue; fi
            box="${C_DIM}[ ]${C_0}"; [[ ${vals[$i]} == 1 ]] && box="${C_G}[x]${C_0}"
            printf '    %s%d)%s %s %-18s %s%s%s\n' "$C_C" "$((i + 1))" "$C_0" "$box" "${names[$i]}" "$C_DIM" "${descs[$i]}" "$C_0"
        done
        ask ans "    Toggle (1-5) or Enter:"
        case "$ans" in
            "") return 0 ;;
            1) WITH_CROWDSEC=$((1 - WITH_CROWDSEC)) ;;
            2) WITH_AGENT=$((1 - WITH_AGENT)) ;;
            3) WITH_SPEEDTEST=$((1 - WITH_SPEEDTEST)) ;;
            4) WITH_GEOIP=$((1 - WITH_GEOIP)) ;;
            5) WITH_APT_REPO=$((1 - WITH_APT_REPO)) ;;
            q|Q) user_abort ;;
            *) printf '    %sType 1-5, or press Enter.%s\n' "$C_Y" "$C_0" ;;
        esac
    done
}

gather_config() {
    local c ans r avoid=()

    # ── Source ───────────────────────────────────────────────────────────────
    if [[ -z $SOURCE ]]; then
        local def=2; have_repo && def=1
        if (( INTERACTIVE )); then
            local local_desc="this folder is not a TuxWall source checkout"
            have_repo && local_desc="build $(repo_version) from $REPO_DIR"
            menu c "Where should TuxWall come from?" "$def" \
                "This folder (source)|$local_desc" \
                "Official APT repository|signed, latest release" \
                "A .deb file|a tuxwall_*.deb you already have"
            case "$c" in 1) SOURCE=local ;; 2) SOURCE=apt ;; 3) SOURCE=deb ;; esac
        else
            SOURCE=apt; have_repo && SOURCE=local
        fi
    fi
    if [[ $SOURCE == local ]] && ! have_repo; then
        die "--source local needs the TuxWall source tree next to this script ($REPO_DIR)."
    fi
    if [[ $SOURCE == deb && -z $DEB_FILE ]]; then
        local found; found="$(find "$REPO_DIR" -maxdepth 1 -name 'tuxwall*_all.deb' 2>/dev/null | sort -V | tail -n1)"
        if (( INTERACTIVE )); then
            ask DEB_FILE "    Path to the .deb${found:+ (Enter = $found)}:"
            DEB_FILE=${DEB_FILE:-$found}
        else
            DEB_FILE=$found
        fi
    fi
    if [[ $SOURCE == deb ]]; then
        [[ -f $DEB_FILE ]] || die "Package file not found: ${DEB_FILE:-<none given>}"
        DEB_FILE="$(readlink -f "$DEB_FILE")"
        [[ "$(dpkg-deb -f "$DEB_FILE" Package 2>/dev/null || true)" == tuxwall ]] || die "$DEB_FILE is not a tuxwall package."
    fi

    # ── Role ─────────────────────────────────────────────────────────────────
    if [[ -z $ROLE ]]; then
        local rdef=1; (( ${#PHYS_IFACES[@]} < 2 )) && rdef=2
        if (( INTERACTIVE )); then
            (( ${#PHYS_IFACES[@]} < 2 )) && note "Only ${#PHYS_IFACES[@]} network interface found; a gateway needs two (WAN + LAN)."
            menu c "How will this machine be used?" "$rdef" \
                "Full gateway|TuxWall routes your network: WAN/LAN, DHCP, DNS, NAT" \
                "Dashboard only|don't set up WAN/LAN, DHCP or DNS on this machine"
            [[ $c == 1 ]] && ROLE=gateway || ROLE=dashboard
        else
            [[ $rdef == 1 ]] && ROLE=gateway || ROLE=dashboard
        fi
    fi

    if [[ $ROLE == gateway ]]; then
        (( ${#PHYS_IFACES[@]} >= 2 )) || warn "Gateway mode with fewer than two physical interfaces: double-check the WAN/LAN choice."

        # WAN
        if [[ -z $WAN ]]; then
            local wdef="${DEF_IF:-${PHYS_IFACES[0]:-}}"
            if (( INTERACTIVE )); then
                pick_iface WAN "Which interface faces the internet (WAN)?" "" "$wdef"
            else
                [[ -n $wdef ]] || die "Cannot detect the WAN interface; pass --wan."
                WAN=$wdef
            fi
        fi
        iface_exists "$WAN" || die "Interface not found: $WAN"

        # WAN mode
        if [[ -z $WAN_MODE ]]; then
            if [[ -n "$(iface_v4 "$WAN")" ]] || iface_wireless "$WAN"; then WAN_MODE=keep; else WAN_MODE=dhcp; fi
            if (( INTERACTIVE )) && [[ $WAN_MODE == keep ]] && ! iface_wireless "$WAN"; then
                menu c "WAN addressing ($WAN currently has $(iface_v4 "$WAN"))" 1 \
                    "Keep current config|leave $WAN exactly as it is (recommended)" \
                    "DHCP from the ISP|let TuxWall configure $WAN for DHCP v4 + v6"
                [[ $c == 1 ]] && WAN_MODE=keep || WAN_MODE=dhcp
            fi
        fi
        if [[ $WAN_MODE == dhcp ]] && iface_wireless "$WAN"; then
            warn "$WAN is wireless; leaving its configuration as it is."
            WAN_MODE=keep
        fi

        # LAN
        if [[ -z $LAN ]]; then
            local ldef="" n
            for n in "${PHYS_IFACES[@]}"; do
                [[ $n == "$WAN" ]] && continue
                [[ -z $ldef ]] && ldef=$n
                [[ "$(iface_link "$n")" == "link up" ]] && { ldef=$n; break; }
            done
            if (( INTERACTIVE )); then
                pick_iface LAN "Which interface connects to your local network (LAN)?" "$WAN" "$ldef"
            else
                local others=0
                for n in "${PHYS_IFACES[@]}"; do [[ $n != "$WAN" ]] && others=$((others + 1)); done
                (( others == 1 )) || die "Several LAN candidates; pass --lan IFACE."
                LAN=$ldef
            fi
        fi
        iface_exists "$LAN" || die "Interface not found: $LAN"
        [[ $LAN != "$WAN" ]] || die "WAN and LAN must be different interfaces."
        iface_wireless "$LAN" && die "$LAN is a wireless interface; the LAN must be wired (use an access point)."

        # LAN subnet
        mapfile -t avoid < <(other_networks "$LAN")
        [[ -n $LAN_SUBNET ]] || LAN_SUBNET="$(default_lan_subnet)"
        while true; do
            if (( INTERACTIVE )); then
                printf '\n  %sLAN network%s %s(the address you type becomes the gateway)%s\n' "$C_BOLD" "$C_0" "$C_DIM" "$C_0"
                ask ans "    LAN address/prefix (Enter = $LAN_SUBNET):"
                [[ $ans =~ ^[qQ]$ ]] && user_abort
                [[ -n $ans ]] && LAN_SUBNET=$ans
            fi
            r="$(net_calc "$LAN_SUBNET" "${avoid[@]}")"
            if [[ $r == OK* ]]; then
                IFS='|' read -r _ NET_CIDR NET_GW NET_MASK NET_PREFIX NET_POOL_LO NET_POOL_HI <<<"$r"
                break
            fi
            (( INTERACTIVE )) || die "LAN network $LAN_SUBNET: ${r#ERR|}"
            printf '    %s%s%s\n' "$C_Y" "${r#ERR|}" "$C_0"
            LAN_SUBNET="$(default_lan_subnet)"
        done

        # Domain
        DOMAIN=${DOMAIN:-home.arpa}
        while true; do
            if (( INTERACTIVE )); then
                ask ans "    Local DNS domain (Enter = $DOMAIN):"
                [[ $ans =~ ^[qQ]$ ]] && user_abort
                [[ -n $ans ]] && DOMAIN="${ans,,}"
            fi
            DOMAIN="${DOMAIN%.}"
            valid_domain "$DOMAIN" && break
            (( INTERACTIVE )) || die "Invalid domain: $DOMAIN"
            printf '    %sUse at least two labels, e.g. home.arpa or lan.example.com (not .local).%s\n' "$C_Y" "$C_0"
            DOMAIN=home.arpa
        done

        ULA="$(existing_ula)"; [[ -n $ULA ]] || ULA="$(gen_ula)"

        # Existing service configs
        if kea_is_replaceable; then KEA_ACTION="write"
        elif (( FORCE_NET )); then KEA_ACTION=replace
        elif (( INTERACTIVE )) && confirm "/etc/kea/kea-dhcp4.conf is already customised. Replace it (a backup is kept)?" n; then KEA_ACTION=replace
        else KEA_ACTION=keep; fi

        if radvd_is_replaceable; then RADVD_ACTION="write"
        elif (( FORCE_NET )); then RADVD_ACTION=replace
        else RADVD_ACTION=keep; fi

        if unbound_is_replaceable; then UNBOUND_ACTION="write"
        elif (( FORCE_NET )); then UNBOUND_ACTION=replace
        else UNBOUND_ACTION=keep; fi

        # SSH: from the LAN only (WireGuard setup adds the VPN), never on the
        # WAN unless --ssh-wan. A session over another (management)
        # interface keeps that interface. The current session survives any
        # choice (established connections stay allowed).
        SSH_SCOPE=lan SSH_EXTRA_IFACE=""
        if (( SSH_WAN )); then
            SSH_SCOPE=wan
        elif [[ -n $SSH_IFACE && $SSH_IFACE == "$WAN" ]]; then
            if (( INTERACTIVE )) && confirm "You are connected through the WAN ($WAN). Keep SSH reachable on the WAN too (rate-limited; Firewall → Findings flags it)?" n; then
                SSH_SCOPE=wan
            fi
        elif [[ -n $SSH_IFACE && $SSH_IFACE != "$LAN" && $SSH_IFACE != lo ]]; then
            SSH_EXTRA_IFACE=$SSH_IFACE
        fi

        decide_network_apply
    else
        SSH_SCOPE=any
        [[ -n $DOMAIN ]] || DOMAIN=home.arpa
    fi

    [[ $SOURCE == apt ]] && WITH_APT_REPO=1
    (( INTERACTIVE )) && toggle_components
    return 0
}

decide_network_apply() {
    local cur_lan_ips
    cur_lan_ips="$(iface_v4 "$LAN")"
    case "$APPLY_NET" in
        now)    NET_APPLY_DECISION=now; NET_APPLY_REASON="requested with --apply-network now" ;;
        reboot) NET_APPLY_DECISION=reboot; NET_APPLY_REASON="requested with --apply-network reboot" ;;
        auto)
            if (( FROM_CONSOLE )) || [[ -z $SSH_CONN ]]; then
                NET_APPLY_DECISION=now; NET_APPLY_REASON="no SSH session to protect"
            elif [[ $SSH_IFACE == "$LAN" && " $cur_lan_ips " != *" $NET_GW/"* ]]; then
                NET_APPLY_DECISION=reboot
                NET_APPLY_REASON="your SSH session uses $LAN, whose address will change to $NET_GW"
            elif [[ $SSH_IFACE == "$WAN" && $WAN_MODE == dhcp ]]; then
                NET_APPLY_DECISION=reboot
                NET_APPLY_REASON="your SSH session uses $WAN, which is being switched to DHCP"
            else
                NET_APPLY_DECISION=now; NET_APPLY_REASON="your SSH session is not affected"
            fi ;;
    esac
}

###############################################################################
#  Review screen
###############################################################################
yesno() { [[ $1 == 1 ]] && printf '%s✓%s' "$C_G" "$C_0" || printf '%s–%s' "$C_DIM" "$C_0"; }

review() {
    local src
    case "$SOURCE" in
        local) src="this folder → builds tuxwall $(repo_version)+src" ;;
        apt)   src="official APT repository (signature checked: ${APT_KEY_FPR: -16})" ;;
        deb)   src="$DEB_FILE ($(dpkg-deb -f "$DEB_FILE" Version 2>/dev/null || true))" ;;
    esac
    printf '\n  %sReview%s\n' "$C_BOLD" "$C_0"
    hr
    kv "Source"  "$src"
    if [[ $ROLE == gateway ]]; then
        kv "Role"        "full gateway"
        if [[ $WAN_MODE == keep ]]; then
            kv "WAN"     "$WAN  keep current config ($(iface_v4 "$WAN" || true))"
        else
            kv "WAN"     "$WAN  DHCP v4 + v6 from the ISP"
        fi
        kv "LAN"         "$LAN  $NET_GW/$NET_PREFIX  (network $NET_CIDR, mask $NET_MASK)"
        kv "DHCP pool"   "$NET_POOL_LO – $NET_POOL_HI   [Kea: $KEA_ACTION]"
        kv "IPv6 (ULA)"  "$ULA::/64 on $LAN, advertised by radvd   [radvd: $RADVD_ACTION]"
        kv "DNS"         "Unbound for the LAN, gateway.$DOMAIN → $NET_GW   [resolver: $UNBOUND_ACTION]"
        kv "Firewall"    "default deny in, LAN → gateway allowed, LAN → WAN routed + NAT"
        if [[ $SSH_SCOPE == wan ]]; then
            kv "SSH"     "port ${SSH_PORTS[*]:-none} allowed from the LAN and ${C_Y}on the WAN ($WAN, rate-limited)${C_0}"
        else
            kv "SSH"     "port ${SSH_PORTS[*]:-none} allowed from the LAN${SSH_EXTRA_IFACE:+ and $SSH_EXTRA_IFACE (your session)} only, never the WAN"
            if [[ -n $SSH_IFACE && $SSH_IFACE == "$WAN" ]]; then
                kv ""    "${C_Y}you are connected via the WAN: this session stays open, new logins only from the LAN (--ssh-wan keeps the WAN)${C_0}"
            fi
        fi
        kv "WireGuard"   "51820/udp opens on the WAN only once you set WireGuard up (VPN page)"
        if [[ $NET_APPLY_DECISION == now ]]; then
            kv "Activate"    "LAN config applied during the install ($NET_APPLY_REASON)"
        else
            kv "Activate"    "${C_Y}after a reboot${C_0}: $NET_APPLY_REASON"
        fi
    else
        kv "Role"        "dashboard only (no WAN/LAN, DHCP or DNS setup by the installer)"
        kv "Firewall"    "SSH (${SSH_PORTS[*]:-none}) + dashboard from private networks; default deny in"
    fi
    kv "Components"  "CrowdSec $(yesno $WITH_CROWDSEC)  AI agent $(yesno $WITH_AGENT)  Speedtest $(yesno $WITH_SPEEDTEST)  GeoIP $(yesno $WITH_GEOIP)  APT updates $(yesno $WITH_APT_REPO)"
    kv "Web root"    "$( (( AGENT_EDIT_WEBROOT )) && echo 'writable by the AI agent (legacy)' || echo 'root-owned, read-only to every other user')"
    kv "Backups"     "$BACKUP_DIR"
    kv "Log"         "$LOG"
    hr

    if [[ $ROLE == gateway ]]; then
        [[ $KEA_ACTION == keep ]] && warn "Keeping your Kea config: its subnet must match $NET_CIDR for DHCP to work."
    fi
    return 0
}

build_steps() {
    STEPS=()
    STEPS+=("step_packages|Install system packages")
    (( WITH_CROWDSEC )) && STEPS+=("step_crowdsec|Install CrowdSec")
    STEPS+=("step_firewall|Firewall baseline (UFW)")
    if [[ $ROLE == gateway ]]; then
        STEPS+=("step_gateway_config|Gateway configuration (netplan, Kea, radvd, Unbound)")
        STEPS+=("step_dns|Point this gateway's DNS at Unbound")
    fi
    STEPS+=("step_package|Install the TuxWall package")
    STEPS+=("step_post|Configure TuxWall")
    (( WITH_AGENT )) && STEPS+=("step_agent|AI assistant (opencode agent)")
    STEPS+=("step_harden|Lock down dashboard files and secrets")
    (( WITH_SPEEDTEST || WITH_GEOIP )) && STEPS+=("step_extras|Speedtest and GeoIP map")
    (( WITH_APT_REPO )) && [[ $SOURCE != apt ]] && STEPS+=("step_updates|Register the TuxWall update repository")
    [[ $ROLE == gateway ]] && STEPS+=("step_network_apply|Activate the network configuration")
    STEPS+=("step_services|Start services")
    STEPS+=("step_verify|Health check")
    STEP_TOTAL=${#STEPS[@]}
}

###############################################################################
#  Steps
###############################################################################
step_packages() {
    local pkgs=(ufw iptables nftables iproute2 kea-dhcp4-server kea-common
                unbound unbound-anchor dns-root-data radvd wireguard-tools
                avahi-daemon suricata suricata-update aide nginx python3 curl
                jq gzip ieee-data rsync gnupg ca-certificates)
    (( WITH_GEOIP )) && pkgs+=(python3-maxminddb)
    run_long "Refreshing package lists" apt-get update -q || die "apt-get update failed: check the internet connection."
    run_long "Installing ${#pkgs[@]} packages (this can take a few minutes)" \
        apt-get install "${APT_OPTS[@]}" "${pkgs[@]}" || die "Package installation failed."
    ok "System packages installed"
}

step_crowdsec() {
    if command -v cscli >/dev/null 2>&1; then
        ok "CrowdSec already installed"
        return 0
    fi
    local key=/usr/share/keyrings/crowdsec-archive-keyring.gpg cs_list=/etc/apt/sources.list.d/crowdsec.list got=0 _try
    if ! grep -rqs "packagecloud.io/crowdsec" /etc/apt/sources.list /etc/apt/sources.list.d/; then
        for _try in 1 2 3; do
            if curl -fsSL -m 60 https://packagecloud.io/crowdsec/crowdsec/gpgkey 2>>"$LOG" \
                   | gpg --batch --yes --dearmor -o "$key" 2>>"$LOG" && [[ -s $key ]]; then
                got=1; break
            fi
            sleep 5
        done
        if (( got )); then
            printf 'deb [signed-by=%s] https://packagecloud.io/crowdsec/crowdsec/any any main\n' "$key" >"$cs_list"
            run_long "Refreshing package lists" apt-get update -q || true
        else
            info "CrowdSec repository key unavailable; trying the Ubuntu archive"
        fi
    fi
    # nftables backend when the kernel/nft work: its set elements keep the
    # full ban duration, while ipset caps timeouts at ~24.8 days (longer bans
    # silently fall out of the kernel). iptables+ipset stays the fallback.
    local bouncer=crowdsec-firewall-bouncer-iptables
    bouncer_nft_usable && bouncer=crowdsec-firewall-bouncer-nftables
    if run_long "Installing CrowdSec + firewall bouncer" \
           apt-get install "${APT_OPTS[@]}" crowdsec "$bouncer"; then
        ok "CrowdSec installed (packagecloud, ${bouncer#crowdsec-firewall-bouncer-} bouncer)"
    elif crowdsec_drop_broken && [[ $bouncer != crowdsec-firewall-bouncer-iptables ]] \
           && run_long "Installing CrowdSec + iptables bouncer" \
           apt-get install "${APT_OPTS[@]}" crowdsec crowdsec-firewall-bouncer-iptables; then
        ok "CrowdSec installed (packagecloud, iptables bouncer)"
    elif crowdsec_drop_broken && run_long "Installing CrowdSec from the Ubuntu archive" \
           apt-get install "${APT_OPTS[@]}" crowdsec crowdsec-firewall-bouncer; then
        ok "CrowdSec installed (Ubuntu archive)"
    else
        crowdsec_drop_broken
        warn "CrowdSec could not be installed; the dashboard works without it."
        return 0
    fi
    configure_bouncer
}

# A failed CrowdSec attempt must not leave dpkg broken: apt-get refuses every
# later install while a package is half-configured ("1 not fully installed"),
# so the next attempt - and the TuxWall package itself - would fail too.
# Purges the CrowdSec packages that are not fully installed. Always returns 0.
crowdsec_drop_broken() {
    local -a broken=()
    local pkg st
    # db:Status-Abbrev = want, state, error flag: U/F/H = unpacked,
    # half-configured, half-installed; R = reinstallation required
    while read -r pkg st; do
        [[ -n $pkg ]] || continue
        if [[ ${st:1:1} == [UFH] || ${st:2:1} == R ]]; then broken+=("$pkg"); fi
    done < <(dpkg-query -W -f='${Package} ${db:Status-Abbrev}\n' 'crowdsec*' 2>/dev/null)
    (( ${#broken[@]} )) || return 0
    log "INFO CrowdSec: purging packages left half-installed: ${broken[*]}"
    run_long "Removing the half-installed CrowdSec packages" \
        apt-get purge -y -q -o DPkg::Lock::Timeout=600 "${broken[@]}" \
        || run_long "Removing the half-installed CrowdSec packages (dpkg)" \
               dpkg --purge --force-remove-reinstreq "${broken[@]}" \
        || true
    return 0
}

bouncer_nft_usable() {
    command -v nft >/dev/null 2>&1 && nft list tables >/dev/null 2>&1
}

# TuxWall bouncer layout (fresh installs only - step_crowdsec returns early
# when CrowdSec is already installed): nftables mode when available, hooked
# on input only (the iptables mode equivalent of CROWDSEC_CHAIN first in
# INPUT; forwarded traffic is not filtered, as before), priority -10 so
# bans drop before ufw's iptables-nft chains (priority filter = 0), DROP.
configure_bouncer() {
    local cfg=/etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml mode=iptables
    [[ -f $cfg ]] || { info "Bouncer config not found; leaving the bouncer defaults"; return 0; }
    bouncer_nft_usable && mode=nftables
    cp -p "$cfg" "$cfg.tuxwall-orig" 2>/dev/null || true
    if ! python3 - "$cfg" "$mode" >>"$LOG" 2>&1 <<'PY'
import re
import sys

path, mode = sys.argv[1], sys.argv[2]
s = open(path).read()
s = re.sub(r"(?m)^mode:.*$", "mode: " + mode, s, count=1)
s = re.sub(r"(?m)^deny_action:.*$", "deny_action: DROP", s, count=1)
if re.search(r"(?m)^nftables_hooks:", s):
    s = re.sub(r"(?m)^nftables_hooks:[ \t]*\n(?:[ \t]*(?:-.*)?\n)*", "nftables_hooks:\n  - input\n\n", s, count=1)
else:
    s = s.rstrip("\n") + "\n\nnftables_hooks:\n  - input\n"
# priority -10 for both families (insert after `chain:` when absent)
out, fam = [], None
for line in s.splitlines():
    m = re.match(r"^  (ipv4|ipv6):\s*$", line)
    if m:
        fam = m.group(1)
    elif re.match(r"^\S", line):
        fam = None
    if fam and re.match(r"^    priority:", line):
        continue
    out.append(line)
    if fam and re.match(r"^    chain:", line):
        out.append("    priority: -10")
s = "\n".join(out) + "\n"
open(path, "w").write(s)
PY
    then
        warn "Could not adjust the bouncer config (left as installed)"
        return 0
    fi
    bouncer_ensure_key "$cfg"
    if systemctl restart crowdsec-firewall-bouncer >>"$LOG" 2>&1; then
        ok "Firewall bouncer: $mode mode, input hook, priority -10"
    else
        warn "Firewall bouncer did not restart; check: journalctl -u crowdsec-firewall-bouncer"
    fi
}

# The bouncer's postinst registers its LAPI key only when CrowdSec is already
# configured, but apt configures the two packages of one transaction in either
# order: bouncer first = no key ("API error: access forbidden", restart loop,
# no ban enforced; seen on a fresh 26.04 netinstall). Register one then - only
# when CrowdSec knows no bouncer at all.
bouncer_ensure_key() {
    local cfg=$1 name key
    command -v cscli >/dev/null 2>&1 || return 0
    [[ "$(cscli bouncers list -o json 2>>"$LOG" | tr -d '[:space:]')" == "[]" ]] || return 0
    name="cs-firewall-bouncer-$(date +%s)"
    if ! key="$(cscli bouncers add "$name" -o raw 2>>"$LOG")" || [[ -z $key ]]; then
        warn "Could not register the firewall bouncer with CrowdSec (cscli bouncers add)"
        return 0
    fi
    if TUXWALL_BOUNCER_KEY="$key" python3 - "$cfg" >>"$LOG" 2>&1 <<'PY'
import os
import re
import sys

path = sys.argv[1]
s = open(path).read()
line = "api_key: " + os.environ["TUXWALL_BOUNCER_KEY"].strip()
if re.search(r"(?m)^api_key:.*$", s):
    s = re.sub(r"(?m)^api_key:.*$", lambda m: line, s, count=1)
else:
    s = s.rstrip("\n") + "\n" + line + "\n"
open(path, "w").write(s)
PY
    then
        ok "Firewall bouncer registered with CrowdSec ($name; the package could not do it)"
    else
        warn "Could not write the bouncer key; run: cscli bouncers add NAME, then set api_key in $cfg"
    fi
}

step_firewall() {
    local was_active=0 p
    ufw status 2>/dev/null | grep -q '^Status: active' && was_active=1

    sed -i 's/^#\?IPV6=.*/IPV6=yes/' /etc/default/ufw
    if (( ! was_active )); then
        q ufw default deny incoming
        q ufw default allow outgoing
        q ufw default deny routed
        info "Defaults: deny incoming, allow outgoing, deny routed"
    else
        info "UFW already active: keeping your default policies"
    fi

    # SSH first, so enabling the firewall can never cut the session
    # (established connections stay allowed whatever the rules say).
    # Gateway: never on the WAN unless --ssh-wan.
    for p in "${SSH_PORTS[@]}"; do
        if ufw_has_ssh_rule "$p"; then
            info "SSH port $p already has a rule (left as is)"
        elif [[ $ROLE == gateway && -n $LAN ]]; then
            q ufw allow in on "$LAN" to any port "$p" proto tcp comment 'TuxWall: SSH from LAN'
            ok "SSH port $p allowed from the LAN ($LAN)"
            if [[ -n $SSH_EXTRA_IFACE ]]; then
                q ufw allow in on "$SSH_EXTRA_IFACE" to any port "$p" proto tcp comment 'TuxWall: SSH (installer session)'
                ok "SSH port $p allowed on $SSH_EXTRA_IFACE (your session)"
            fi
            if [[ $SSH_SCOPE == wan ]]; then
                q ufw limit in on "$WAN" to any port "$p" proto tcp comment 'TuxWall: SSH from WAN (--ssh-wan)'
                warn "SSH port $p is reachable from the internet on $WAN (rate-limited, --ssh-wan); Firewall → Findings flags it"
            elif [[ -n $SSH_IFACE && $SSH_IFACE == "$WAN" ]]; then
                note "This SSH session (via the WAN) stays open; new SSH logins only from the LAN ($LAN)."
            fi
        else
            q ufw allow "$p/tcp" comment 'TuxWall: SSH'
            ok "SSH port $p allowed"
        fi
    done
    (( ${#SSH_PORTS[@]} )) || info "No SSH server found: no SSH rule needed"
    # the package's postinst opens SSH/80 only when nothing did: here we did
    export TUXWALL_INSTALLER_FIREWALL=1

    if [[ $ROLE == gateway ]]; then
        q ufw allow in on "$LAN" comment 'TuxWall: LAN to gateway'
        # An explicit LAN-scoped dashboard rule also stops the package from
        # opening 80/tcp on every interface.
        q ufw allow in on "$LAN" to any port 80 proto tcp comment 'TuxWall dashboard (LAN)'
        q ufw allow in on "$LAN" to any port 443 proto tcp comment 'TuxWall dashboard HTTPS (LAN)'
        q ufw route allow in on "$LAN" out on "$WAN" comment 'tuxwall: LAN -> WAN'
        # WireGuard's port is opened on the WAN by the dashboard's WireGuard
        # setup (tagged tuxwall-wireguard), not before a VPN exists.
        grep -q '^net/ipv4/ip_forward' /etc/ufw/sysctl.conf 2>/dev/null || echo 'net/ipv4/ip_forward=1' >>/etc/ufw/sysctl.conf
        grep -q '^net/ipv6/conf/all/forwarding' /etc/ufw/sysctl.conf 2>/dev/null || echo 'net/ipv6/conf/all/forwarding=1' >>/etc/ufw/sysctl.conf
        ok "LAN → gateway allowed, LAN → WAN routed (WireGuard's port opens when you set WireGuard up)"
    else
        local net
        for net in 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 fd00::/8; do
            q ufw allow proto tcp from "$net" to any port 80 comment 'TuxWall dashboard (private networks)'
            q ufw allow proto tcp from "$net" to any port 443 comment 'TuxWall dashboard HTTPS (private networks)'
        done
        ok "Dashboard (80+443/tcp) allowed from private networks only"
    fi

    if (( ! was_active )); then
        q ufw --force enable
        ok "Firewall enabled"
    else
        q ufw reload || true
        ok "Firewall rules updated"
    fi
}

netplan_yaml() {
    echo "# $INSTALLER_MARK on $(date '+%F %T')."
    echo "# LAN = $LAN ($NET_GW/$NET_PREFIX), WAN = $WAN ($WAN_MODE)."
    echo "network:"
    echo "  version: 2"
    echo "  ethernets:"
    echo "    $LAN:"
    echo "      dhcp4: false"
    echo "      dhcp6: false"
    echo "      accept-ra: false"
    echo "      optional: true"
    echo "      ignore-carrier: true"
    echo "      addresses:"
    echo "        - $NET_GW/$NET_PREFIX"
    echo "        - \"$ULA::1/64\""
    if [[ $WAN_MODE == dhcp ]]; then
        echo "    $WAN:"
        echo "      dhcp4: true"
        echo "      dhcp6: true"
        echo "      accept-ra: true"
    fi
}

write_netplan() {
    local f=/etc/netplan/90-tuxwall.yaml tmp other
    tmp="$(mktemp)"
    netplan_yaml >"$tmp"
    backup_file "$f"
    install -m 600 "$tmp" "$f"
    rm -f "$tmp"
    if ! q netplan generate; then
        rm -f "$f"
        [[ -e "$BACKUP_DIR$f" ]] && cp -a "$BACKUP_DIR$f" "$f"
        die "netplan rejected the generated config (details in $LOG)."
    fi
    ok "Netplan: $LAN = $NET_GW/$NET_PREFIX + $ULA::1/64$([[ $WAN_MODE == dhcp ]] && echo ", $WAN = DHCP")"
    other="$(grep -l -E "^[[:space:]]+$LAN:" /etc/netplan/*.yaml 2>/dev/null | grep -v 90-tuxwall.yaml || true)"
    [[ -n $other ]] && note "Also mentions $LAN: $other (TuxWall's file overrides its DHCP setting)"
    return 0
}

kea_json() {   # kea_json socket-key
    # Socket retries (= pkg/DEBIAN/postinst KEA_SOCKET_RETRIES/_WAIT): Kea
    # opens its sockets once; when the LAN link is not running yet at boot
    # it retries every 10 s for 5 minutes instead of serving no DHCP.
    # lease_cmds hook (as pkg/DEBIAN/postinst): the dashboard's leases view
    # and its post-reload health check use lease4-get-all, which answers
    # "command not supported" without it. Only when the library exists -
    # Kea refuses to start with a missing hook library.
    local hooks=""
    [[ -f $KEA_LEASE_CMDS_LIB ]] && hooks=",
    \"hooks-libraries\": [
      { \"library\": \"$KEA_LEASE_CMDS_LIB\" }
    ]"
    cat <<KEA
// $INSTALLER_MARK on $(date '+%F %T'). Managed from the DHCP page afterwards.
{
  "Dhcp4": {
    "interfaces-config": {
      "interfaces": [ "$LAN" ],
      "service-sockets-max-retries": 30,
      "service-sockets-retry-wait-time": 10000
    },
    "valid-lifetime": 7200,
    "renew-timer": 3600,
    "rebind-timer": 6300,
    "lease-database": {
      "type": "memfile",
      "lfc-interval": 3600,
      "persist": true,
      "name": "/var/lib/kea/kea-leases4.csv"
    },
    "control-socket": {
      "socket-type": "unix",
      "$1": "/run/kea/kea4-ctrl-socket"
    },
    "subnet4": [
      {
        "id": 1,
        "subnet": "$NET_CIDR",
        "interface": "$LAN",
        "pools": [ { "pool": "$NET_POOL_LO - $NET_POOL_HI" } ],
        "option-data": [
          { "name": "routers", "data": "$NET_GW" },
          { "name": "domain-name-servers", "data": "$NET_GW" },
          { "name": "domain-name", "data": "$DOMAIN" },
          { "name": "domain-search", "data": "$DOMAIN" }
        ]
      }
    ]$hooks
  }
}
KEA
}

write_kea() {
    local f=/etc/kea/kea-dhcp4.conf tmp key chosen="" grp=root
    # Test file must live under /etc/kea: Kea's AppArmor profile blocks /tmp.
    mkdir -p /etc/kea
    tmp="$(mktemp -p /etc/kea .tuxwall-kea-dhcp4.XXXXXX)"
    # Syntax check as the _kea user: Ubuntu 26.04's /etc/kea is
    # _kea:_kea 0750 and Kea's AppArmor profile denies root the DAC
    # override capabilities, so a root-run 'kea-dhcp4 -t' cannot even
    # read the file. As _kea the check works on every release.
    local kea_user=""
    getent passwd _kea >/dev/null 2>&1 && kea_user=_kea
    getent passwd kea  >/dev/null 2>&1 && kea_user=${kea_user:-kea}
    kea_check() {
        if [[ -n $kea_user ]] && command -v runuser >/dev/null 2>&1; then
            q runuser -u "$kea_user" -- kea-dhcp4 -t "$tmp"
        else
            q kea-dhcp4 -t "$tmp"
        fi
    }
    for key in socket-name socket-address; do
        kea_json "$key" >"$tmp"
        chmod 0644 "$tmp"   # mktemp gives 0600 root-only; _kea must read it
        if ! command -v kea-dhcp4 >/dev/null 2>&1 || kea_check; then
            chosen=$key; break
        fi
    done
    if [[ -z $chosen ]]; then
        rm -f "$tmp"
        warn "Kea rejected the generated config (see $LOG); kept the existing file."
        return 0
    fi
    getent group _kea >/dev/null 2>&1 && grp=_kea
    getent group kea  >/dev/null 2>&1 && grp=kea
    backup_file "$f"
    install -o root -g "$grp" -m 640 "$tmp" "$f"
    rm -f "$tmp"
    ok "Kea DHCP: $NET_CIDR on $LAN, pool $NET_POOL_LO – $NET_POOL_HI"
}

radvd_conf() {
    cat <<RADVD
# $INSTALLER_MARK on $(date '+%F %T').
interface $LAN
{
    AdvSendAdvert on;
    MinRtrAdvInterval 30;
    MaxRtrAdvInterval 100;
    AdvManagedFlag off;
    AdvOtherConfigFlag off;
    prefix $ULA::/64
    {
        AdvOnLink on;
        AdvAutonomous on;
        AdvRouterAddr on;
    };
    RDNSS $ULA::1 { };
    DNSSL $DOMAIN { };
};
RADVD
}

# Same bytes as pkg/usr/share/tuxwall/radvd/10-tuxwall.conf (the package may
# be older than this installer; tools/pkg_scripts_check.py compares them).
radvd_dropin() {
    cat <<'DROPIN'
# TuxWall: radvd reads /etc/tuxwall/radvd.conf instead of /etc/radvd.conf.
# The dashboard runs with ProtectSystem=full (/etc read-only except its
# ReadWritePaths), so it can only replace radvd's config inside /etc/tuxwall.
# Installed by the TuxWall installer / postinst as
# /etc/systemd/system/radvd.service.d/10-tuxwall.conf after
# `radvd --configtest --config /etc/tuxwall/radvd.conf` passed. The old
# /etc/radvd.conf is left in place, unused. Undo: delete this drop-in,
# `systemctl daemon-reload`, `systemctl restart radvd`.
[Unit]
ConditionPathExists=
ConditionPathExists=/etc/tuxwall/radvd.conf

[Service]
ExecStartPre=
ExecStartPre=/usr/sbin/radvd --logmethod stderr_clean --configtest --config /etc/tuxwall/radvd.conf
ExecStart=
ExecStart=/usr/sbin/radvd --logmethod stderr_clean --config /etc/tuxwall/radvd.conf
ExecReload=
ExecReload=/usr/sbin/radvd --logmethod stderr_clean --configtest --config /etc/tuxwall/radvd.conf
ExecReload=/bin/kill -HUP $MAINPID
DROPIN
}

write_radvd() {
    local f=$RADVD_CONF tmp
    tmp="$(mktemp)"
    radvd_conf >"$tmp"
    if command -v radvd >/dev/null 2>&1 && ! q radvd --configtest --config "$tmp"; then
        rm -f "$tmp"
        warn "radvd rejected the generated config (see $LOG); kept the existing file."
        return 0
    fi
    backup_file "$f"
    mkdir -p "${f%/*}"
    install -m 644 "$tmp" "$f"
    rm -f "$tmp"
    # radvd reads it through the drop-in; the stock file (if any) stays, unused
    mkdir -p "${RADVD_DROPIN%/*}"
    radvd_dropin >"$RADVD_DROPIN"
    chmod 644 "$RADVD_DROPIN"
    q systemctl daemon-reload || true
    ok "radvd: advertising $ULA::/64 and DNS $ULA::1 on $LAN ($f)"
}

unbound_router_conf() {
    cat <<UNB
# $INSTALLER_MARK on $(date '+%F %T'). Managed from the DNS page afterwards.
server:
    interface: 0.0.0.0
    interface: ::0
    interface-automatic: yes
    access-control: 127.0.0.0/8 allow
    access-control: ::1/128 allow
    access-control: $NET_CIDR allow
    access-control: $ULA::/48 allow
    do-not-query-localhost: no
forward-zone:
    name: "."
    forward-addr: 1.1.1.1
    forward-addr: 8.8.8.8
UNB
}

unbound_gateway_conf() {
    cat <<UNB
# $INSTALLER_MARK on $(date '+%F %T').
server:
    local-zone: "$DOMAIN." static
    local-data: "gateway.$DOMAIN. IN A $NET_GW"
    local-data: "gateway.$DOMAIN. IN AAAA $ULA::1"
    local-data-ptr: "$NET_GW gateway.$DOMAIN."
    local-data-ptr: "$ULA::1 gateway.$DOMAIN."
UNB
}

write_unbound() {
    local d=/etc/unbound/unbound.conf.d written=()
    mkdir -p "$d" /var/lib/unbound

    if [[ $UNBOUND_ACTION != keep ]]; then
        backup_file "$d/router-dns.conf"
        unbound_router_conf >"$d/router-dns.conf"
        written+=("$d/router-dns.conf")
    elif ! grep -qs "access-control:.*${NET_CIDR%/*}" "$d"/*.conf; then
        warn "Your Unbound config has no access-control for $NET_CIDR: LAN clients may be refused."
    fi

    # Gateway name in its own file: the Local Domains page owns 98-local-domains.conf.
    backup_file "$d/97-tuxwall-gateway.conf"
    unbound_gateway_conf >"$d/97-tuxwall-gateway.conf"
    written+=("$d/97-tuxwall-gateway.conf")

    # Pre-empt the packaged default (hard-coded 192.168.1.1 / home.arpa) with
    # the include the Local Domains page writes itself.
    if [[ ! -s $d/98-local-domains.conf ]] || grep -q 'gateway.home.arpa. IN A 192.168.1.1' "$d/98-local-domains.conf"; then
        backup_file "$d/98-local-domains.conf"
        [[ -s /var/lib/unbound/local-domains.conf ]] || \
            printf '# Generated by the tuxwall Local Domains page - DO NOT EDIT\n# 0 local domains\nserver:\n' >/var/lib/unbound/local-domains.conf
        printf '# Managed by the tuxwall Local Domains page - DO NOT EDIT\nserver:\ninclude: "/var/lib/unbound/local-domains.conf"\n' >"$d/98-local-domains.conf"
        written+=("$d/98-local-domains.conf")
    fi

    # DNSSEC trust anchor (unbound refuses to start without it).
    if [[ ! -s /var/lib/unbound/root.key ]]; then
        if [[ -s /usr/share/dns/root.key ]]; then
            cp /usr/share/dns/root.key /var/lib/unbound/root.key
        else
            q unbound-anchor -a /var/lib/unbound/root.key || true
        fi
        chown unbound:unbound /var/lib/unbound/root.key 2>/dev/null || true
    fi

    if ! q unbound-checkconf; then
        local f
        for f in "${written[@]}"; do
            if [[ -e "$BACKUP_DIR$f" ]]; then cp -a "$BACKUP_DIR$f" "$f"; else rm -f "$f"; fi
        done
        warn "unbound-checkconf rejected the new files; restored the previous Unbound config."
        return 0
    fi
    ok "Unbound: serves $NET_CIDR + $ULA::/48, gateway.$DOMAIN → $NET_GW"
}

step_gateway_config() {
    mkdir -p /etc/tuxwall "$BACKUP_DIR"

    # Packet forwarding, persisted where the package expects it.
    printf '# %s\nnet.ipv4.ip_forward=1\nnet.ipv6.conf.all.forwarding=1\n' "$INSTALLER_MARK" \
        >/etc/sysctl.d/99-tuxwall-router.conf
    q sysctl -w net.ipv4.ip_forward=1
    q sysctl -w net.ipv6.conf.all.forwarding=1
    ok "IPv4/IPv6 forwarding enabled"

    write_netplan
    if [[ $KEA_ACTION == keep ]]; then info "Kea: keeping your existing config"; else write_kea; fi
    if [[ $RADVD_ACTION == keep ]]; then info "radvd: keeping your existing config"; else write_radvd; fi
    write_unbound

    # NAT follows the chosen WAN even before a default route exists at boot.
    mkdir -p /etc/systemd/system/tuxwall-nat.service.d
    printf '[Service]\nEnvironment=TUXWALL_WAN_IFACE=%s\n' "$WAN" \
        >/etc/systemd/system/tuxwall-nat.service.d/10-wan.conf
    ok "NAT pinned to WAN interface $WAN"
}

step_dns() {
    q systemctl disable --now systemd-resolved.service || true
    q systemctl disable --now systemd-resolved-varlink.socket systemd-resolved-monitor.socket || true
    # netplan's generated systemd-networkd-wait-online drop-in waits with --dns
    # (it pings io.systemd.Resolve.Monitor). Once resolved is retired the wait
    # fails on every boot ("Failed to connect to io.systemd.Resolve.Monitor") -
    # cosmetic (network-online.target is still reached) but it leaves a red
    # failed unit. Re-run the same wait without --dns.
    mkdir -p /etc/systemd/system/systemd-networkd-wait-online.service.d
    printf '[Service]\nExecStart=\nExecStart=/lib/systemd/systemd-networkd-wait-online --any -o routable -i %s\n' \
        "$WAN" >/etc/systemd/system/systemd-networkd-wait-online.service.d/tuxwall.conf
    ok "network-online wait no longer waits for the retired systemd-resolved"
    if [[ -e /etc/resolv.conf || -L /etc/resolv.conf ]]; then
        mkdir -p "$BACKUP_DIR/etc"
        cp -aL /etc/resolv.conf "$BACKUP_DIR/etc/resolv.conf" 2>/dev/null || true
    fi
    rm -f /etc/resolv.conf
    printf '# %s: this gateway resolves through its own Unbound.\nnameserver 127.0.0.1\nnameserver ::1\nsearch %s\n' \
        "$INSTALLER_MARK" "$DOMAIN" >/etc/resolv.conf
    q systemctl enable unbound || true
    q systemctl restart unbound || true
    if wait_dns 20; then
        ok "systemd-resolved retired; this gateway now resolves through Unbound"
    else
        printf '# %s: temporary public resolvers (Unbound did not answer).\nnameserver 1.1.1.1\nnameserver 9.9.9.9\nsearch %s\n' \
            "$INSTALLER_MARK" "$DOMAIN" >/etc/resolv.conf
        warn "Unbound did not answer; /etc/resolv.conf uses 1.1.1.1 / 9.9.9.9 for now. Switch it back to 127.0.0.1 once Unbound works."
    fi
}

build_local_deb() {
    local stage ver
    stage="$(mktemp -d /tmp/tuxwall-build.XXXXXX)"
    chmod 755 "$stage"   # apt's _apt user must be able to read the .deb
    ver="$(repo_version)+src$(date +%Y%m%d%H%M)"
    local excl=(--exclude '*.bak' --exclude '*.bak-*' --exclude '*.bak.*' --exclude '__pycache__'
                --exclude '*.pyc' --exclude '*.orig' --exclude '*.swp' --exclude '*~' --exclude '.git')
    rsync -a "${excl[@]}" "$REPO_DIR/pkg/" "$stage/pkg/"
    mkdir -p "$stage/pkg/var/www/html"
    rsync -a "${excl[@]}" "$REPO_DIR/www/" "$stage/pkg/var/www/html/"
    sed -i "s/^Version: .*/Version: $ver/" "$stage/pkg/DEBIAN/control"
    find "$stage/pkg" -type d -exec chmod 755 {} +
    chmod -R go-w "$stage/pkg"
    chmod 755 "$stage/pkg/DEBIAN"/{postinst,prerm,postrm} 2>/dev/null || true
    chmod 644 "$stage/pkg/DEBIAN"/{control,conffiles} 2>/dev/null || true
    find "$stage/pkg/usr/local/sbin" -type f -exec chmod 755 {} + 2>/dev/null || true
    chmod 755 "$stage/pkg/var/www/html/includes/api_server.py"
    q dpkg-deb --root-owner-group -Zxz --build "$stage/pkg" "$stage/tuxwall_${ver}_all.deb" \
        || die "dpkg-deb could not build the package."
    DEB_FILE="$stage/tuxwall_${ver}_all.deb"
    PKG_VERSION=$ver
    ok "Built tuxwall $ver from $REPO_DIR"
}

register_apt_repo() {
    local tmp fpr
    tmp="$(mktemp -d)"
    mkdir -m 700 "$tmp/gnupg"
    if [[ -s $REPO_DIR/apt-public.asc ]]; then
        cp "$REPO_DIR/apt-public.asc" "$tmp/key.asc"
    elif ! curl -fsSL --retry 3 -m 60 "$APT_REPO_URL/public.asc" -o "$tmp/key.asc" 2>>"$LOG"; then
        rm -rf "$tmp"; return 1
    fi
    GNUPGHOME="$tmp/gnupg" gpg --batch --yes --dearmor -o "$tmp/tuxwall.gpg" "$tmp/key.asc" 2>>"$LOG" || { rm -rf "$tmp"; return 1; }
    fpr="$(GNUPGHOME="$tmp/gnupg" gpg --batch --show-keys --with-colons "$tmp/tuxwall.gpg" 2>/dev/null | awk -F: '/^fpr:/{print $10; exit}' || true)"
    if [[ $fpr != "$APT_KEY_FPR" ]]; then
        rm -rf "$tmp"
        warn "TuxWall signing key fingerprint mismatch (got ${fpr:-none}); repository NOT added."
        return 1
    fi
    install -m 644 "$tmp/tuxwall.gpg" "$APT_KEYRING"
    echo "deb [signed-by=$APT_KEYRING] $APT_REPO_URL stable main" >"$APT_LIST"
    rm -rf "$tmp"
    return 0
}

step_package() {
    # Ubuntu's stock nginx site also serves /var/www/html, which makes the
    # package think a custom site exists and skip enabling the dashboard.
    if [[ -L /etc/nginx/sites-enabled/default && "$(readlink -f /etc/nginx/sites-enabled/default)" == /etc/nginx/sites-available/default ]]; then
        rm -f /etc/nginx/sites-enabled/default
        info "Disabled nginx's stock default site"
    fi
    # The package's postinst installs files owned by this user, so it must exist first.
    if ! id tuxwall-agent >/dev/null 2>&1; then
        q useradd --create-home --shell /bin/bash tuxwall-agent
        info "Created the tuxwall-agent user"
    fi
    # --no-agent: the postinst installs the AI assistant when opencode is
    # missing unless this opt-out exists (step_agent does it otherwise).
    mkdir -p /etc/tuxwall
    if (( WITH_AGENT )); then rm -f /etc/tuxwall/no-agent; else touch /etc/tuxwall/no-agent; fi

    case "$SOURCE" in
        local) build_local_deb ;;
        deb)   PKG_VERSION="$(dpkg-deb -f "$DEB_FILE" Version 2>/dev/null || true)" ;;
        apt)
            register_apt_repo || die "Could not add the TuxWall APT repository (see $LOG)."
            run_long "Refreshing package lists" apt-get update -q || die "apt-get update failed."
            ok "TuxWall APT repository added (key ${APT_KEY_FPR: -16} verified)" ;;
    esac

    local target=tuxwall
    [[ $SOURCE != apt ]] && target="$DEB_FILE"
    if ! run_long "Installing the TuxWall package" apt-get install "${APT_OPTS[@]}" "$target"; then
        die "Package installation failed. Fix the error above, then run: sudo dpkg --configure -a"
    fi
    PKG_VERSION="$(dpkg-query -W -f='${Version}' tuxwall 2>/dev/null || echo "$PKG_VERSION")"
    ok "tuxwall $PKG_VERSION installed"
    [[ $SOURCE == local ]] && rm -rf "$(dirname "$DEB_FILE")"
    return 0
}

step_post() {
    mkdir -p /etc/tuxwall /var/lib/tuxwall/backups/system
    chmod 755 /etc/tuxwall

    if have_repo; then
        [[ -f /etc/tuxwall/ui.json ]] || install -m 644 "$REPO_DIR/config/ui.json" /etc/tuxwall/ui.json
        [[ -f /etc/tuxwall/custom-blocklist.txt ]] || install -m 644 "$REPO_DIR/config/custom-blocklist.txt" /etc/tuxwall/custom-blocklist.txt
        [[ -f /etc/tuxwall/llm.json ]] || install -m 600 "$REPO_DIR/config/llm.json.example" /etc/tuxwall/llm.json
        # The package ships the SQM helper since 3.3.5; an older --source deb
        # package does not, so fall back to the copy in this checkout.
        if [[ ! -x /usr/local/sbin/tuxwall-sqm.sh && -f $REPO_DIR/pkg/usr/local/sbin/tuxwall-sqm.sh ]]; then
            install -m 755 "$REPO_DIR/pkg/usr/local/sbin/tuxwall-sqm.sh" /usr/local/sbin/tuxwall-sqm.sh
        fi
    elif [[ ! -f /etc/tuxwall/llm.json && -f /etc/tuxwall/llm.json.example ]]; then
        install -m 600 /etc/tuxwall/llm.json.example /etc/tuxwall/llm.json
    fi
    ok "Dashboard settings in /etc/tuxwall"

    local sqm_wan="${WAN:-$DEF_IF}"
    if [[ ! -f /etc/tuxwall/sqm.conf && -n $sqm_wan ]]; then
        printf '%s\n' '# TuxWall SQM rates (Mbit). Managed by System > Traffic Shaping.' \
            "WAN=$sqm_wan" 'UP_RATE=95mbit' 'DOWN_RATE=920mbit' >/etc/tuxwall/sqm.conf
        info "Traffic shaping seeded for $sqm_wan (off until enabled in System → Traffic Shaping)"
    fi

    # nginx: the packaged vhost is host neutral since 3.3.3 (its LAN/VPN
    # listen lines are generated into /etc/nginx/snippets/tuxwall-listen.conf
    # by tuxwall-nginx-listen); an older, edited vhost kept by dpkg may still
    # name addresses - drop listeners for addresses this box does not have.
    local vhost=/etc/nginx/sites-available/tuxwall addr line
    if [[ -f $vhost ]]; then
        while read -r line; do
            addr="$(sed -E 's/^[[:space:]]*listen[[:space:]]+\[?([0-9a-fA-F:.]+)\]?:[0-9]+.*/\1/' <<<"$line")"
            if ! ip -o addr show 2>/dev/null | awk '{split($4,a,"/"); print a[1]}' | grep -qxF "$addr"; then
                backup_file "$vhost"
                sed -i "\|^[[:space:]]*listen[[:space:]]\+\[\?${addr//./\\.}\]\?:|d" "$vhost"
                info "nginx: removed listener for $addr (not on this machine)"
            fi
        done < <(grep -E '^[[:space:]]*listen[[:space:]]+(([0-9]{1,3}\.){3}[0-9]{1,3}|\[[0-9a-fA-F:]*[0-9a-fA-F][0-9a-fA-F:]*\]):' "$vhost" || true)
        ln -sf "$vhost" /etc/nginx/sites-enabled/tuxwall
        if q nginx -t; then ok "nginx dashboard site enabled"; else warn "nginx -t failed: check $vhost"; fi
    fi

    # Canary egress containment (only when OpenCanary is deployed). Shared
    # with postinst/deploy-opencanary: www/includes/canary_egress.py detects
    # the owner-match REJECT itself (the old marker test never matched its own
    # comment, so every run added another copy) and is idempotent.
    if id opencanary >/dev/null 2>&1 && [[ -f /var/www/html/includes/canary_egress.py ]]; then
        if ! PYTHONDONTWRITEBYTECODE=1 python3 /var/www/html/includes/canary_egress.py --check >/dev/null 2>&1; then
            PYTHONDONTWRITEBYTECODE=1 python3 /var/www/html/includes/canary_egress.py --apply >/dev/null 2>&1 || true
            ok "Canary egress containment applied"
        fi
    fi

    # Agent home: the package creates ~/.config as root; give it back.
    if id tuxwall-agent >/dev/null 2>&1 && [[ -d /home/tuxwall-agent ]]; then
        chown -R tuxwall-agent:tuxwall-agent /home/tuxwall-agent
    fi

    # Install profile: lets later tooling (and future dashboard versions) know
    # the topology instead of guessing interface names.
    python3 - "$PROFILE_JSON" <<PY
import json, sys, datetime
data = {
    "installed_at": datetime.datetime.now().isoformat(timespec="seconds"),
    "installer": "$INSTALLER_VERSION",
    "source": "$SOURCE",
    "role": "$ROLE",
    "package_version": "$PKG_VERSION",
    "wan": "$WAN" or None,
    "wan_mode": "$WAN_MODE" or None,
    "lan": "$LAN" or None,
    "lan_network": "$NET_CIDR" or None,
    "lan_gateway": "$NET_GW" or None,
    "dhcp_pool": ["$NET_POOL_LO", "$NET_POOL_HI"] if "$NET_POOL_LO" else None,
    "ula_prefix": ("$ULA::/64" if "$ULA" else None),
    "domain": "$DOMAIN" or None,
}
with open(sys.argv[1], "w") as f:
    json.dump(data, f, indent=2)
    f.write("\n")
PY
    chmod 644 "$PROFILE_JSON"
    ok "Install profile written to $PROFILE_JSON"

    # Interface roles record (WAN/LAN/OPT/VPN) next to the profile. Never
    # overwrites an existing file; best effort.
    if [[ ! -e /etc/tuxwall/interfaces.json && -f /var/www/html/includes/topology.py ]]; then
        if PYTHONDONTWRITEBYTECODE=1 python3 /var/www/html/includes/topology.py --write >/dev/null 2>&1 \
                && [[ -f /etc/tuxwall/interfaces.json ]]; then
            ok "Interface roles written to /etc/tuxwall/interfaces.json"
        else
            warn "Could not record interface roles yet; the dashboard creates /etc/tuxwall/interfaces.json on first use."
        fi
    fi
}

step_agent() {
    # The package ships the script (the postinst already ran it when opencode
    # was missing); a re-run is idempotent and downloads nothing then.
    local script="" args=() cand
    for cand in /usr/local/share/tuxwall/scripts/setup-opencode-agent.sh \
                "$REPO_DIR/pkg/usr/local/share/tuxwall/scripts/setup-opencode-agent.sh"; do
        [[ -f $cand ]] && { script=$cand; break; }
    done
    if [[ -z $script ]]; then
        warn "setup-opencode-agent.sh not found; skipped the AI assistant."
        return 0
    fi
    [[ -f $REPO_DIR/config/opencode.json ]] && args=("$REPO_DIR/config/opencode.json")
    if run_long "Installing the opencode agent (pinned, checksum-verified download)" \
            env TUXWALL_AGENT_EDIT_WEBROOT="$AGENT_EDIT_WEBROOT" bash "$script" "${args[@]}"; then
        ok "AI assistant ready (tuxwall-agent.service on 127.0.0.1:4096)"
    else
        warn "AI assistant setup failed (offline?). Re-run later: sudo bash $script"
    fi
}

step_harden() {
    local w=/var/www/html f
    find "$w" \( -name '*.bak-[0-9]*' -o -name '*.bak.[0-9]*' -o -name '*.pyc' \) -type f -delete 2>/dev/null || true
    find "$w" -name '__pycache__' -type d -prune -exec rm -rf {} + 2>/dev/null || true

    if (( AGENT_EDIT_WEBROOT )); then
        warn "Web root left writable by tuxwall-agent (--agent-edit-webroot)."
    else
        chown -R root:root "$w"
        find "$w" -type d -exec chmod 755 {} +
        find "$w" -type f -exec chmod 644 {} +
        chmod 755 "$w/includes/api_server.py"
        find "$w/scripts" -maxdepth 1 -name '*.sh' -type f -exec chmod 755 {} + 2>/dev/null || true
        ok "Dashboard code is root-owned; nginx and the agent can read but not change it"
    fi

    for f in /etc/tuxwall/llm.json /etc/tuxwall/auth.json /etc/tuxwall/internal-token \
             /etc/tuxwall/agent-token /etc/tuxwall/agent-password.env /etc/tuxwall/reporting.json /etc/tuxwall/llm.json.bak*; do
        if [[ -e $f ]]; then chmod 600 "$f"; fi
    done
    ok "Secrets in /etc/tuxwall readable by root only"
}

step_extras() {
    local s
    if (( WITH_SPEEDTEST )); then
        if command -v speedtest >/dev/null 2>&1; then
            ok "Speedtest already installed"
        else
            s=/var/www/html/scripts/install-speedtest.sh
            [[ -f $s ]] || s="$REPO_DIR/scripts/install-speedtest.sh"
            if [[ -f $s ]] && run_long "Installing the Ookla speedtest CLI" bash "$s"; then
                ok "Speedtest installed"
            else
                warn "Speedtest not installed; Traffic Shaping will show an install hint."
            fi
        fi
    fi
    if (( WITH_GEOIP )); then
        if [[ -s /var/lib/tuxwall/dbip-city-lite.mmdb ]]; then
            ok "GeoIP database already present"
        else
            s=/var/www/html/scripts/geoip-setup.sh
            [[ -f $s ]] || s="$REPO_DIR/www/scripts/geoip-setup.sh"
            if [[ -f $s ]] && run_long "Downloading the DB-IP GeoIP databases" bash "$s"; then
                ok "GeoIP attack map enabled"
            else
                warn "GeoIP download failed; run later: sudo bash /var/www/html/scripts/geoip-setup.sh"
            fi
        fi
    fi
}

step_updates() {
    if grep -rqs "rezzonance.github.io/tuxwall" /etc/apt/sources.list /etc/apt/sources.list.d/; then
        ok "TuxWall APT repository already registered"
        return 0
    fi
    if register_apt_repo; then
        run_long "Refreshing package lists" apt-get update -q || true
        ok "Updates via: sudo apt update && sudo apt upgrade tuxwall"
        [[ $SOURCE == local ]] && note "A newer official release will replace this source build on apt upgrade."
    else
        warn "Update repository not registered; add it later with this installer (--source apt)."
    fi
}

step_network_apply() {
    if [[ $NET_APPLY_DECISION == reboot ]]; then
        warn "LAN configuration saved but not activated: $NET_APPLY_REASON. Reboot to activate it."
        return 0
    fi
    if run_long "Applying netplan" netplan apply; then
        sleep 3
        ok "Network active: $LAN = $NET_GW/$NET_PREFIX"
    else
        warn "netplan apply failed; the configuration activates at the next reboot."
        NET_APPLY_DECISION=reboot
        NET_APPLY_REASON="netplan apply failed"
    fi
}

step_services() {
    q systemctl daemon-reload
    # LAN/VPN addresses exist now (network applied): regenerate the vhost's
    # default_server listen include (nginx -t inside; old file kept on failure)
    if [[ -x /usr/local/sbin/tuxwall-nginx-listen ]]; then
        q /usr/local/sbin/tuxwall-nginx-listen || warn "nginx listen include not updated (sudo tuxwall-nginx-listen)"
    fi
    # dashboard HTTPS: certificate SANs + 443 listeners for the addresses that
    # exist now (nginx -t inside, previous files kept on failure)
    if [[ -x /usr/local/sbin/tuxwall-tls ]]; then
        q /usr/local/sbin/tuxwall-tls refresh || warn "dashboard HTTPS not updated (sudo tuxwall-tls refresh --reload)"
    fi
    local svc
    local -a base=(nginx tuxwall tuxwall-nat avahi-daemon tuxwall-blocklist-update.timer suricata-update.timer)
    [[ $ROLE == gateway ]] && base=(unbound "${base[@]}")
    for svc in "${base[@]}"; do
        q systemctl enable "$svc" || true
        q systemctl restart "$svc" || warn "$svc did not start (systemctl status $svc)"
    done
    if [[ $ROLE == gateway ]]; then
        for svc in kea-dhcp4-server radvd tuxwall-kea-mirror.timer; do
            q systemctl enable "$svc" || true
            if [[ $NET_APPLY_DECISION == now ]]; then
                q systemctl restart "$svc" || warn "$svc did not start (systemctl status $svc)"
            fi
        done
    fi
    # The LAN has its address and role now (the package's postinst may have
    # run before the network was applied): make Suricata capture it too, so
    # device monitoring can attribute IDS alerts to LAN devices. Untouched
    # when it already does, for IPS setups, or when no LAN is known.
    local tune=/usr/local/share/tuxwall/scripts/tune-suricata.py
    if [[ -f /etc/suricata/suricata.yaml && -f $tune ]] && q python3 "$tune" --add-lan /etc/suricata/suricata.yaml; then
        ok "Suricata also captures the LAN interface (device monitoring)"
    fi
    q systemctl enable suricata || true
    q systemctl restart suricata || info "Suricata is not running yet (it starts once rules are downloaded)"
    if command -v cscli >/dev/null 2>&1; then
        for svc in crowdsec crowdsec-firewall-bouncer crowdsec-dedupe.timer; do
            q systemctl enable "$svc" 2>/dev/null || true
            q systemctl restart "$svc" 2>/dev/null || true
        done
    fi
    ok "Services enabled and started"

    if wait_api 30; then
        ok "Dashboard API is up"
        local tok=/etc/tuxwall/internal-token hdr
        if [[ -s $tok ]]; then
            hdr="$(mktemp)"; chmod 600 "$hdr"
            printf 'X-Tuxwall-Token: %s\n' "$(cat "$tok")" >"$hdr"
            if curl -fsS -m 15 -X POST -H @"$hdr" http://127.0.0.1:8008/api/blocklists/update >>"$LOG" 2>&1; then
                ok "First blocklist download started (Blocklists page shows progress)"
            else
                warn "Could not start the first blocklist download; the daily timer will do it."
            fi
            rm -f "$hdr"
        else
            info "Blocklists download on the daily timer (no internal token yet)"
        fi
    else
        warn "Dashboard API did not answer within 30s (journalctl -u tuxwall)"
    fi
}

check() {   # check LEVEL "label" cmd...   LEVEL: critical | normal | pending
    local level=$1 label=$2; shift 2
    if "$@" >>"$LOG" 2>&1; then
        printf '    %s✓%s %s\n' "$C_G" "$C_0" "$label"
    elif [[ $level == pending ]]; then
        printf '    %s…%s %s %s(after reboot)%s\n' "$C_Y" "$C_0" "$label" "$C_DIM" "$C_0"
    elif [[ $level == critical ]]; then
        printf '    %s✗%s %s\n' "$C_R" "$C_0" "$label"
        CRIT_FAIL=$((CRIT_FAIL + 1))
        log "CHECK FAILED (critical): $label"
    else
        printf '    %s!%s %s\n' "$C_Y" "$C_0" "$label"
        log "CHECK FAILED: $label"
    fi
}
active()       { systemctl is-active --quiet "$1"; }
http_ok()      { curl -fsS -m 5 -o /dev/null "$1"; }
ufw_active()   { ufw status | grep -q '^Status: active'; }
nat_ok()       { iptables -t nat -S POSTROUTING | grep -q -- "-o $WAN -j MASQUERADE"; }
fwd_ok()       { [[ "$(sysctl -n net.ipv4.ip_forward 2>/dev/null || true)" == 1 ]]; }
dns_ok()       { getent hosts archive.ubuntu.com >/dev/null; }
lan_ip_ok()    { ip -4 -o addr show dev "$LAN" | grep -q " $NET_GW/"; }

step_verify() {
    local pend=normal
    [[ ${NET_APPLY_DECISION:-now} == reboot ]] && pend=pending
    check critical "Dashboard web server (nginx)"     http_ok http://127.0.0.1/
    check critical "Dashboard API"                    http_ok http://127.0.0.1/api/auth/session
    check critical "Firewall active (UFW)"            ufw_active
    if [[ $ROLE == gateway ]]; then
        check critical "Packet forwarding"            fwd_ok
        check critical "NAT masquerade on $WAN"       nat_ok
        check critical "DNS resolver (Unbound)"       active unbound
        check normal   "Name resolution"              dns_ok
        check "$pend"  "LAN address $NET_GW on $LAN"  lan_ip_ok
        check "$pend"  "DHCP server (Kea)"            active kea-dhcp4-server
        check "$pend"  "IPv6 router adverts (radvd)"  active radvd
    fi
    check normal "Intrusion detection (Suricata)"     active suricata
    command -v cscli >/dev/null 2>&1 && check normal "CrowdSec" active crowdsec
    (( WITH_AGENT )) && check normal "AI assistant (tuxwall-agent)" active tuxwall-agent
    check normal "mDNS reflector (Avahi)"             active avahi-daemon
    return 0
}

###############################################################################
#  Console (first-boot) mode
###############################################################################
stage_console() {
    have_repo || die "--console needs the TuxWall source tree next to this script."
    printf '\n  %sConsole setup%s\n' "$C_BOLD" "$C_0"
    hr
    mkdir -p "$APPLIANCE_DIR" /etc/tuxwall
    q rsync -a --delete --exclude '.git' --exclude '__pycache__' --exclude '*.pyc' \
        --exclude '*.bak' --exclude '*.bak-*' --exclude '*.bak.*' "$REPO_DIR/" "$APPLIANCE_DIR/src/"
    # The console hook runs src/tuxwall-install.sh at the staged tree
    # root; install a runnable copy there regardless of which layout
    # the installer was invoked from (repo root or scripts/).
    install -m 755 "$SELF" "$APPLIANCE_DIR/src/tuxwall-install.sh"
    chown -R root:root "$APPLIANCE_DIR"
    chmod -R go-w "$APPLIANCE_DIR"
    ok "Installer staged in $APPLIANCE_DIR/src"

    local serial unit dropdir
    serial="$(sed -n 's/.*console=\(ttyS[0-9]*\).*/\1/p' /proc/cmdline 2>/dev/null)"
    if [[ -n $serial ]]; then
        unit="serial-getty@$serial.service"
        dropdir="/etc/systemd/system/$unit.d"
        mkdir -p "$dropdir"
        printf '# TuxWall one-time console setup (removed when it starts)\n[Service]\nExecStart=\nExecStart=-/sbin/agetty --autologin root --keep-baud 115200,57600,38400,9600 %%I $TERM\n' \
            >"$dropdir/tuxwall-console-setup.conf"
    else
        unit="getty@tty1.service"
        dropdir="/etc/systemd/system/$unit.d"
        mkdir -p "$dropdir"
        printf '# TuxWall one-time console setup (removed when it starts)\n[Service]\nExecStart=\nExecStart=-/sbin/agetty --autologin root --noclear %%I $TERM\n' \
            >"$dropdir/tuxwall-console-setup.conf"
    fi
    q systemctl daemon-reload

    cat >"$CONSOLE_HOOK" <<'HOOK'
# TuxWall one-time console setup, installed by tuxwall-install.sh --console.
# The installer removes this file (and the autologin) as soon as it starts.
if [ -f /etc/tuxwall/.console-setup-pending ] && [ "$(id -u)" = 0 ] \
   && [ -x /opt/tuxwall-appliance/src/tuxwall-install.sh ]; then
    _tw_console="$(sed -n 's/.*console=\(ttyS[0-9]*\).*/\1/p' /proc/cmdline 2>/dev/null)"
    [ -n "$_tw_console" ] || _tw_console=tty1
    if [ "$(tty 2>/dev/null)" = "/dev/$_tw_console" ]; then
        exec /opt/tuxwall-appliance/src/tuxwall-install.sh --from-console
    fi
    unset _tw_console
fi
HOOK
    chmod 644 "$CONSOLE_HOOK"
    touch "$PENDING"
    ok "One-time autologin armed on ${serial:-tty1} ($unit)"

    if (( DISABLE_MULTIPATH )) && command -v multipathd >/dev/null 2>&1; then
        backup_file /etc/multipath.conf
        mkdir -p /etc/multipath
        printf 'defaults {\n    user_friendly_names no\n}\n' >/etc/multipath.conf
        touch /etc/multipath/bindings
        printf 'blacklist dm_multipath\n' >/etc/modprobe.d/blacklist-multipath.conf
        q systemctl disable --now multipathd.service || true
        ok "multipathd will not claim the system disk"
    fi
    hr
    printf '\n  Reboot (or log in on %s as root). The guided install starts there once;\n' "${serial:-tty1}"
    printf '  the autologin is removed the moment it starts, whatever the outcome.\n'
    printf '  Cancel instead:  sudo rm %s %s %s/tuxwall-console-setup.conf\n\n' "$PENDING" "$CONSOLE_HOOK" "$dropdir"
}

console_disarm() {
    rm -f "$PENDING" "$CONSOLE_HOOK"
    rm -f /etc/systemd/system/getty@tty1.service.d/tuxwall-console-setup.conf \
          /etc/systemd/system/serial-getty@*.service.d/tuxwall-console-setup.conf 2>/dev/null || true
    systemctl daemon-reload >/dev/null 2>&1 || true
    log "console autologin disarmed"
}

###############################################################################
#  Main
###############################################################################
final_summary() {
    local host="${NET_GW:-$(hostname -I 2>/dev/null | awk '{print $1}' || true)}" url
    url="http://$host/"
    [[ "$(/usr/local/sbin/tuxwall-tls decide 2>/dev/null || true)" == active ]] && url="https://$host/"
    printf '\n'
    hr
    if (( CRIT_FAIL )); then
        printf '  %s%sTuxWall installed with %d problem(s) to fix%s\n' "$C_BOLD" "$C_Y" "$CRIT_FAIL" "$C_0"
    else
        printf '  %s%sTuxWall %s is installed%s\n' "$C_BOLD" "$C_G" "$PKG_VERSION" "$C_0"
    fi
    hr
    kv "Dashboard"  "$url"
    kv "First login" "open the dashboard and create the first administrator"
    [[ $url == https://* ]] && kv "Certificate" "trust the router's CA: http://$host/tuxwall-ca.crt (Settings → Security → HTTPS)"
    [[ $ROLE == gateway ]] && kv "Gateway name" "gateway.$DOMAIN"
    kv "Log"        "$LOG"
    [[ -d $BACKUP_DIR ]] && kv "Backups" "$BACKUP_DIR"
    if [[ ${NET_APPLY_DECISION:-} == reboot ]]; then
        printf '\n  %s%sReboot to activate the LAN:%s sudo reboot\n' "$C_BOLD" "$C_Y" "$C_0"
        printf '  %sThen connect a device to %s and open %s%s\n' "$C_DIM" "$LAN" "$url" "$C_0"
    fi
    if (( ${#WARNINGS[@]} )); then
        printf '\n  %sWarnings (%d)%s\n' "$C_Y" "${#WARNINGS[@]}" "$C_0"
        local w
        for w in "${WARNINGS[@]}"; do printf '    %s!%s %s\n' "$C_Y" "$C_0" "$w"; done
    fi
    printf '\n'
}

main() {
    ORIG_ARGS="$*"
    parse_args "$@"
    require_root
    init_log
    acquire_lock
    (( FROM_CONSOLE )) && console_disarm
    banner
    if (( CONSOLE_STAGE )); then
        stage_console
        exit 0
    fi

    preflight
    if (( ! INTERACTIVE )) && (( ! ASSUME_YES )) && (( ! DRY_RUN )); then
        die "No terminal for questions: re-run with --yes and the options you need (see --help)."
    fi
    gather_config
    review
    build_steps

    if (( DRY_RUN )); then
        printf '\n  %sPlan%s %s(dry run: nothing was changed)%s\n' "$C_BOLD" "$C_0" "$C_DIM" "$C_0"
        local i=1 s
        for s in "${STEPS[@]}"; do printf '    %2d. %s\n' "$i" "${s#*|}"; i=$((i + 1)); done
        printf '\n'
        exit 0
    fi

    if (( INTERACTIVE )); then
        confirm "Install TuxWall with these settings?" y || user_abort
    fi
    log "settings: source=$SOURCE role=$ROLE wan=$WAN/$WAN_MODE lan=$LAN net=$NET_CIDR gw=$NET_GW domain=$DOMAIN ula=$ULA kea=$KEA_ACTION radvd=$RADVD_ACTION unbound=$UNBOUND_ACTION apply=$NET_APPLY_DECISION crowdsec=$WITH_CROWDSEC agent=$WITH_AGENT"

    local s
    for s in "${STEPS[@]}"; do
        step "${s#*|}"
        "${s%%|*}"
    done

    if (( CRIT_FAIL == 0 )); then
        touch "$MARKER"
    fi
    final_summary
    if (( FROM_CONSOLE )); then
        local _; ask _ "  Press Enter to finish (a normal login prompt follows)."
    fi
    if (( CRIT_FAIL )); then exit 1; fi
    exit 0
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    main "$@"
fi
