#!/usr/bin/env bash
#
# Fairlead Panel — one-command installer.
#
#   curl -fsSL https://install.fairlead-panel.com/install.sh | sudo bash
#
# install.sh (scripts/bootstrap.sh) fetches this file from the package registry, where every release
# publishes its own: the latest release's, or the one of the version given with --version.
#
# Checks the server is supported, adds the panel's (public, token-free) package
# source, installs the panel + webmail, and starts it. Then you finish setup in
# the browser — the installer prints a one-time setup link that opens the
# panel's first-run wizard.
#
# Other uses:
#   ... | sudo bash -s -- --upgrade          upgrade an existing install to the latest
#   ... | sudo bash -s -- --version 0.2.11   install/upgrade to a specific version
#   ... | sudo bash -s -- --list-versions    list the versions available to install
#   ... | sudo bash -s -- --uninstall        remove the panel (keep user data/databases)
#   ... | sudo bash -s -- --purge            remove everything the panel installed and holds (asks first)
#   ... | sudo bash -s -- --purge --yes      the same, without the question (no terminal needed)
#   ... | sudo bash -s -- --check            run the preflight checks only, change nothing
#   ... | sudo bash -s -- --force            install even if a preflight check fails
#   ... | sudo bash -s -- --help             show detailed help
#
set -euo pipefail
# Everything this script writes is system configuration that apt — and its unprivileged _apt user,
# which reads the keyring — must be able to read, whatever umask the caller's shell had.
umask 022

# ----------------------------------------------------------------------------- config
REGISTRY="https://git.zen-dns.net/api/packages/velvon/debian"
# Fingerprint of the registry's signing key (its primary key, which signs the Release files). The key
# fetched at install time must be exactly this one; anything else is refused, never trusted.
REGISTRY_KEY_FPR="CAF727F27962AE81E9D9CB33C0A37BE57F600796"
KEYRING="/etc/apt/keyrings/fairlead.gpg"
SOURCES_D="/etc/apt/sources.list.d"
SOURCE_LIST="$SOURCES_D/fairlead.list"
# The same entry in deb822 form. apt 3 (Debian 13) offers `apt modernize-sources`, which turns
# fairlead.list into fairlead.sources (keeping the old file as fairlead.list.bak). Either form is ours,
# and there is only ever one of them.
SOURCE_DEB822="$SOURCES_D/fairlead.sources"
PANEL_PKG="fairlead-panel"
WEBMAIL_PKG="fairlead-panel-webmail"
LANG_PREFIX="fairlead-lang-"
PANEL_ROOT="/opt/panel"
PANEL_PORT="8443"
# A "1 GB" server reports roughly 960–1000 MiB in MemTotal (the kernel keeps its share), so the floor
# sits below 1024 to let those through.
MIN_RAM_MB=900
MIN_DISK_GB=5
# How long apt waits for another apt/dpkg run to let go of its lock. A fresh cloud VM runs
# unattended-upgrades / apt-daily on first boot, often for several minutes.
APT_LOCK_WAIT=600

MODE="install"     # install | upgrade | uninstall | purge | check | list
FORCE=0
YES=0
PIN_VERSION=""     # empty = latest; else a specific version (0.2.11 or 0.2.11-063)

# The PHP registry source the panel writes (internal/php) points at the SAME Gitea registry as our
# source, signed-by its own keyring — next to ours apt rejects the repository ("Conflicting values set
# for option Signed-By"). On install/upgrade these are the only panel apt files cleared, and only when
# they point at our registry.
PANEL_PHP_APT_FILES="/etc/apt/keyrings/panel-php.gpg /etc/apt/auth.conf.d/panel-php.conf"

# Every apt artifact the panel adds at runtime: the PHP registry, the MySQL/MariaDB vendor repo, PGDG.
# Removed on uninstall/purge ONLY — an install or upgrade must leave them, the panel still uses them.
PANEL_APT_EXTRA="$SOURCES_D/panel-php.list /etc/apt/keyrings/panel-php.gpg /etc/apt/auth.conf.d/panel-php.conf \
$SOURCES_D/panel-db.list /etc/apt/keyrings/panel-mysql.gpg /etc/apt/keyrings/panel-mariadb.gpg \
$SOURCES_D/panel-postgres.list /etc/apt/keyrings/panel-postgres.gpg"

# ----------------------------------------------------------------------------- output
if [ -t 1 ]; then
  C_B="\033[1m"; C_G="\033[32m"; C_Y="\033[33m"; C_R="\033[31m"; C_D="\033[2m"; C_0="\033[0m"
else
  C_B=""; C_G=""; C_Y=""; C_R=""; C_D=""; C_0=""
fi
say()  { printf "${C_B}==>${C_0} %s\n" "$*"; }
ok()   { printf "${C_G}  ✓${C_0} %s\n" "$*"; }
warn() { printf "${C_Y}  !${C_0} %s\n" "$*" >&2; }
die()  { printf "${C_R}✗ %s${C_0}\n" "$*" >&2; exit 1; }

# Scratch space (the signing key is checked here before it goes anywhere near apt), removed on exit.
WORK_DIR=""
cleanup() { if [ -n "$WORK_DIR" ]; then rm -rf "$WORK_DIR"; fi; }
trap cleanup EXIT
work_dir() { if [ -z "$WORK_DIR" ]; then WORK_DIR="$(mktemp -d)"; fi; }

# A question needs a terminal. Piped from curl, stdin is this script, so ask on /dev/tty — when there
# is one (cloud-init, CI and other unattended runs have none).
have_tty() { { : </dev/tty; } 2>/dev/null; }
confirm_tty() { # confirm_tty <question>: 0 when the answer was yes
  local ans=""
  printf '%s [y/N] ' "$1" >/dev/tty
  read -r ans </dev/tty || ans=""
  case "$ans" in y|Y|yes|Yes|YES) return 0 ;; esac
  return 1
}

# The colour variables hold escape sequences as text (\033[...), which printf's %b turns into the
# real thing — a bare cat would print them literally.
usage() {
  printf '%b' "$(cat <<EOF
${C_B}Fairlead Panel installer${C_0}

A hosting control panel for Ubuntu 24.04 / 26.04 and Debian 13 (amd64). It installs the
panel + webmail from a public package registry and starts them on
https://<server-ip>:${PANEL_PORT}; you finish setup in the browser with the
one-time setup link the installer prints.

${C_B}Usage${C_0}
  curl -fsSL https://install.fairlead-panel.com/install.sh | sudo bash [-- OPTIONS]

${C_B}Options${C_0}
  (none)              Install the panel, or upgrade it if already installed
  --upgrade           Upgrade an existing install to the latest release
  --version <ver>     Install/upgrade to a specific version (e.g. 0.2.11 or
                      0.2.11-063). A downgrade is allowed and reversible.
  --list-versions     List the versions available in the package registry
  --uninstall         Remove the panel, keep user data and databases
  --purge             Remove everything the panel installed and holds, data
                      included. Accounts it only adopted, software that was
                      there before it and your SSH/network settings stay.
                      Asks you to type "purge" first; without a terminal it
                      needs --yes
  -y, --yes           Answer yes to the installer's questions (--purge, and
                      installing on a server that already runs services)
  --check             Run the preflight checks only, change nothing
  --force             Install even if a preflight check fails (at your own
                      risk); with --uninstall/--purge, remove the panel even
                      when its uninstaller reported failed steps
  -h, --help          Show this help

${C_B}Examples${C_0}
  ... | sudo bash                            # install the latest version
  ... | sudo bash -s -- --list-versions      # see what's available
  ... | sudo bash -s -- --version 0.2.10     # install a specific version
  ... | sudo bash -s -- --upgrade            # upgrade to the latest
  ... | sudo bash -s -- --uninstall          # remove, keeping data
EOF
)"
  printf '\n'
}

# ----------------------------------------------------------------------------- args
while [ $# -gt 0 ]; do
  case "$1" in
    --upgrade)       MODE="upgrade" ;;
    --uninstall)     MODE="uninstall" ;;
    --purge)         MODE="purge" ;;
    --check)         MODE="check" ;;
    --list-versions) MODE="list" ;;
    --force)         FORCE=1 ;;
    -y|--yes)        YES=1 ;;
    --version|-V)
      shift; [ $# -gt 0 ] || die "--version needs a value (e.g. --version 0.2.11)"
      PIN_VERSION="$1" ;;
    --version=*)     PIN_VERSION="${1#*=}" ;;
    -h|--help)       usage; exit 0 ;;
    *) die "unknown option: $1 (try --help)" ;;
  esac
  shift
done

# A pinned version must look like X.Y.Z or X.Y.Z-BBB — reject anything else so it
# can never smuggle extra tokens into the apt command.
if [ -n "$PIN_VERSION" ] && ! printf '%s' "$PIN_VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9]+)?$'; then
  die "invalid --version '$PIN_VERSION' (expected e.g. 0.2.11 or 0.2.11-063)"
fi

# A failed preflight check aborts — unless --force turns it into a warning.
require() { # require <condition-desc> <ok?0/1>
  if [ "$2" = "1" ]; then ok "$1"; return 0; fi
  if [ "$FORCE" = "1" ]; then warn "$1 — ignored (--force)"; return 0; fi
  die "$1 — not met. Re-run with --force to override at your own risk."
}

# ----------------------------------------------------------------------------- detect
SUITE=""; OS_LABEL=""
detect_os() {
  [ -r /etc/os-release ] || die "cannot read /etc/os-release — unsupported system"
  # shellcheck disable=SC1091
  . /etc/os-release
  OS_LABEL="${PRETTY_NAME:-$ID $VERSION_ID}"
  case "${ID:-}:${VERSION_ID:-}" in
    ubuntu:24.04) SUITE="noble" ;;
    ubuntu:26.04) SUITE="resolute" ;;
    debian:13)    SUITE="trixie" ;;
    *)            SUITE="" ;;
  esac
}

# ----------------------------------------------------------------------------- preflight
preflight() {
  say "Checking this server"
  require "running as root" "$([ "$(id -u)" = "0" ] && echo 1 || echo 0)"

  local arch; arch="$(uname -m)"
  require "architecture is amd64 (found $arch)" "$([ "$arch" = "x86_64" ] && echo 1 || echo 0)"

  detect_os
  require "supported OS: Ubuntu 24.04, Ubuntu 26.04 or Debian 13 (found $OS_LABEL)" "$([ -n "$SUITE" ] && echo 1 || echo 0)"
  [ -n "$SUITE" ] && ok "package suite: $SUITE"
  # --force with an unknown OS: fall back to the closest suite so we can still try.
  [ -z "$SUITE" ] && SUITE="noble"

  require "systemd is the init system" "$([ -d /run/systemd/system ] && echo 1 || echo 0)"

  local ram_mb; ram_mb=$(( $(awk '/MemTotal/{print $2}' /proc/meminfo) / 1024 ))
  require "at least 1 GB of RAM (found ${ram_mb} MiB usable; a 1 GB server shows a little less, so ${MIN_RAM_MB} MiB is the floor)" \
    "$([ "$ram_mb" -ge "$MIN_RAM_MB" ] && echo 1 || echo 0)"
  if [ "$ram_mb" -ge "$MIN_RAM_MB" ] && [ "$ram_mb" -lt 1900 ]; then
    warn "under 2 GB of RAM: enough for the panel and websites; a full mail stack with antivirus (ClamAV) wants 2 GB or more, or swap"
  fi

  local disk_gb; disk_gb=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
  require "at least ${MIN_DISK_GB} GiB free on / (found ${disk_gb} GiB)" "$([ "${disk_gb:-0}" -ge "$MIN_DISK_GB" ] && echo 1 || echo 0)"

  # Port 8443 in use by something that isn't our panel? Warn, don't block — the
  # admin may intend to front the panel differently.
  if command -v ss >/dev/null 2>&1 && ss -ltnH 2>/dev/null | awk '{print $4}' | grep -qE "[:.]${PANEL_PORT}\$"; then
    if ! systemctl is-active --quiet panel.service 2>/dev/null; then
      warn "port ${PANEL_PORT} is already in use — the panel may fail to bind"
    fi
  fi

  check_container
  if ! panel_installed; then
    check_root_password
    check_existing
  fi
  # The registry check needs curl; without it, it runs once ensure_tools has installed it.
  if command -v curl >/dev/null 2>&1; then check_registry; fi
}

# check_container warns (never fails) when this is a container rather than a VM or bare metal: the
# panel drives the kernel directly in ways a container usually isn't allowed to.
check_container() {
  local virt=""
  if command -v systemd-detect-virt >/dev/null 2>&1; then
    virt="$(systemd-detect-virt -c 2>/dev/null || true)"
  fi
  if [ "$virt" = "none" ]; then virt=""; fi
  if [ -z "$virt" ] && [ -f /.dockerenv ]; then virt="docker"; fi
  if [ -z "$virt" ] && [ -d /proc/vz ] && [ ! -d /proc/bc ]; then virt="openvz"; fi
  if [ -z "$virt" ]; then
    ok "not a container"
    return 0
  fi
  warn "this is a container ($virt), not a VM or bare metal. Here these may not work: the nftables firewall and its XDP filtering, jailed shells (they need bind mounts), disk quotas, and kernel (sysctl) tuning. A KVM VM or a dedicated server is the supported setup."
}

# check_root_password notes when root can't log in with a password (locked or empty — the default on
# most cloud images). That doesn't block anything: the way in is the one-time setup link this script
# prints at the end, and the setup wizard asks for the administrator password.
ROOT_PW_UNUSABLE=0
check_root_password() {
  local st; st="$(passwd -S root 2>/dev/null | awk '{print $2}' || true)"
  case "$st" in
    L|LK|NP)
      ROOT_PW_UNUSABLE=1
      warn "root has no usable password (passwd -S: $st) — that's fine: open the one-time setup link printed at the end; the setup wizard asks you to set the administrator password"
      ;;
  esac
  return 0
}

# Services an existing hosting setup runs. The panel installs and configures its own web, mail,
# database, DNS and FTP servers, so finding them running means this isn't a fresh server.
EXISTING_SVCS="nginx apache2 httpd lighttpd caddy lsws haproxy traefik varnish \
postfix exim4 sendmail dovecot courier-imap \
mysql mariadb mysqld postgresql \
named bind9 pdns \
proftpd pure-ftpd vsftpd"
# Other hosting control panels, by a directory each one installs (<name>:<path>).
OTHER_PANELS="cPanel:/usr/local/cpanel Plesk:/usr/local/psa Plesk:/opt/psa ISPmanager:/usr/local/mgr5 \
HestiaCP:/usr/local/hestia VestaCP:/usr/local/vesta CyberPanel:/usr/local/CyberCP aaPanel:/www/server/panel \
Virtualmin:/etc/webmin/virtual-server Webmin:/etc/webmin Webmin:/usr/share/webmin \
ISPConfig:/usr/local/ispconfig FASTPANEL:/usr/local/fastpanel2"

# check_existing warns about services and other control panels already on this server, and asks
# before going on (--force or --yes answers for you; with no terminal to ask, it stops).
check_existing() {
  local s id seen=" " svcs="" panels="" e name path
  for s in $EXISTING_SVCS; do
    systemctl is-active --quiet "$s.service" 2>/dev/null || continue
    # One service often answers to several names (mariadb = mysql = mysqld): report it once.
    id="$(systemctl show -p Id --value "$s.service" 2>/dev/null || true)"
    id="${id%.service}"; [ -n "$id" ] || id="$s"
    case "$seen" in *" $id "*) continue ;; esac
    seen="$seen$id "; svcs="$svcs $id"
  done
  for e in $OTHER_PANELS; do
    name="${e%%:*}"; path="${e#*:}"
    [ -e "$path" ] || continue
    case " $panels " in *" $name "*) continue ;; esac
    panels="$panels $name"
  done
  if [ -z "$svcs$panels" ]; then
    ok "a fresh server: no web, mail, database or DNS server and no other control panel running"
    return 0
  fi
  if [ -n "$panels" ]; then
    warn "another control panel is installed:$panels — two panels managing one server overwrite each other's configuration"
  fi
  if [ -n "$svcs" ]; then
    warn "already running:$svcs — the panel configures web, mail, database and DNS servers itself and can change how these run"
  fi
  warn "Fairlead Panel is meant for a fresh server."
  if [ "$MODE" = "check" ]; then return 0; fi
  if [ "$FORCE" = "1" ] || [ "$YES" = "1" ]; then
    warn "continuing anyway (--force/--yes)"
    return 0
  fi
  if have_tty; then
    if confirm_tty "Install on this server anyway?"; then return 0; fi
    die "stopped — nothing was changed"
  fi
  die "this isn't a fresh server and there is no terminal to ask — re-run with --yes (or --force) to install anyway"
}

# check_registry makes sure the package registry can be reached before anything is changed. It has no
# IPv6 address (no AAAA record), so an IPv6-only server can't reach it — unless NAT64/DNS64 bridges.
REGISTRY_CHECKED=0
check_registry() {
  if [ "$REGISTRY_CHECKED" = "1" ]; then return 0; fi
  local host; host="${REGISTRY#*://}"; host="${host%%/*}"
  if curl -4 -fsS --max-time 20 -o /dev/null "$REGISTRY/repository.key" 2>/dev/null; then
    ok "package registry reachable ($host)"
    REGISTRY_CHECKED=1
    return 0
  fi
  if curl -fsS --max-time 20 -o /dev/null "$REGISTRY/repository.key" 2>/dev/null; then
    ok "package registry reachable ($host, through IPv6/NAT64)"
    REGISTRY_CHECKED=1
    return 0
  fi
  local v4=""
  if command -v ip >/dev/null 2>&1; then v4="$(ip -4 route show default 2>/dev/null || true)"; fi
  if [ -z "$v4" ]; then
    die "this server has no IPv4 connectivity (no IPv4 default route), and the package registry $host is reachable over IPv4 only — it has no IPv6 address. Give the server an IPv4 address (or NAT64/DNS64) and run the installer again."
  fi
  die "cannot reach the package registry https://$host — check DNS, the firewall and outbound HTTPS (port 443)"
}

# not_inside_panel refuses to run from inside the panel's own service — its web terminal. Restarting
# or removing the panel ends every process it started, so this script would be killed half-way, with
# the panel stopped. Run it over SSH (or upgrade from Administration → Updates).
not_inside_panel() {
  if grep -qE '/panel(-webmail)?\.service(/|$)' /proc/self/cgroup 2>/dev/null; then
    die "this is running inside the panel's own service (its web terminal) — the panel is stopped or restarted during this, which would end the installer half-way. Run it over SSH instead, or upgrade from Administration → Updates."
  fi
}

# ----------------------------------------------------------------------------- apt
# apt_get runs apt-get unattended, waiting up to APT_LOCK_WAIT for another apt/dpkg run to let go of
# its lock. stdin is /dev/null: piped from curl, stdin is the rest of this script.
apt_get() { DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout="$APT_LOCK_WAIT" "$@" </dev/null; }

# apt_busy: is another package run going on? (The ever-running unattended-upgrade-SHUTDOWN helper is
# not one — it's matched out by looking for the real run's command line.)
apt_busy() {
  command -v pgrep >/dev/null 2>&1 || return 1
  pgrep -x 'apt|apt-get|aptitude|dpkg' >/dev/null 2>&1 && return 0
  pgrep -f '/usr/bin/unattended-upgrade|/usr/lib/apt/apt.systemd.daily' >/dev/null 2>&1
}

# wait_apt_idle waits (up to APT_LOCK_WAIT) while another package run is going on, saying so.
wait_apt_idle() {
  apt_busy || return 0
  say "Waiting for apt: another package run is in progress (on a fresh server, usually the first-boot unattended-upgrades) — up to $((APT_LOCK_WAIT / 60)) minutes"
  local waited=0
  while apt_busy && [ "$waited" -lt "$APT_LOCK_WAIT" ]; do
    sleep 5
    waited=$((waited + 5))
    if [ $((waited % 60)) -eq 0 ]; then printf "${C_D}    still waiting for apt (%ss)…${C_0}\n" "$waited"; fi
  done
  if apt_busy; then
    warn "apt is still busy after ${APT_LOCK_WAIT}s — going on; apt itself waits for its lock"
  else
    ok "apt is free"
  fi
}

# apt_update runs apt-get update with retries: DPkg::Lock::Timeout covers dpkg's lock, not the lock on
# the package lists that `update` takes, and a fresh VM's first-boot apt run holds it for a while.
apt_update() {
  local try delay=10
  wait_apt_idle
  for try in 1 2 3 4 5; do
    if apt_get update "$@"; then return 0; fi
    [ "$try" = "5" ] && break
    warn "apt-get update failed (try $try of 5) — apt may be busy with another run; waiting for apt, retrying in ${delay}s"
    sleep "$delay"
    delay=$((delay * 2))
  done
  return 1
}

ensure_tools() {
  local missing=""
  command -v curl >/dev/null 2>&1 || missing="$missing curl"
  command -v gpg  >/dev/null 2>&1 || missing="$missing gpg"
  [ -e /etc/ssl/certs/ca-certificates.crt ] || missing="$missing ca-certificates"
  if [ -n "$missing" ]; then
    say "Installing prerequisites:$missing"
    apt_update -qq || die "apt-get update failed — check this server's package sources and network"
    # shellcheck disable=SC2086
    apt_get install -y --no-install-recommends $missing || die "could not install:$missing"
  fi
}

# ----------------------------------------------------------------------------- apt source
# install_key fetches the registry's signing key, checks it is exactly the pinned key, and installs it
# world-readable (apt verifies signatures as the unprivileged _apt user). The check runs in a scratch
# GnuPG home — root's own keyring is never touched.
install_key() {
  work_dir
  local asc="$WORK_DIR/repository.key" home="$WORK_DIR/gnupg" fprs
  install -d -m 0700 "$home"
  curl -fsSL --retry 3 --max-time 60 "$REGISTRY/repository.key" -o "$asc" \
    || die "could not fetch the repository signing key from $REGISTRY"
  fprs="$(gpg --batch --quiet --homedir "$home" --with-colons --show-keys "$asc" 2>/dev/null \
    | awk -F: '$1=="pub"{want=1; next} $1=="fpr" && want {print $10; want=0}' || true)"
  if [ "$fprs" != "$REGISTRY_KEY_FPR" ]; then
    die "the registry's signing key is not the expected one (expected $REGISTRY_KEY_FPR, got: $(printf '%s' "${fprs:-nothing}" | tr '\n' ' ')) — refusing to trust it. If the key was rotated, use the current installer; otherwise the connection may be tampered with."
  fi
  gpg --batch --quiet --homedir "$home" --yes --dearmor -o "$WORK_DIR/fairlead.gpg" "$asc" \
    || die "could not convert the repository signing key"
  install -d -m 0755 /etc/apt/keyrings
  install -m 0644 "$WORK_DIR/fairlead.gpg" "$KEYRING"
  ok "signing key verified ($REGISTRY_KEY_FPR)"
}

# src_entries prints the lines of an apt source file that name repositories: the "deb" lines of a
# one-line .list, the "URIs:" fields of a deb822 .sources.
src_entries() {
  case "$1" in
    *.list)    grep -E '^[[:space:]]*deb(-src)?[[:space:]]' "$1" 2>/dev/null || true ;;
    *.sources) grep -iE '^[[:space:]]*URIs:' "$1" 2>/dev/null || true ;;
  esac
}
# src_serves: does this apt source file name our registry?
src_serves() { case "$(src_entries "$1")" in *"$REGISTRY"*) return 0 ;; esac; return 1; }
# src_only_ours: does it name nothing BUT our registry (so it can be rewritten or set aside whole)?
src_only_ours() {
  local line
  while IFS= read -r line; do
    case "$line" in *"$REGISTRY"*) ;; *) return 1 ;; esac
  done <<EOF
$(src_entries "$1")
EOF
  return 0
}

# canonical_source is the file that carries our entry: the deb822 form when the admin converted the
# one-line file (fairlead.sources, or another .sources naming only our registry), else fairlead.list.
canonical_source() {
  local f
  if [ -f "$SOURCE_DEB822" ]; then printf '%s' "$SOURCE_DEB822"; return 0; fi
  for f in "$SOURCES_D"/*.sources; do
    [ -f "$f" ] || continue
    case "$f" in "$SOURCES_D"/panel-php.sources) continue ;; esac
    if src_serves "$f" && src_only_ours "$f"; then printf '%s' "$f"; return 0; fi
  done
  printf '%s' "$SOURCE_LIST"
}

# settle_sources leaves <canon> the ONLY apt entry for our registry. Two entries for one repository
# with different Signed-By make apt reject it outright, so: our other form goes, the panel's PHP
# source for this same registry goes (the panel reuses ours), and a foreign file naming only our
# registry is set aside as *.disabled (apt ignores that suffix). A file mixing our registry with other
# repositories is the admin's to edit — the script says so and stops rather than touch it.
settle_sources() {
  local canon="$1" f
  for f in "$SOURCES_D"/*.list "$SOURCES_D"/*.sources; do
    [ -f "$f" ] && [ "$f" != "$canon" ] || continue
    src_serves "$f" || continue
    case "$f" in
      "$SOURCE_LIST"|"$SOURCE_DEB822")
        rm -f "$f"
        ok "removed $f (the entry lives in $canon)"
        ;;
      "$SOURCES_D"/panel-php.list|"$SOURCES_D"/panel-php.sources)
        # shellcheck disable=SC2086
        rm -f "$f" $PANEL_PHP_APT_FILES
        ok "removed $f — the panel's PHP packages come from this same source"
        ;;
      *)
        if src_only_ours "$f"; then
          mv -f "$f" "$f.disabled"
          warn "set $f aside as $f.disabled — it named the Fairlead registry a second time"
        else
          die "$f names the Fairlead registry next to other repositories — remove the line for $REGISTRY from it and run the installer again (two entries for one repository with different keys make apt reject it)"
        fi
        ;;
    esac
  done
  case "$(grep -E '^[[:space:]]*deb[[:space:]]' /etc/apt/sources.list 2>/dev/null || true)" in
    *"$REGISTRY"*) die "/etc/apt/sources.list names the Fairlead registry — remove that line and run the installer again (two entries for one repository with different keys make apt reject it)" ;;
  esac
  return 0
}

# write_source writes our entry into <file>, in that file's format.
write_source() {
  local f="$1"
  case "$f" in
    *.sources) printf 'Types: deb\nURIs: %s\nSuites: %s\nComponents: main\nSigned-By: %s\n' "$REGISTRY" "$SUITE" "$KEYRING" > "$f" ;;
    *)         printf 'deb [signed-by=%s] %s %s main\n' "$KEYRING" "$REGISTRY" "$SUITE" > "$f" ;;
  esac
  chmod 0644 "$f"
}

add_source() {
  say "Adding the Fairlead package source ($SUITE, public — no credentials)"
  install_key
  local canon; canon="$(canonical_source)"
  settle_sources "$canon"
  write_source "$canon"
  ok "wrote $canon"
  # Refresh ONLY our source, so a stale unrelated repo elsewhere can't fail the run.
  # sourcelist is relative to Dir::Etc (/etc/apt) and parsed by its extension (.list or .sources);
  # sourceparts="-" tells apt to read no sources.list.d parts.
  apt_update \
    -o Dir::Etc::sourcelist="sources.list.d/$(basename "$canon")" \
    -o Dir::Etc::sourceparts="-" \
    -o APT::Get::List-Cleanup="0" -qq \
    || die "apt could not read the Fairlead source — check network/DNS to git.zen-dns.net"
}

# apt_teardown_files lists every apt file the installer or the panel may have written, in both forms:
# the one-line .list, the deb822 .sources `apt modernize-sources` makes of it, and the .list.bak it keeps.
apt_teardown_files() {
  local f
  # shellcheck disable=SC2086
  for f in "$SOURCE_LIST" "$KEYRING" /etc/apt/auth.conf.d/fairlead.conf $PANEL_APT_EXTRA; do
    printf '%s\n' "$f"
    case "$f" in *.list) printf '%s\n%s\n' "${f%.list}.sources" "$f.bak" ;; esac
  done
}

# remove_panel_apt removes all of those, plus a deb822 file under another name that names only our
# registry (ours, by the rule in canonical_source). Uninstall/purge only.
remove_panel_apt() {
  local f
  for f in $(apt_teardown_files); do rm -f "$f"; done
  for f in "$SOURCES_D"/*.sources; do
    if [ -f "$f" ] && src_serves "$f" && src_only_ours "$f"; then rm -f "$f"; fi
  done
  return 0
}

# ----------------------------------------------------------------------------- packages
pkg_installed() { dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -q "install ok installed"; }
panel_installed() { pkg_installed "$PANEL_PKG"; }
pkg_version() { dpkg-query -W -f='${Version}' "$1" 2>/dev/null || true; }
candidate_version() { apt-cache policy "$1" 2>/dev/null | awk '/Candidate:/ {print $2; exit}' || true; }

primary_ip() {
  local ip; ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
  if [ -z "$ip" ] && command -v ip >/dev/null 2>&1; then
    ip="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") {print $(i + 1); exit}}' || true)"
  fi
  printf '%s' "$ip"
}

# available_versions lists the panel versions apt can see (needs add_source first),
# newest first. Format is X.Y.Z-BBB.
available_versions() { apt-cache madison "$PANEL_PKG" 2>/dev/null | awk '{print $3}' | sort -Vr; }

# resolve_version turns a pin (full or partial) into a concrete registry version, or
# empty if there's no match. A full "X.Y.Z-BBB" matches exactly; a partial "X.Y.Z"
# resolves to the highest build of that release.
resolve_version() {
  local want="$1" all
  all="$(available_versions || true)"
  if printf '%s\n' "$want" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+-[0-9]+$'; then
    if printf '%s\n' "$all" | grep -qxF "$want"; then echo "$want"; fi
    return 0
  fi
  printf '%s\n' "$all" | grep -E "^${want//./\\.}-[0-9]+$" | head -1 || true
}

# pinned_version resolves --version against the registry (empty without a pin). Run it as
# `v="$(pinned_version)" || exit 1` — it dies with a helpful message if the version isn't there.
pinned_version() {
  [ -n "$PIN_VERSION" ] || return 0
  local full; full="$(resolve_version "$PIN_VERSION")"
  [ -n "$full" ] || die "version '$PIN_VERSION' is not in the registry — run --list-versions to see what's available"
  printf '%s' "$full"
}

# Language codes are package-name material: keep only what can be one (and never English, which is
# built into the binary, not a pack).
lang_filter() { grep -E '^[a-z0-9][a-z0-9.+-]*$' | grep -vxF en | sort -u || true; }

# registry_lang_codes: every UI language the registry offers as a pack.
registry_lang_codes() { apt-cache pkgnames "$LANG_PREFIX" 2>/dev/null | sed "s/^$LANG_PREFIX//" | lang_filter || true; }

# installed_lang_codes: the UI languages this panel USES — the same rule as the panel's own self-update
# (internal/server/selfupdate.go): the union of the language packs dpkg has and any catalogue on disk
# that isn't dpkg-tracked yet (installing its pack adopts it, so it stays current from then on).
installed_lang_codes() {
  {
    dpkg-query -W -f='${Package} ${db:Status-Abbrev}\n' "${LANG_PREFIX}*" 2>/dev/null \
      | awk -v p="$LANG_PREFIX" '$2 ~ /^i/ {sub("^" p, "", $1); print $1}' || true
    for f in "$PANEL_ROOT"/lang/*.json; do [ -e "$f" ] && basename "$f" .json; done
  } | lang_filter || true
}

# lang_pkgs <version> <code>...: the apt arguments that bring each language pack to <version>, the
# panel's own version. A pack missing from the registry at that version is reported and left as it is.
lang_pkgs() {
  local want="$1" c vers out=""
  shift
  for c in "$@"; do
    vers="$(apt-cache madison "$LANG_PREFIX$c" 2>/dev/null | awk '{print $3}' || true)"
    case "
$vers
" in
      *"
$want
"*) out="$out $LANG_PREFIX$c=$want" ;;
      *) warn "language pack $LANG_PREFIX$c $want is not in the registry — left as it is" ;;
    esac
  done
  printf '%s' "$out"
}

# has_inst: does `apt-get -s` output (in $1) install, upgrade or downgrade anything?
has_inst() { case "
$1" in *"
Inst "*) return 0 ;; esac; return 1; }

# ----------------------------------------------------------------------------- start + way in
# start_panel makes sure the panel is enabled at boot and running, then waits until it answers on its
# port. Every path that leaves an installed panel behind ends here — including a re-run after a first
# start that failed, which goes through the upgrade path. <hint> is added to the failure message.
start_panel() {
  local hint="${1:-}" code="000" url
  say "Starting the panel"
  systemctl daemon-reload 2>/dev/null || true
  systemctl enable panel.service >/dev/null 2>&1 || warn "could not enable panel.service at boot"
  if ! systemctl is-active --quiet panel.service; then
    systemctl reset-failed panel.service 2>/dev/null || true
    systemctl start panel.service || true
  fi
  for _ in $(seq 1 30); do
    # Read each time: on a first start the panel writes its config moments after it starts.
    url="$(panel_login_url)"
    code="$(curl -sk -o /dev/null -w '%{http_code}' --max-time 3 "$url" 2>/dev/null || true)"
    [ "${code:-000}" != "000" ] && break
    sleep 1
  done
  if ! systemctl is-active --quiet panel.service; then
    die "the panel service did not start — see: journalctl -u panel.service -n 50${hint:+. $hint}"
  fi
  if [ "${code:-000}" = "000" ]; then
    warn "the panel runs but doesn't answer on ${url%/app/login} yet — if that persists, see: journalctl -u panel.service -n 50"
  else
    ok "the panel is running and answering on ${url%/app/login}"
  fi
}

# panel_login_url is where this server's panel answers its login page: the [panel] listen address of
# its config (loopback when it listens on every address), else the default port on loopback.
panel_login_url() {
  local listen host port
  listen="$(awk -F'"' '/^[[:space:]]*\[/ {sec = $0; gsub(/[[:space:]]/, "", sec)}
    sec == "[panel]" && /^[[:space:]]*listen[[:space:]]*=/ {print $2; exit}' \
    "$PANEL_ROOT/etc/config.toml" 2>/dev/null || true)"
  port="${listen##*:}"; host="${listen%:*}"
  case "$port" in ''|*[!0-9]*) port="$PANEL_PORT" ;; esac
  case "$host" in ''|0.0.0.0|::|'[::]'|*[!0-9A-Za-z.:\[\]-]*) host="127.0.0.1" ;; esac
  printf 'https://%s:%s/app/login' "$host" "$port"
}

# setup_link asks the panel for its one-time setup URL: 0 = SETUP_LINK holds it, 3 = first-run setup
# is already complete, 2 = this panel version has no --setup-link, 1 = no answer.
SETUP_LINK=""
setup_link() {
  local out rc
  [ -x "$PANEL_ROOT/panel" ] || return 1
  for _ in 1 2 3 4 5; do
    rc=0
    out="$("$PANEL_ROOT/panel" --setup-link </dev/null 2>/dev/null)" || rc=$?
    case "$rc" in
      0) SETUP_LINK="$(printf '%s\n' "$out" | tr -d '\r' | sed -n '1p')"
         if [ -n "$SETUP_LINK" ]; then return 0; fi ;;
      2|3) return "$rc" ;;
    esac
    sleep 2
  done
  return 1
}

# show_way_in tells how to get into the panel. While first-run setup is open, that is the one-time
# setup link (valid 1 hour, single use) — root password or not. <fresh> is 1 right after an install.
show_way_in() {
  local fresh="$1" rc=0 ip
  setup_link || rc=$?
  if [ "$rc" = "0" ]; then
    if [ "$fresh" = "1" ]; then
      printf "\n${C_B}Finish setup in your browser — open this one-time link:${C_0}\n\n"
    else
      printf "\n${C_B}First-run setup isn't finished yet — continue with this one-time link:${C_0}\n\n"
    fi
    printf "    ${C_B}%s${C_0}\n\n" "$SETUP_LINK"
    printf "${C_D}It works once and expires in 1 hour. The wizard asks you to set the administrator password,\n"
    printf "then walks through hostname, IPs, stacks and SSL. A new link (replacing this one):  sudo %s/panel --setup-link\n" "$PANEL_ROOT"
    printf "The panel uses a self-signed certificate until the wizard issues one — expect a browser warning.${C_0}\n"
    return 0
  fi
  [ "$fresh" = "1" ] || return 0
  ip="$(primary_ip)"
  printf "\n${C_B}Open:${C_0}  https://%s:%s\n" "${ip:-<server-ip>}" "$PANEL_PORT"
  if [ "$rc" = "3" ]; then
    printf "${C_B}Log in:${C_0} with the administrator account set up earlier — first-run setup was already completed here.\n"
    return 0
  fi
  printf "${C_B}Log in:${C_0} user ${C_B}root${C_0} with this server's root password.\n"
  if [ "$ROOT_PW_UNUSABLE" = "1" ]; then
    warn "root has no usable password and this panel version prints no setup link — set one first:  sudo passwd root"
  fi
  printf "${C_D}First login starts the setup wizard (hostname, IPs, stacks, SSL).\n"
  printf "The panel uses a self-signed cert until you issue one in the wizard — expect a browser warning.${C_0}\n"
}

# ----------------------------------------------------------------------------- list versions
do_list_versions() {
  add_source
  say "Versions available for $OS_LABEL ($SUITE):"
  local vers; vers="$(available_versions || true)"
  [ -n "$vers" ] || die "no versions found — check network/DNS to the package registry"
  printf '%s\n' "$vers" | sed 's/^/  /'
  printf "\n${C_D}Install one with:  ... | sudo bash -s -- --version X.Y.Z${C_0}\n"
}

# ----------------------------------------------------------------------------- install
do_install() {
  if panel_installed; then
    say "The panel is already installed — upgrading instead"
    do_upgrade
    return
  fi
  add_source
  local target pkgs langs codes
  target="$(pinned_version)" || exit 1
  if [ -n "$target" ]; then
    say "Pinning to version $target"
    pkgs="$PANEL_PKG=$target $WEBMAIL_PKG=$target"
  else
    pkgs="$PANEL_PKG $WEBMAIL_PKG"
  fi
  say "Installing $PANEL_PKG + $WEBMAIL_PKG"
  # shellcheck disable=SC2086
  apt_get install -y --no-install-recommends --allow-downgrades $pkgs \
    || die "installing the panel packages failed — see the apt output above"
  # Translation catalogues, dpkg-tracked so the panel's self-update keeps them in lockstep with the
  # binary — at the version just installed (a --version pin pins them too). English is embedded; the
  # others ship as packs. Best-effort: a missing language never blocks the install. The panel isn't
  # running yet, so it reads them on its first start.
  target="$(pkg_version "$PANEL_PKG")"
  codes="$(registry_lang_codes)"
  if [ -n "$codes" ]; then
    say "Installing language catalogues ($target)"
    # shellcheck disable=SC2086
    langs="$(lang_pkgs "$target" $codes)"
    if [ -n "$langs" ]; then
      # shellcheck disable=SC2086
      apt_get install -y --no-install-recommends --allow-downgrades $langs \
        || warn "the language packs didn't install — the panel works in English; add them later from Administration → Settings → Languages"
    fi
  fi
  start_panel
  printf '\n'
  ok "Fairlead Panel is installed and running."
  show_way_in 1
}

# ----------------------------------------------------------------------------- upgrade
do_upgrade() {
  panel_installed || die "the panel isn't installed yet — run without --upgrade first"
  add_source
  local prev target pkgs langs sim codes webmail_on=0
  prev="$(pkg_version "$PANEL_PKG")"
  target="$(pinned_version)" || exit 1
  if [ -n "$target" ]; then
    say "Switching to version $target (installed: $prev)"
    pkgs="$PANEL_PKG=$target $WEBMAIL_PKG=$target"
  else
    target="$(candidate_version "$PANEL_PKG")"
    if [ -z "$target" ] || [ "$target" = "(none)" ]; then
      die "the registry offers no $PANEL_PKG for $SUITE — see --list-versions"
    fi
    say "Upgrading to the latest release ($target; installed: $prev)"
    pkgs="$PANEL_PKG"
    if pkg_installed "$WEBMAIL_PKG"; then pkgs="$pkgs $WEBMAIL_PKG"; fi
  fi
  # The UI languages move WITH the panel, in the same apt transaction and to the same version — the
  # rule the panel's own self-update follows — or the UI runs on stale catalogues.
  codes="$(installed_lang_codes)"
  langs=""
  if [ -n "$codes" ]; then
    # shellcheck disable=SC2086
    langs="$(lang_pkgs "$target" $codes)"
  fi

  # Nothing to change (a re-run, say after a first start that failed)? Then only make sure the panel
  # runs — no needless restart. If the dry run itself fails, the real run below shows why.
  # shellcheck disable=SC2086
  if sim="$(apt_get install -s --allow-downgrades $pkgs $langs 2>&1)" && ! has_inst "$sim"; then
    ok "already at $target — nothing to upgrade"
    start_panel
    show_way_in 0
    return 0
  fi
  [ -z "$langs" ] || say "Language packs move with it:$langs"
  # Download first, so the panel is down only while dpkg unpacks.
  # shellcheck disable=SC2086
  apt_get install -y -d --allow-downgrades $pkgs $langs \
    || die "could not download the packages — nothing was changed"
  # The panel (and webmail) stop for the swap: a .deb's postinst restarts its RUNNING service as soon
  # as it is configured — possibly before dpkg unpacks the new language catalogues, which are read at
  # startup. Stopped, they start once, on the finished set.
  if systemctl is-active --quiet panel-webmail.service; then webmail_on=1; fi
  systemctl stop panel.service 2>/dev/null || true
  if [ "$webmail_on" = "1" ]; then systemctl stop panel-webmail.service 2>/dev/null || true; fi
  # shellcheck disable=SC2086
  if ! apt_get install -y --no-install-recommends --allow-downgrades $pkgs $langs; then
    warn "the upgrade failed — starting the panel again on what is installed"
    if [ "$webmail_on" = "1" ]; then systemctl start panel-webmail.service 2>/dev/null || true; fi
    start_panel
    die "upgrade failed — see the apt output above (installed now: $PANEL_PKG $(pkg_version "$PANEL_PKG"))"
  fi
  if [ "$webmail_on" = "1" ]; then
    systemctl start panel-webmail.service \
      || warn "the webmail service didn't start — see: journalctl -u panel-webmail.service -n 50"
  fi
  start_panel "To go back: ... | sudo bash -s -- --version $prev"
  ok "Done: $PANEL_PKG $prev → $(pkg_version "$PANEL_PKG")."
  show_way_in 0
}

# ----------------------------------------------------------------------------- uninstall / purge
# The teardown belongs to the panel's own uninstaller (`panel --uninstall [--purge --yes]`,
# internal/uninstall). It reads the install ledger and removes exactly what the panel installed —
# never a package or data directory that was there before it, never an account the panel only adopted
# (state/accounts/<user>.toml says `imported = true`), never the administrator's SSH or network
# settings — and ends with a Removed / Kept / Notes / Failed summary, exiting non-zero if a step failed.
# It refuses to run while the panel service is active, so the panel is stopped first.
#
# After it, this script removes only what is the panel package's own: the panel, webmail and language
# packages (the running binary can't remove its own package), a panel build (fairlead-*, panel-php*)
# still installed, the panel's apt source and key in every form, its PAM file and units, and — on
# --purge — /opt/panel. When the binary is missing (a broken install) a fallback sweep stands in, held
# to the same limits by what the panel's state records.

# The panel's own unit links (its packages' prerm drops them; removed here too if a package is gone).
PANEL_UNIT_FILES="/etc/systemd/system/panel.service /etc/systemd/system/panel-webmail.service"

# The panel's system integration outside any ledger entry — what internal/uninstall removes in both
# modes (the fallback sweep removes it in its place). Globs are expanded against these absolute paths.
PANEL_INTEGRATION="/etc/systemd/system/panel-net.service /etc/systemd/system/panel-reboot.timer \
/etc/systemd/system/panel-reboot.service /etc/sysctl.d/99-panel-core.conf /etc/sysctl.d/99-panel-net.conf \
/etc/modules-load.d/panel-bbr.conf /etc/systemd/journald.conf.d/99-panel.conf /etc/tmpfiles.d/fairlead-*.conf \
/etc/iproute2/rt_tables.d/panel.conf /usr/local/sbin/panel-net-apply.sh /etc/cloud/cloud.cfg.d/99-fairlead.cfg \
/etc/apt/apt.conf.d/21panel-auto-upgrades /etc/apt/apt.conf.d/52panel-unattended \
/etc/apt/preferences.d/98-panel-frozen-*.pref /etc/apt/preferences.d/99-panel-clone.pref \
/etc/systemd/system/*.service.d/fairlead.conf /etc/systemd/system/*.service.d/10-fairlead.conf \
/etc/systemd/system/*.service.d/10-panel-order.conf /etc/systemd/system/*.service.d/10-panel-db.conf \
/etc/systemd/system/*.service.d/panel-hardening.conf /etc/systemd/system/apt-daily-upgrade.timer.d/10-panel.conf \
/etc/pam.d/panel"

# The panel's own trees outside its root: per-account certificates and settings, acme.sh, the jail
# cages (/var/lib/panel), per-account logs, the catch-all page.
PANEL_TREES="/var/lib/panel /var/log/panel /var/www/panel-default"
JAILS_BASE="/var/lib/panel/jails"

# Per-account units and cron entries the panel generates (they point into its tree).
ACCOUNT_UNIT_GLOBS="/etc/systemd/system/phpfpm-*.service /etc/systemd/system/panel-app-*.service \
/etc/systemd/system/panel-appsock-*.service /etc/systemd/system/panel-appsock-*.path \
/etc/systemd/system/hosting-*.slice /etc/cron.d/panel-*"

# Trees a component's software leaves behind after its packages are purged (internal/uninstall's
# componentDirs), as <ledger component>:<path>, and each web server's configuration tree by package.
COMPONENT_DIRS="db:/var/lib/mysql dns:/etc/bind dns:/var/lib/bind dns:/var/cache/bind dns:/etc/powerdns \
dns:/var/lib/powerdns mail:/etc/dovecot mail:/etc/exim4 mail:/etc/postfix mail:/etc/rspamd mail:/etc/redis \
mail:/etc/opendkim mail:/etc/opendmarc mail:/var/lib/dovecot mail:/var/lib/redis mail:/var/lib/rspamd \
mail:/var/cache/rspamd mail:/var/spool/postfix mail:/var/spool/exim4 antivirus:/etc/clamav \
antivirus:/var/lib/clamav fail2ban:/etc/fail2ban ftp:/etc/proftpd jail:/etc/jailkit"
WEB_CONF_DIRS="nginx:/etc/nginx fairlead-nginx:/etc/nginx apache2:/etc/apache2 fairlead-apache:/etc/apache2 haproxy:/etc/haproxy"

# Mail configs the panel writes into package-owned dirs; dovecot's purge runs doveconf and aborts on
# them, so before a purge each is put back from its *.orig or removed.
PANEL_MAIL_CONFIGS="/etc/dovecot/dovecot.conf /etc/postfix/main.cf /etc/postfix/master.cf /etc/exim4/exim4.conf"

# is_kept: the administrator's SSH and network settings — the panel only wrote them on their behalf,
# and removing them could change how the server is reached. Kept in every mode, never reported.
is_kept() {
  case "$1" in
    /etc/ssh|/etc/ssh/*|/etc/systemd/system/ssh.socket.d|/etc/systemd/system/ssh.socket.d/*) return 0 ;;
    /etc/netplan|/etc/netplan/*|/etc/network|/etc/network/*|/etc/systemd/network|/etc/systemd/network/*) return 0 ;;
  esac
  return 1
}

# removable <path>: may a path read from the panel's state be deleted? Absolute, clean, at least two
# levels deep, not a shared system directory and not kept — so a damaged state file can never point
# the sweep at /, /etc or /home.
removable() {
  local p="$1"
  case "$p" in /*/*) ;; *) return 1 ;; esac                      # absolute, at least two levels
  case "$p" in *//*|*/./*|*/../*|*/.|*/..|*/) return 1 ;; esac     # clean
  case "$p" in
    /usr/local/*/*) ;;                                              # a helper the panel put there
    /bin/*|/boot/*|/dev/*|/lib*|/proc/*|/root/*|/run/*|/sbin/*|/sys/*|/usr/*) return 1 ;;
  esac
  case "$p" in
    /etc/*.d|/etc/systemd|/etc/systemd/system|/etc/apt|/etc/default|/etc/ssl|/var/lib|/var/www|/var/log \
    |/var/mail|/var/spool|/var/cache|/var/backups|/opt/panel|/srv/www|/home/lost+found|/var/lib/panel/jails) return 1 ;;
  esac
  if is_kept "$p"; then return 1; fi
  return 0
}

# safe_home <path>: may this be deleted as an account's home? (internal/uninstall's safeHome)
safe_home() {
  case "$1" in /*/*) ;; *) return 1 ;; esac
  case "$1" in *//*|*/./*|*/../*|*/.|*/..|*/) return 1 ;; esac
  case "$1/" in /bin/*|/boot/*|/dev/*|/etc/*|/lib*|/proc/*|/root/*|/run/*|/sbin/*|/sys/*|/usr/*) return 1 ;; esac
  case "$1" in /var/lib|/var/www|/var/log|/var/mail|/var/spool|/var/cache|/var/backups|/opt/panel|/srv/www|/home/lost+found) return 1 ;; esac
  return 0
}

# toml_strings <key> <file>: the strings of a top-level `key = "…"` or `key = [ … ]` in a state file
# the panel wrote, one per line.
toml_strings() {
  awk -v k="$1" '
    function emit(s) { while (match(s, /"[^"]*"/)) { print substr(s, RSTART + 1, RLENGTH - 2); s = substr(s, RSTART + RLENGTH) } }
    /^[[:space:]]*\[[^"]*\][[:space:]]*$/ { exit }
    open { emit($0); if ($0 ~ /\]/) open = 0; next }
    $0 ~ "^[[:space:]]*" k "[[:space:]]*=" { s = $0; sub(/^[^=]*=/, "", s); emit(s); if (s ~ /\[/ && s !~ /\]/) open = 1 }
  ' "$2" 2>/dev/null || true
}
# toml_true <key> <file>: is a top-level boolean key true?
toml_true() {
  awk -v k="$1" '/^[[:space:]]*\[[^"]*\][[:space:]]*$/ { exit }
    $0 ~ "^[[:space:]]*" k "[[:space:]]*=[[:space:]]*true[[:space:]]*$" { f = 1 } END { exit !f }' "$2" 2>/dev/null
}

# add_word <var> <word>: append a word to a space-separated list variable once.
add_word() {
  local cur="${!1}"
  case " $cur " in *" $2 "*) return 0 ;; esac
  printf -v "$1" '%s' "${cur:+$cur }$2"
}

# drop_word VAR WORD — remove WORD from the space-separated list in VAR.
drop_word() {
  local out="" w
  for w in ${!1}; do [ "$w" = "$2" ] || out="${out:+$out }$w"; done
  printf -v "$1" '%s' "$out"
}

# ----- the footprint: what the panel's state says it put on this server. Read BEFORE anything is
# removed — the uninstaller resets that state and the purge removes it — and used by the fallback
# sweep and by the final check.
FP_STATE=0      # 1 when the panel's state was there to read
FP_PKGS=""      # packages the install ledger or a web-stack manifest says the panel installed
FP_PREEXISTING="" # packages the ledger says were installed before the panel — never removed
FP_ADOPTED=""   # panel builds a stack migration put in place of a service that was there before
FP_COMPONENTS="" # ledger components
FP_SERVICES=""  # their units
FP_PATHS=""     # their files and trees (configuration and data), only removable ones
FP_DELETE=""    # accounts the panel created, as user:home
FP_KEEP=""      # accounts the panel only adopted — released, never deleted
read_footprint() {
  local st="$PANEL_ROOT/state" f x y c u home majors
  [ -d "$st" ] || return 0
  FP_STATE=1
  for f in "$st"/ledger/*.toml; do
    [ -e "$f" ] || continue
    c="$(toml_strings component "$f" | head -n1)"
    if [ "$c" = preexisting ]; then
      # Packages that were on the server before the panel (ledger.Preexisting): never removed.
      while IFS= read -r x; do [ -n "$x" ] && add_word FP_PREEXISTING "$x"; done < <(toml_strings packages "$f")
      continue
    fi
    [ -n "$c" ] && add_word FP_COMPONENTS "$c"
    majors=""
    while IFS= read -r x; do
      [ -n "$x" ] || continue
      add_word FP_PKGS "$x"
      case "$x" in postgresql-[0-9]|postgresql-[0-9][0-9]) add_word majors "${x#postgresql-}" ;; esac
    done < <(toml_strings packages "$f")
    while IFS= read -r x; do [ -n "$x" ] && add_word FP_SERVICES "$x"; done < <(toml_strings services "$f")
    while IFS= read -r x; do
      case "$x" in
        "$SOURCES_D"/*.list|"$SOURCES_D"/*.sources)
          x="${x%.list}"; x="${x%.sources}"
          for y in "$x.list" "$x.sources" "$x.list.bak"; do if removable "$y"; then add_word FP_PATHS "$y"; fi; done ;;
        /etc/postgresql|/var/lib/postgresql)
          # Only the majors the panel installed: these roots may hold another PostgreSQL's clusters.
          [ "$c" = "pg" ] || continue
          for y in $majors; do add_word FP_PATHS "$x/$y"; done ;;
        *) if removable "$x"; then add_word FP_PATHS "$x"; fi ;;
      esac
    done < <(toml_strings files "$f"; toml_strings dirs "$f"; toml_strings data_dirs "$f")
  done
  for f in "$st"/modules/*.toml; do
    [ -e "$f" ] || continue
    while IFS= read -r x; do
      [ -n "$x" ] || continue
      add_word FP_PKGS "$x"
      for c in $WEB_CONF_DIRS; do if [ "${c%%:*}" = "$x" ]; then add_word FP_PATHS "${c#*:}"; fi; done
    done < <(toml_strings packages "$f")
  done
  for c in $COMPONENT_DIRS; do
    case " $FP_COMPONENTS " in *" ${c%%:*} "*) add_word FP_PATHS "${c#*:}" ;; esac
  done
  for f in "$st"/stackmig/*.toml; do
    [ -e "$f" ] || continue
    while IFS= read -r x; do
      [ -n "$x" ] || continue
      case " $FP_PKGS " in *" $x "*) ;; *) add_word FP_ADOPTED "$x" ;; esac
    done < <(toml_strings FairleadPkgs "$f"; toml_strings fairlead_pkgs "$f")
  done
  for f in "$st"/accounts/*.toml; do
    [ -e "$f" ] || continue
    u="$(basename "$f" .toml)"
    case "$u" in root|''|*[!a-z0-9_.-]*) continue ;; esac
    if toml_true imported "$f"; then add_word FP_KEEP "$u"; continue; fi
    home="$(toml_strings home "$f" | head -n1)"
    case "$home" in *[[:space:]:]*) home="" ;; esac
    add_word FP_DELETE "$u:${home:-/home/$u}"
  done
  for x in $FP_PREEXISTING; do drop_word FP_PKGS "$x"; done
  return 0
}

# panel_build: a package only the panel's repositories ship (internal/uninstall's panelBuild).
panel_build() {
  case "$1" in
    "$PANEL_PKG"|"$WEBMAIL_PKG"|"$LANG_PREFIX"*) return 1 ;;
    fairlead-*|panel-php*) return 0 ;;
  esac
  return 1
}

# pkg_state is dpkg's status abbreviation of a package ("ii ", "rc ", … — empty when dpkg doesn't know it).
pkg_state() { dpkg-query -W -f='${db:Status-Abbrev}' "$1" 2>/dev/null || true; }

# installed_from lists which of the given packages dpkg still has anything of: installed (even half
# way) or with configuration left.
installed_from() {
  local p out=""
  for p in "$@"; do
    case "$(pkg_state "$p")" in ''|?n*) ;; *) out="$out $p" ;; esac
  done
  printf '%s' "$out"
}

# installed_now lists which of the given packages are installed (configuration-only ones don't count).
installed_now() {
  local p out=""
  for p in "$@"; do
    case "$(pkg_state "$p")" in ?[iUFHWT]*) out="$out $p" ;; esac
  done
  printf '%s' "$out"
}

# neutralize_maintainer_scripts blanks a package's dpkg maintainer scripts to a no-op, so a failing
# prerm/postrm can't keep `dpkg --purge` from removing a package the panel installed. The last resort,
# for packages that survived a forced purge.
neutralize_maintainer_scripts() {
  local s f
  for s in prerm postrm preinst postinst; do
    f="/var/lib/dpkg/info/$1.$s"
    if [ -f "$f" ]; then printf '#!/bin/sh\nexit 0\n' > "$f"; fi
  done
  return 0
}

# panel_builds_present: every fairlead-* / panel-php* package dpkg knows (not the panel's own).
panel_builds_present() {
  local p out=""
  for p in $(dpkg-query -W -f='${Package}\n' 'fairlead-*' 'panel-php*' 2>/dev/null || true); do
    if panel_build "$p"; then out="$out $p"; fi
  done
  printf '%s' "$out"
}

# own_packages: the panel's own packages dpkg still has anything of.
own_packages() {
  # shellcheck disable=SC2046
  installed_from "$PANEL_PKG" "$WEBMAIL_PKG" $(dpkg-query -W -f='${Package}\n' "${LANG_PREFIX}*" 2>/dev/null || true)
}

# mounts_under <path>: mount points at or below <path>, deepest first.
mounts_under() {
  awk -v p="$1" '{ m = $5; gsub(/\\040/, " ", m); gsub(/\\011/, "\t", m); gsub(/\\134/, "\\", m)
    if (m == p || index(m, p "/") == 1) print length(m) "\t" m }' /proc/self/mountinfo 2>/dev/null \
    | sort -rn | cut -f2- || true
}

# rm_path removes a file or tree, never through a mount: a tree with anything still mounted at or below
# it is left in place, and said so (a jail bind of a user's home, a data disk).
rm_path() {
  local p="$1"
  [ -e "$p" ] || [ -L "$p" ] || return 0
  if [ -d "$p" ] && [ ! -L "$p" ] && [ -n "$(mounts_under "$p")" ]; then
    warn "left $p in place: something is still mounted inside it"
    return 1
  fi
  rm -rf --one-file-system "$p"
}

# ----- the fallback sweep: no panel binary to run (a broken install). It does what the uninstaller
# would, as far as a script can, and no more: only accounts the panel created (never an adopted one),
# only packages the panel's state says it installed plus its own builds (a build that replaced a
# service which was there before is removed, never purged), only those components' trees, and never
# the SSH or network settings. Without any state it purges nothing but the panel's own packages and
# removes its builds without purging them. Best-effort: errexit is off while it runs.
fallback_sweep() {
  set +e +o pipefail
  say "${1:-The panel cannot run its own uninstaller} — sweeping by the panel's records instead"
  [ "$FP_STATE" = "1" ] || warn "the panel's state is gone too: only the panel's own packages, builds and files are removed"
  local f u home p unit line name rest pk purge remove

  # 1) Services: the panel's, the recorded components', the per-account units and the jail cages.
  for unit in panel.service panel-webmail.service panel-net.service panel-reboot.timer panel-reboot.service $FP_SERVICES; do
    systemctl disable --now "$unit" 2>/dev/null
  done
  # shellcheck disable=SC2086
  for f in $ACCOUNT_UNIT_GLOBS; do
    [ -e "$f" ] || continue
    case "$f" in /etc/systemd/system/*) systemctl disable --now "$(basename "$f")" 2>/dev/null ;; esac
    rm -f "$f"
  done
  for f in /etc/systemd/system/*.mount; do
    [ -f "$f" ] && grep -q 'Generated by Panel (jail mount' "$f" 2>/dev/null || continue
    systemctl disable --now "$(basename "$f")" 2>/dev/null
    rm -f "$f"
  done
  systemctl daemon-reload 2>/dev/null
  mounts_under "$JAILS_BASE" | while IFS= read -r p; do umount -l "$p" 2>/dev/null; done
  pkill -f '^/opt/panel/' 2>/dev/null

  # 2) Jailed logins get their real home back (the cages go); an adopted user its own shell, others nologin.
  while IFS=: read -r name _ _ _ _ home rest; do
    case "$home" in "$JAILS_BASE"/*/./*) ;; *) continue ;; esac
    case " $FP_KEEP " in
      *" $name "*) p="$(toml_strings imported_shell "$PANEL_ROOT/state/accounts/$name.toml" | head -n1)"
                   case "$p" in ''|*/jk_chrootsh) p="/usr/sbin/nologin" ;; esac ;;
      *) p="/usr/sbin/nologin" ;;
    esac
    usermod -d "/${home#*/./}" -s "$p" "$name" 2>/dev/null && ok "released $name from its jail (home /${home#*/./}, shell $p)"
  done < <(getent passwd 2>/dev/null || cat /etc/passwd)

  # 3) Accounts: the ones the panel created go with their homes (never through a mount); adopted stay.
  for line in $FP_DELETE; do
    u="${line%%:*}"; home="${line#*:}"
    if getent passwd "$u" >/dev/null 2>&1; then
      userdel -f "$u" 2>/dev/null || { warn "could not delete user $u — its home $home stays"; continue; }
      ok "removed user $u"
    fi
    if safe_home "$home"; then rm_path "$home"; else warn "left $home in place: not a path the panel creates"; fi
  done
  for u in $FP_KEEP; do ok "kept user $u — it existed before the panel adopted it"; done

  # 4) Packages: the recorded ones and the panel's builds are purged (a build that replaced a service
  #    which was there before only removed, so that service's configuration stays). With no state at
  #    all, no build can be told apart, so all are only removed. The panel's own packages go too.
  case " $FP_COMPONENTS " in
    *" mail "*) for f in $PANEL_MAIL_CONFIGS; do if [ -f "$f.orig" ]; then mv -f "$f.orig" "$f"; else rm -f "$f"; fi; done ;;
  esac
  purge=""; remove=""
  # shellcheck disable=SC2086
  for p in $(installed_from $FP_PKGS $(panel_builds_present)); do
    case " $FP_ADOPTED " in *" $p "*) add_word remove "$p"; continue ;; esac
    if [ "$FP_STATE" = "1" ]; then add_word purge "$p"; else add_word remove "$p"; fi
  done
  for p in $(own_packages); do add_word purge "$p"; done
  # shellcheck disable=SC2086
  remove="$(installed_now $remove)"
  if [ -n "$purge" ]; then
    # shellcheck disable=SC2086
    apt_get purge -y $purge 2>/dev/null
    # shellcheck disable=SC2086
    pk="$(installed_from $purge)"
    if [ -n "$pk" ]; then
      wait_apt_idle
      # shellcheck disable=SC2086
      dpkg --purge --force-all $pk 2>/dev/null
      # shellcheck disable=SC2086
      pk="$(installed_from $pk)"
      if [ -n "$pk" ]; then
        warn "forcing removal of stubborn packages:$pk"
        for p in $pk; do neutralize_maintainer_scripts "$p"; done
        # shellcheck disable=SC2086
        dpkg --purge --force-all $pk 2>/dev/null
      fi
    fi
  fi
  # shellcheck disable=SC2086
  if [ -n "$remove" ]; then apt_get remove -y $remove 2>/dev/null; fi

  # 5) Files and trees: the recorded components', the panel's own, its integration, apt source, root.
  for p in $FP_PATHS $PANEL_TREES; do rm_path "$p"; done
  # shellcheck disable=SC2086
  for p in $PANEL_INTEGRATION $PANEL_UNIT_FILES; do is_kept "$p" || rm -f "$p"; done
  remove_panel_apt
  command -v nft >/dev/null 2>&1 && nft delete table inet panel_fw 2>/dev/null
  rm_path "$PANEL_ROOT"
  systemctl daemon-reload 2>/dev/null
  systemctl reset-failed 2>/dev/null
  set -e -o pipefail
  return 0
}

# own_cleanup removes what is the panel package's own after the uninstaller ran: the panel, webmail
# and language packages (purged — nothing of theirs is anyone else's), a panel build the uninstaller
# left installed (removed, not purged: it may have replaced a service that was there before), the
# panel's apt source and key in every form, its PAM file and unit links — and on --purge /opt/panel.
own_cleanup() {
  local purge="$1" pk
  say "Removing the panel packages"
  systemctl disable --now panel.service panel-webmail.service 2>/dev/null || true
  pk="$(own_packages)"
  if [ -n "$pk" ]; then
    # shellcheck disable=SC2086
    apt_get purge -y $pk || warn "apt could not remove:$pk"
  fi
  if [ "$purge" = "1" ]; then
    # shellcheck disable=SC2086
    pk="$(installed_now $(panel_builds_present))"
    if [ -n "$pk" ]; then
      warn "panel builds still installed after the uninstaller:$pk — removing them (their configuration stays)"
      # shellcheck disable=SC2086
      apt_get remove -y $pk || warn "apt could not remove:$pk"
    fi
  fi
  say "Removing the package sources and PAM service"
  remove_panel_apt
  # shellcheck disable=SC2086
  rm -f /etc/pam.d/panel $PANEL_UNIT_FILES
  systemctl daemon-reload 2>/dev/null || true
  if [ "$purge" = "1" ]; then
    say "Removing the panel root ($PANEL_ROOT)"
    rm_path "$PANEL_ROOT" || true
  fi
}

# verify_clean checks, after --purge, that nothing it was meant to remove is left: the panel's own
# packages; any panel build still installed; the packages the panel's state recorded; those
# components' files and trees, the panel's own trees and /opt/panel; its integration files, units, apt
# source and keys (every form) and pins; the accounts it created; anything still running from
# /opt/panel; its firewall table. What stays on purpose — accounts the panel only adopted, software and
# data that were there before it, the SSH and network settings — is not a leftover and isn't listed.
# Prints what is left, per category, and returns non-zero if anything is.
verify_clean() {
  local p line pk="" fl="" ul="" pl="" nl=""
  # shellcheck disable=SC2046,SC2086
  for p in $(own_packages) $(installed_now $(panel_builds_present)) $(installed_from $FP_PKGS); do add_word pk "$p"; done
  for p in $FP_PATHS $PANEL_TREES "$PANEL_ROOT"; do
    if [ -e "$p" ] || [ -L "$p" ]; then add_word fl "$p"; fi
  done
  # shellcheck disable=SC2086
  for p in $PANEL_INTEGRATION $PANEL_UNIT_FILES $(apt_teardown_files); do
    is_kept "$p" && continue
    if [ -e "$p" ] || [ -L "$p" ]; then add_word fl "$p"; fi
  done
  for p in "$SOURCES_D"/*.list "$SOURCES_D"/*.sources; do
    if [ -f "$p" ] && src_serves "$p"; then add_word fl "$p"; fi
  done
  for line in $FP_DELETE; do
    if getent passwd "${line%%:*}" >/dev/null 2>&1; then add_word ul "${line%%:*}"; fi
  done
  if pgrep -f '^/opt/panel/' >/dev/null 2>&1; then pl=" $(pgrep -f '^/opt/panel/' | tr '\n' ' ')"; fi
  if command -v nft >/dev/null 2>&1 && nft list table inet panel_fw >/dev/null 2>&1; then nl=" inet panel_fw"; fi

  if [ -z "$(printf '%s%s%s%s%s' "$pk" "$fl" "$ul" "$pl" "$nl" | tr -d '[:space:]')" ]; then
    ok "Verified: nothing the purge removes is left (what stays on purpose is listed in the summary above)."
    return 0
  fi
  warn "NOT fully clean — still present:"
  if [ -n "$pk" ]; then warn "  packages: $pk"; fi
  if [ -n "$fl" ]; then warn "  files and directories: $fl"; fi
  if [ -n "$ul" ]; then warn "  accounts the panel created: $ul"; fi
  if [ -n "$pl" ]; then warn "  processes running from $PANEL_ROOT:$pl"; fi
  if [ -n "$nl" ]; then warn "  firewall table:$nl"; fi
  return 1
}

# confirm_purge: --purge destroys the data the panel holds, so it is confirmed first — by typing
# "purge" on the terminal, or up front with --yes when there is no terminal to ask.
confirm_purge() {
  [ "$YES" = "1" ] && return 0
  have_tty || die "--purge removes everything the panel installed and holds and must be confirmed, but there is no terminal to ask — re-run with --purge --yes"
  {
    printf "\n${C_R}${C_B}--purge removes EVERYTHING the panel installed and holds, and cannot be undone:${C_0}\n"
    printf "  every database, DNS zone and mail store of the services the panel installed,\n"
    printf "  every account the panel created, with its home (websites, mail, files),\n"
    printf "  the configuration of every service the panel installed, and the panel itself.\n"
    printf "  Accounts that existed before the panel adopted them, software that was there before it,\n"
    printf "  and your SSH and network settings stay. Back up anything you need first.\n\n"
    printf "Type ${C_B}purge${C_0} to continue (anything else stops): "
  } >/dev/tty
  local ans=""
  read -r ans </dev/tty || ans=""
  [ "$ans" = "purge" ] || die "not confirmed — nothing was changed"
}

# panel_knows_flag <name>: does the installed panel binary accept -<name>? (Older releases reject an
# unknown flag before doing anything; -version makes the probe a no-op on the ones that know it.)
panel_knows_flag() {
  local bin="$PANEL_ROOT/panel" help
  [ -x "$bin" ] || return 1
  "$bin" "-$1" -version </dev/null >/dev/null 2>&1 && return 0
  help="$("$bin" -h </dev/null 2>&1 || true)"
  case "$help" in *"  -$1"[[:space:]]*|*"  -$1") return 0 ;; esac
  return 1
}

# stop_panel stops the panel and webmail; the uninstaller refuses to run beside a running panel (its
# reconcilers would put back what is removed).
stop_panel() {
  say "Stopping the panel"
  systemctl stop panel.service 2>/dev/null || true
  systemctl stop panel-webmail.service 2>/dev/null || true
  if systemctl is-active --quiet panel.service; then
    die "panel.service is still running — stop it (systemctl stop panel.service) and run this again; nothing was changed"
  fi
}

do_uninstall() {
  local purge="$1" rc=0 args="--uninstall"
  [ "$purge" = "1" ] && args="--uninstall --purge"
  # What the panel's state records, read before anything changes it.
  read_footprint
  stop_panel

  if [ -x "$PANEL_ROOT/panel" ] && panel_knows_flag yes; then
    # The panel's own uninstaller — the teardown. --yes: the question was asked above (its own can't
    # be answered here, stdin is this script).
    say "Running the panel's uninstaller"
    [ "$purge" = "1" ] && args="$args --yes"
    # shellcheck disable=SC2086
    "$PANEL_ROOT/panel" $args </dev/null || rc=$?
    if [ "$rc" != "0" ]; then
      if [ "$FORCE" != "1" ]; then
        die "the panel's uninstaller reported failed steps (see its summary above). The panel package and $PANEL_ROOT are kept, so its records stay and running this again retries just what failed — fix those and re-run, or add --force to remove the panel anyway"
      fi
      warn "the panel's uninstaller reported failed steps — removing the panel anyway (--force)"
    fi
    own_cleanup "$purge"
  elif [ -x "$PANEL_ROOT/panel" ]; then
    # A release from before the reworked uninstaller: its ledger teardown, then (on --purge) the sweep.
    say "Reversing panel-managed subsystems (from the install ledger)"
    # shellcheck disable=SC2086
    "$PANEL_ROOT/panel" $args </dev/null || warn "ledger teardown reported problems (continuing)"
    if [ "$purge" = "1" ]; then fallback_sweep "This panel release predates its full uninstaller"; else own_cleanup 0; fi
  else
    warn "panel binary not found at $PANEL_ROOT/panel — it can't run its own uninstaller"
    if [ "$purge" = "1" ]; then fallback_sweep "Panel binary missing"; else own_cleanup 0; fi
  fi

  if [ "$purge" = "1" ]; then
    if verify_clean; then
      ok "Server returned to a bare state — what the panel found here, and your SSH and network settings, stay."
    else
      die "the purge finished, but what is listed above is still there — remove it by hand or run --purge again"
    fi
  else
    ok "Panel removed. User data and databases were left in place."
    printf "${C_D}Run with --purge to remove everything the panel installed, including %s.${C_0}\n" "$PANEL_ROOT"
  fi
}

# ----------------------------------------------------------------------------- main
main() {
  [ "$(id -u)" = "0" ] || die "please run as root (pipe into 'sudo bash')"
  case "$MODE" in
    install|upgrade|uninstall|purge) not_inside_panel ;;
  esac
  case "$MODE" in
    check)     preflight; printf "\n"; ok "Preflight only — nothing was changed." ;;
    install)   preflight; ensure_tools; check_registry; do_install ;;
    upgrade)   detect_os; [ -n "$SUITE" ] || SUITE="noble"; ensure_tools; check_registry; do_upgrade ;;
    list)      detect_os; [ -n "$SUITE" ] || SUITE="noble"; ensure_tools; check_registry; do_list_versions ;;
    uninstall) do_uninstall 0 ;;
    purge)     confirm_purge; do_uninstall 1 ;;
  esac
}
main
