#!/usr/bin/env bash
# WAFio All-in-One Installer
# https://wafio.cloud/docs#getting-started
#
# Usage:
#   curl -fsSL https://wafio.cloud/install.sh | sudo bash
#   sudo bash install.sh
#   sudo bash install.sh --component controlplane
#
# This script handles everything end-to-end:
#    1. Component selection (controlplane / waf-agent / host-agent / all)
#    2. OS detection (Debian/Ubuntu or RHEL/CentOS/Rocky)
#    3. PostgreSQL check / auto-install
#    4. Binary download from wafio.cloud portal API (free, no signup)
#    5. Security data download (GeoIP, FireHOL, JA4, Bots)
#    6. Config file generation (/etc/wafio/config.yaml)
#    7. Database migrations
#    8. Admin account creation
#    9. Project + agent credential provisioning
#   10. Systemd service installation + start
#   11. Health verification
#
# Usage:
#   curl -fsSL https://wafio.cloud/install.sh | sudo bash
#   curl -fsSL https://wafio.cloud/install.sh | sudo bash -s -- controlplane
#   curl -fsSL https://wafio.cloud/install.sh | sudo bash -s -- waf-agent
#   curl -fsSL https://wafio.cloud/install.sh | sudo bash -s -- host-agent
#
# The control plane's database: --db docker (own container), host or existing.
#
# Or download first, then run (recommended for production):
#   curl -fsSL https://wafio.cloud/install.sh -o wafio-install.sh
#   sudo bash wafio-install.sh [controlplane|waf-agent|host-agent]
#
# One-command agent install with the host key (dashboard → Hosts → Connect
# this host shows the exact command). The installer makes the private key on
# this host, sends a CSR authenticated by the host key, pins the agent CA to
# --ca-sha256 and writes /etc/wafio/certs/<agent>/ + /etc/wafio/<agent>.env:
#   printf '%s\n' 'wafh_…' | sudo bash wafio-install.sh host-agent --host-key-stdin \
#        --url https://dashboard.example.com --ca-sha256 <hex> [--control-plane host:9090] [--server-name NAME]
# (--host-key KEY also works but shows the key in ps and sudo's log; with
# neither the installer asks for it without echo.)
#   sudo bash wafio-install.sh waf-agent --url … --ca-sha256 … --agent-name web-1@waf
# A manual install with a project credential takes --bundle <credential.tar>
# (or the files in /etc/wafio/certs/<agent>/, or pasted PEM blocks).
# sudo bash wafio-install.sh --help lists every option.

set -uo pipefail
# NOTE: errexit (-e) is intentionally NOT enabled. This installer is interactive
# (many `read < /dev/tty` calls) and runs many best-effort commands; under -e a
# benign non-zero — an empty Enter, a `read` EOF, a systemctl warning — would kill
# the entire run mid-install. Steps that MUST succeed use explicit `|| die`.

# ─── Color helpers ───────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; BOLD='\033[1m'; GRAY='\033[0;90m'; NC='\033[0m'
# Messages can carry values from a server (host name, error text): they are
# printed with %s — never `echo -e`, which would turn a literal "\033" into
# ESC — and with C0 controls and DEL dropped (_plain). Only the colour
# constants above go through %b. Server values are also passed through
# sanitize (enroll lib) at the source, which drops C1 and bidi characters too.
_plain() { printf '%s' "$*" | LC_ALL=C tr -d '\000-\010\013-\037\177'; }
info()   { printf '%b[INFO]%b   %s\n' "$BLUE" "$NC" "$(_plain "$*")"; }
ok()     { printf '%b[ ✓ ]%b   %s\n' "$GREEN" "$NC" "$(_plain "$*")"; }
warn()   { printf '%b[WARN]%b  %s\n' "$YELLOW" "$NC" "$(_plain "$*")"; }
die()    { printf '\n%b[ERR]%b   %s\n' "$RED" "$NC" "$(_plain "$*")" >&2; exit 1; }
step()   { printf '\n%b━━ %s ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━%b\n' "${BOLD}${CYAN}" "$(_plain "$*")" "$NC"; }
prompt() { printf '  %b→ %s%b' "$BOLD" "$(_plain "$*")" "$NC"; }
hr()     { echo -e "${GRAY}──────────────────────────────────────────────────────${NC}"; }

# ask_req VAR "prompt" [regex] [errmsg]
# Required input: re-prompts on empty (or on regex mismatch) instead of accepting
# a blank value. Callers are inside a HAVE_TTY-guarded block; a genuine EOF
# (no terminal) dies cleanly rather than looping forever.
ask_req() {
  local __var="$1" __prompt="$2" __re="${3:-}" __err="${4:-}" __val=""
  while true; do
    prompt "$__prompt"; __val=""
    read -r __val < /dev/tty || die "Unexpected end of input reading a required value. Run the installer in an interactive terminal."
    __val="${__val#"${__val%%[![:space:]]*}"}"          # ltrim
    __val="${__val%"${__val##*[![:space:]]}"}"           # rtrim
    if [[ -z "$__val" ]]; then
      echo -e "  ${RED}✗ This field is required — please enter a value.${NC}"; continue
    fi
    if [[ -n "$__re" && ! "$__val" =~ $__re ]]; then
      echo -e "  ${RED}✗ ${__err:-Invalid format.}${NC}"; continue
    fi
    break
  done
  printf -v "$__var" '%s' "$__val"
}

# read_pem VAR "label"
# Required pasted PEM block (blank line ends it). Re-prompts until a non-empty
# block containing a -----BEGIN header is given; clean die on EOF (no terminal).
read_pem() {
  local __var="$1" __label="$2" __txt="" __line="" __eof=0
  while true; do
    echo "  Paste the ${__label} (press Enter on an empty line when done):"
    __txt=""; __eof=0
    while IFS= read -r __line < /dev/tty; do
      [[ -z "$__line" ]] && break
      __txt+="$__line"$'\n'
    done || __eof=1
    if [[ "$__txt" != *"-----BEGIN"* ]]; then
      [[ $__eof -eq 1 ]] && die "Unexpected end of input reading ${__label}. Run the installer in an interactive terminal."
      echo -e "  ${RED}✗ That doesn't look like a PEM block (missing -----BEGIN). Try again.${NC}"; continue
    fi
    break
  done
  printf -v "$__var" '%s' "$__txt"
}

# >>> wafio-enroll-lib ─────────────────────────────────────────────────────────
# Agent enrollment and credential-file helpers. scripts/tests/test_install_enroll.sh
# extracts this block (between the >>> and <<< markers) and runs it against a
# stub control plane, so keep it free of top-level side effects: functions only.
# Needs: die/info/ok/warn, curl, openssl, python3, and the globals CONFIG_DIR and
# CERTS_DIR; the enroll_* inputs are the ENROLL_* globals set by the flag parser.

# ask_secret VAR "prompt" — required input read without echo (host key).
ask_secret() {
  local __var="$1" __prompt="$2" __val=""
  while true; do
    prompt "$__prompt"; __val=""
    read -rs __val < /dev/tty || die "Unexpected end of input reading a required value. Run the installer in an interactive terminal."
    echo ""
    __val="${__val#"${__val%%[![:space:]]*}"}"
    __val="${__val%"${__val##*[![:space:]]}"}"
    [[ -n "$__val" ]] && break
    echo -e "  ${RED}✗ This field is required — please enter a value.${NC}"
  done
  printf -v "$__var" '%s' "$__val"
}

# sanitize VALUE — VALUE with only printable characters (Python's
# str.isprintable: no C0/C1 control, DEL, bidi/zero-width/format character,
# line or paragraph separator; invalid UTF-8 becomes U+FFFD). For every value
# a server sent before it is printed: a host name with ESC/OSC sequences must
# not reach the root terminal running this installer. Python rather than
# `LC_ALL=C tr -cd '[:print:]'`, which would also strip every non-ASCII
# letter (a host named 東京-1 would print as -1) and cannot see bidi
# characters; the fallback without python3 is that ASCII-only filter.
sanitize() {
  if command -v python3 >/dev/null 2>&1; then
    printf '%s' "$1" | python3 -c 'import sys
s = sys.stdin.buffer.read().decode("utf-8", "replace")
sys.stdout.write("".join(c for c in s if c.isprintable()))'
  else
    printf '%s' "$1" | LC_ALL=C tr -cd '[:print:]'
  fi
}

# Value checks. Everything that ends up in an env file is checked against a
# closed character set, so no value can add a line (or a variable) to it.
valid_host_key()    { [[ "$1" =~ ^wafh_[a-z2-7]{24}$ ]]; }
valid_agent_name()  { [[ ${#1} -le 128 && "$1" =~ ^[A-Za-z0-9][A-Za-z0-9._@:-]*$ ]]; }
# (POSIX brackets: a literal ] must come first, so [][…] holds both brackets.)
valid_grpc_addr()   { local re='^[][A-Za-z0-9._:-]+:[0-9]{1,5}$'; [[ ${#1} -le 260 && "$1" =~ $re ]]; }
valid_server_name() { [[ ${#1} -le 253 && "$1" =~ ^[A-Za-z0-9._:-]+$ ]]; }

# normalize_sha256 HEX — lowercase, colons dropped; prints "" when not 64 hex.
normalize_sha256() {
  local v="${1//:/}"
  v="$(printf '%s' "$v" | tr 'A-F' 'a-f')"
  [[ "$v" =~ ^[0-9a-f]{64}$ ]] && printf '%s' "$v"
}

# check_dashboard_url URL — https://, or http:// to a loopback address only:
# the host key travels in a request header.
check_dashboard_url() {
  local u="$1"
  [[ "$u" =~ ^https://[^[:space:]/?#]+(/[^[:space:]?#]*)?$ ]] && return 0
  [[ "$u" =~ ^http://(127\.0\.0\.1|localhost|\[::1\])(:[0-9]{1,5})?(/[^[:space:]?#]*)?$ ]] && return 0
  return 1
}

# env_set FILE KEY VALUE / env_unset FILE KEY — rewrite one KEY= line of an
# env file in place (appended when missing); other lines are kept as they are.
env_set() {
  python3 - "$1" "$2" "$3" <<'PY' || die "Cannot update $1"
import os, sys
path, key, val = sys.argv[1], sys.argv[2], sys.argv[3]
if not key or not (key + val).isprintable():
    sys.exit("refusing a control character in " + key.encode("unicode_escape").decode())
lines = open(path).read().splitlines() if os.path.exists(path) else []
out, done = [], False
for line in lines:
    if line.split("=", 1)[0].strip() == key:
        if not done:
            out.append(key + "=" + val)
            done = True
        continue
    out.append(line)
if not done:
    out.append(key + "=" + val)
tmp = path + ".tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
    f.write("\n".join(out) + "\n")
os.chmod(tmp, 0o600)
os.replace(tmp, path)
PY
}
env_unset() {
  [[ -f "$1" ]] || return 0
  python3 - "$1" "$2" <<'PY' || die "Cannot update $1"
import os, sys
path, key = sys.argv[1], sys.argv[2]
lines = [l for l in open(path).read().splitlines() if l.split("=", 1)[0].strip() != key]
tmp = path + ".tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
    f.write("\n".join(lines) + ("\n" if lines else ""))
os.chmod(tmp, 0o600)
os.replace(tmp, path)
PY
}

# is_pem_cert FILE / is_pem_key FILE — the file holds what its name says.
is_pem_cert() { openssl x509 -in "$1" -noout 2>/dev/null; }
is_pem_key()  { openssl pkey -in "$1" -noout 2>/dev/null; }

# install_credential_files SRC_DIR DEST_DIR — ca.crt + client.crt (0644) and
# client.key (0600) from SRC_DIR into DEST_DIR, each written next to its
# destination and renamed, so a running agent never reads half a file.
install_credential_files() {
  local src="$1" dest="$2" f
  is_pem_cert "${src}/ca.crt"     || die "ca.crt is not a PEM certificate."
  is_pem_cert "${src}/client.crt" || die "client.crt is not a PEM certificate."
  is_pem_key  "${src}/client.key" || die "client.key is not a PEM private key."
  install -d -m 0750 "$dest" || die "Cannot create ${dest}"
  for f in ca.crt client.crt; do
    install -m 0644 "${src}/${f}" "${dest}/.${f}.new" && mv -f "${dest}/.${f}.new" "${dest}/${f}" \
      || die "Cannot write ${dest}/${f}"
  done
  ( umask 077; install -m 0600 "${src}/client.key" "${dest}/.client.key.new" ) \
    && mv -f "${dest}/.client.key.new" "${dest}/client.key" || die "Cannot write ${dest}/client.key"
}

# extract_credential_bundle TAR DEST_DIR — the dashboard's credential .tar
# (ca.crt, client.crt, client.key; other members ignored). Only those three
# names are extracted, into a private directory first.
extract_credential_bundle() {
  local tarball="$1" dest="$2" tmp
  [[ -f "$tarball" ]] || die "Bundle not found: ${tarball}"
  tmp=$(mktemp -d "${CONFIG_DIR}/.bundle.XXXXXX") || die "Cannot create a work directory in ${CONFIG_DIR}"
  chmod 700 "$tmp"
  if ! ( umask 077; tar -xf "$tarball" -C "$tmp" ca.crt client.crt client.key ) 2>/dev/null; then
    rm -rf "$tmp"; die "The bundle must contain ca.crt, client.crt and client.key (the .tar from the dashboard's Credentials page)."
  fi
  install_credential_files "$tmp" "$dest"
  rm -rf "$tmp"
}

# have_credential_files DIR — ca.crt, client.crt and client.key are present.
have_credential_files() { [[ -s "$1/ca.crt" && -s "$1/client.crt" && -s "$1/client.key" ]]; }

# ENROLL_WORK: the private work directory of an enrollment (removed on exit).
ENROLL_WORK=""
enroll_cleanup() { [[ -n "$ENROLL_WORK" && -d "$ENROLL_WORK" ]] && rm -rf "$ENROLL_WORK"; ENROLL_WORK=""; }
# exit_hooks STATUS: what the installer does at exit besides the cleanup above, with the exit status. The EXIT trap of an
# enrollment replaces any other, so every trap of this script calls it; the download block redefines it.
exit_hooks() { :; }

# read_host_key_stdin — --host-key-stdin: the first line of stdin is the host
# key (`printf '%s\n' 'wafh_…' | sudo bash wafio-install.sh … --host-key-stdin`
# keeps it out of argv, `ps` and sudo's log). Not for `curl … | bash`, where
# stdin is the script itself.
read_host_key_stdin() {
  local line=""
  IFS= read -r line || true
  line="${line//[[:space:]]/}"
  printf -v ENROLL_HOST_KEY '%s' "$line"
}

# enroll_request KIND NAME KEYFILE — one POST to /api/internal/host-enroll
# with a CSR for KEYFILE; sets ENR_CODE (HTTP status) and leaves the body in
# ${ENROLL_WORK}/resp.json. The host key goes through curl's stdin config.
enroll_request() {
  local kind="$1" name="$2" keyfile="$3"
  printf '[req]\ndistinguished_name = dn\nprompt = no\n[dn]\nCN = wafio-enroll\n' > "${ENROLL_WORK}/req.cnf"
  openssl req -new -sha256 -key "$keyfile" -config "${ENROLL_WORK}/req.cnf" \
    -out "${ENROLL_WORK}/req.csr" 2>/dev/null || die "openssl could not create the certificate request."
  python3 - "${ENROLL_WORK}/req.csr" "$kind" "$name" > "${ENROLL_WORK}/req.json" <<'PY' || die "Cannot build the enrollment request."
import json, sys
print(json.dumps({"csr_pem": open(sys.argv[1]).read(), "agent_kind": sys.argv[2], "agent_name": sys.argv[3]}))
PY
  local -a tls_opts=()
  [[ -n "${ENROLL_DASHBOARD_CACERT:-}" ]] && tls_opts=(--cacert "$ENROLL_DASHBOARD_CACERT")
  rm -f "${ENROLL_WORK}/resp.json"
  ENR_CODE=$(printf 'header = "X-Wafio-Host-Key: %s"\n' "$ENROLL_HOST_KEY" \
    | curl -sS --proto '=https,http' --connect-timeout 10 --max-time 60 -K - ${tls_opts[@]+"${tls_opts[@]}"} \
        -X POST -H 'Content-Type: application/json' -H "User-Agent: wafio-install/${VERSION:-dev}" \
        --data-binary "@${ENROLL_WORK}/req.json" -o "${ENROLL_WORK}/resp.json" -w '%{http_code}' \
        "${ENROLL_URL%/}/api/internal/host-enroll") \
    || die "Cannot reach ${ENROLL_URL} (check --url, DNS, firewall and the dashboard's TLS certificate; --dashboard-cacert takes a private CA)."
}

# enroll_error_code — the "code" of the error body in resp.json ("" if none).
enroll_error_code() {
  python3 -c 'import json,sys
try:
    print(str(json.load(open(sys.argv[1])).get("code", ""))[:64])
except Exception:
    print("")' "${ENROLL_WORK}/resp.json" 2>/dev/null | tr -cd 'A-Z_'
}

# enroll_agent KIND NAME DEST_DIR: host-key enrollment.
# Generates a P-256 key on this host (it never leaves it), sends a CSR with
# the host key to ${ENROLL_URL}/api/internal/host-enroll, checks the returned
# CA against ENROLL_CA_SHA256 and the certificate against the key and the CA,
# and only then installs ca.crt, client.crt and client.key into DEST_DIR.
# An agent that already enrolled with this host key (ENROLL_USED) is renewed
# only by proving it holds the key: the request is repeated with the key
# already in DEST_DIR (an installer re-run on the same host).
# Sets ENR_GRPC_ENDPOINT, ENR_SERVER_NAME, ENR_VALID_UNTIL, ENR_HOST_NAME and
# ENR_RENEWED.
enroll_agent() {
  local kind="$1" name="$2" dest="$3" msg fp cert_pub key_pub
  ENR_GRPC_ENDPOINT=""; ENR_SERVER_NAME=""; ENR_VALID_UNTIL=""; ENR_HOST_NAME=""; ENR_RENEWED=""; ENR_CODE=""
  valid_host_key "$ENROLL_HOST_KEY" || die "The host key is not valid (expected wafh_ followed by 24 characters)."
  valid_agent_name "$name" || die "Agent name '${name}' is not valid (letters, digits and . _ @ : -, at most 128)."
  [[ -n "$ENROLL_CA_SHA256" ]] || die "--ca-sha256 is required for enrollment (Connect this host in the dashboard shows it)."
  check_dashboard_url "$ENROLL_URL" || die "--url must be https://… (or http:// to 127.0.0.1/localhost/[::1] only)."
  install -d -m 0755 "$CONFIG_DIR" || die "Cannot create ${CONFIG_DIR}"
  ENROLL_WORK=$(mktemp -d "${CONFIG_DIR}/.enroll.XXXXXX") || die "Cannot create a work directory in ${CONFIG_DIR}"
  trap 'rc=$?; enroll_cleanup; exit_hooks "$rc"' EXIT
  chmod 700 "$ENROLL_WORK"

  ( umask 077; openssl ecparam -name prime256v1 -genkey -noout -out "${ENROLL_WORK}/client.key" ) 2>/dev/null \
    || die "openssl could not generate a P-256 key."
  info "Enrolling ${kind} agent '${name}' at ${ENROLL_URL} ..."
  enroll_request "$kind" "$name" "${ENROLL_WORK}/client.key"
  if [[ "$ENR_CODE" == "409" && "$(enroll_error_code)" == "ENROLL_USED" ]] && is_pem_key "${dest}/client.key"; then
    info "'${name}' already enrolled with this host key; renewing with the key this host holds."
    ( umask 077; cp "${dest}/client.key" "${ENROLL_WORK}/client.key" ) || die "Cannot read ${dest}/client.key"
    enroll_request "$kind" "$name" "${ENROLL_WORK}/client.key"
  fi
  if [[ "$ENR_CODE" != "201" ]]; then
    msg=$(python3 -c 'import json,sys
try:
    d = json.load(open(sys.argv[1]))
    m = "%s %s" % (d.get("code", ""), d.get("error", ""))
    print("".join(c for c in m if c.isprintable())[:400])
except Exception:
    print("")' "${ENROLL_WORK}/resp.json" 2>/dev/null)
    die "Enrollment refused (HTTP ${ENR_CODE}): ${msg:-no details}"
  fi

  # Exactly one certificate per field, written back as that one block: a CA
  # file is trusted whole (openssl verify -CAfile, the agents' cert pools),
  # while the pin below can only fingerprint one certificate, so a second
  # block would be a CA the pin never saw.
  python3 - "${ENROLL_WORK}/resp.json" "$ENROLL_WORK" <<'PY' || die "The enrollment response is not usable. Nothing was installed."
import json, os, re, sys
d = json.load(open(sys.argv[1]))
work = sys.argv[2]
block = re.compile(r"\A\s*(-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+-----END CERTIFICATE-----)\s*\Z")
for key, name in (("client_cert", "client.crt"), ("ca_cert", "ca.crt")):
    v = d.get(key)
    if not isinstance(v, str) or v.count("-----BEGIN") != 1:
        sys.exit("response field %s must hold exactly one certificate" % key)
    m = block.match(v)
    if not m:
        sys.exit("response field %s is not a single PEM certificate" % key)
    with open(os.path.join(work, name), "w") as f:
        f.write(m.group(1).replace("\r", "") + "\n")
def s(k):
    # Printable characters only: these values are printed to the terminal
    # (host_name is chosen by any project member) and one per line below.
    v = d.get(k)
    if v is True:
        return "true"
    return "".join(c for c in v if c.isprintable()) if isinstance(v, str) else ""
with open(os.path.join(work, "meta"), "w") as f:
    f.write("\n".join(s(k) for k in ("grpc_endpoint", "grpc_server_name", "valid_until", "host_name", "renewed")) + "\n")
PY

  # The CA pin: nothing is installed unless the CA is the one the dashboard
  # showed. A substituted CA would let a man in the middle impersonate the
  # control plane to this agent.
  fp=$(openssl x509 -in "${ENROLL_WORK}/ca.crt" -noout -fingerprint -sha256 2>/dev/null | sed 's/.*=//')
  fp=$(normalize_sha256 "$fp")
  [[ -n "$fp" && "$fp" == "$ENROLL_CA_SHA256" ]] \
    || die "The control plane's CA (SHA-256 ${fp:-unreadable}) does not match --ca-sha256 ${ENROLL_CA_SHA256}. Nothing was installed."
  openssl verify -CAfile "${ENROLL_WORK}/ca.crt" "${ENROLL_WORK}/client.crt" >/dev/null 2>&1 \
    || die "The issued certificate does not chain to the pinned CA. Nothing was installed."
  cert_pub=$(openssl x509 -in "${ENROLL_WORK}/client.crt" -noout -pubkey 2>/dev/null | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null | sed 's/.*= *//')
  key_pub=$(openssl pkey -in "${ENROLL_WORK}/client.key" -pubout -outform DER 2>/dev/null | openssl dgst -sha256 2>/dev/null | sed 's/.*= *//')
  [[ -n "$cert_pub" && "$cert_pub" == "$key_pub" ]] \
    || die "The issued certificate is not for the key generated here. Nothing was installed."

  { IFS= read -r ENR_GRPC_ENDPOINT; IFS= read -r ENR_SERVER_NAME; IFS= read -r ENR_VALID_UNTIL
    IFS= read -r ENR_HOST_NAME; IFS= read -r ENR_RENEWED; } < "${ENROLL_WORK}/meta"
  install_credential_files "$ENROLL_WORK" "$dest"
  enroll_cleanup
  trap 'exit_hooks "$?"' EXIT
  ok "Enrolled ${kind} agent '${name}' for host '$(sanitize "${ENR_HOST_NAME:-?}")' — certificate valid until $(sanitize "${ENR_VALID_UNTIL:-?}")"
  [[ "$ENR_RENEWED" == "true" ]] && info "This replaced (and revoked) the previous certificate of '${name}'."
  return 0
}

# enroll_resolve_target — the gRPC address and server name to write: the
# flags (--control-plane / --server-name) win over what the control plane
# returned. Sets ENR_GRPC_ENDPOINT / ENR_SERVER_NAME or dies.
enroll_resolve_target() {
  [[ -n "$ENROLL_GRPC_SERVER" ]] && ENR_GRPC_ENDPOINT="$ENROLL_GRPC_SERVER"
  [[ -n "$ENROLL_SERVER_NAME" ]] && ENR_SERVER_NAME="$ENROLL_SERVER_NAME"
  [[ -n "$ENR_GRPC_ENDPOINT" ]] \
    || die "The control plane has no server.grpc_domain, so it cannot say where agents connect. Re-run with --control-plane host:9090 (the certificate is renewed)."
  valid_grpc_addr "$ENR_GRPC_ENDPOINT" || die "gRPC address '$(sanitize "$ENR_GRPC_ENDPOINT")' is not host:port."
  if [[ -n "$ENR_SERVER_NAME" ]]; then
    valid_server_name "$ENR_SERVER_NAME" || die "gRPC server name '$(sanitize "$ENR_SERVER_NAME")' is not valid."
  fi
  return 0
}

# write_agent_env FILE NAME CERT_DIR — the gRPC part of an agent env file.
# Keys this installer owns are set; other lines are kept. WAFIO_HOST_KEY is
# removed: an enrolled certificate already names the host, and a host key
# left in the file goes stale at the next rotation (Hello then refuses it).
write_agent_env() {
  local file="$1" name="$2" certs="$3"
  if [[ -f "$file" ]]; then
    # Backup without WAFIO_HOST_KEY: a host key left in a backup could still
    # enroll during its window.
    python3 - "$file" "${file}.bak.$(date +%s 2>/dev/null || echo old)" <<'PY' 2>/dev/null || true
import os, sys
src, dst = sys.argv[1], sys.argv[2]
lines = [l for l in open(src).read().splitlines() if l.split("=", 1)[0].strip() != "WAFIO_HOST_KEY"]
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
    f.write("\n".join(lines) + ("\n" if lines else ""))
PY
  fi
  env_set "$file" WAFIO_GRPC_SERVER "$ENR_GRPC_ENDPOINT"
  if [[ -n "$ENR_SERVER_NAME" ]]; then
    env_set "$file" WAFIO_GRPC_SERVER_NAME "$ENR_SERVER_NAME"
  else
    env_unset "$file" WAFIO_GRPC_SERVER_NAME
  fi
  env_set "$file" WAFIO_GRPC_CA_CERT "${certs}/ca.crt"
  env_set "$file" WAFIO_GRPC_CLIENT_CERT "${certs}/client.crt"
  env_set "$file" WAFIO_GRPC_CLIENT_KEY "${certs}/client.key"
  env_set "$file" WAFIO_AGENT_NAME "$name"
  env_unset "$file" WAFIO_HOST_KEY
  chmod 600 "$file"
}
# <<< wafio-enroll-lib ─────────────────────────────────────────────────────────

# >>> wafio-unit-lib ───────────────────────────────────────────────────────────
# Agent units: a bundle that carries systemd/<name>.service gets that unit. A WAF agent
# bundle without it is refused; a host agent bundle without it (a reused older bundle)
# gets the inline unit written further down. scripts/tests/test_install_units.sh extracts
# this block (it needs env_set from the enroll block above), so keep it free of top-level
# side effects.

# install_bundled_unit BUNDLE_DIR NAME DEST_DIR BIN_DIR: copy BUNDLE_DIR/systemd/NAME.service
# into DEST_DIR with its ExecStart on BIN_DIR (the bundled units name /usr/local/bin).
# Returns 1, writing nothing, when the bundle has no such unit.
install_bundled_unit() {
  local src="$1/systemd/$2.service"
  [[ -s "$src" ]] || return 1
  sed "/^ExecStart=/s#/usr/local/bin/$2#$4/$2#" "$src" > "$3/$2.service" && chmod 0644 "$3/$2.service"
}

# stage_bundled_unit EXDIR NAME STAGE: keep EXDIR/systemd/NAME.service, in the bundle layout,
# for install_bundled_unit. Nothing to do when the bundle carries none.
stage_bundled_unit() {
  [[ -s "$1/systemd/$2.service" ]] || return 0
  install -D -m 0644 "$1/systemd/$2.service" "$3/systemd/$2.service"
}

# env_default FILE KEY VALUE: KEY=VALUE unless FILE already sets KEY (an operator's value stays). systemd's EnvironmentFile= ignores
# white space before a name, so a line that starts with some counts as set.
env_default() { grep -Eq "^[[:space:]]*$2=" "$1" 2>/dev/null || env_set "$1" "$2" "$3"; }

# host_unit_env FILE NIC EBPF_DIR GEOIP_DB: the keys the bundled host unit reads. Its ExecStart
# takes the interface, the BPF objects and the GeoIP database from the environment, and the
# local API token goes to group wafio so the WAF agent (user wafio) can push IP jails.
host_unit_env() {
  env_default "$1" WAFIO_INTERFACE "$2" \
    && env_default "$1" WAFIO_EBPF_XDP_OBJ "$3/wafio_xdp.o" \
    && env_default "$1" WAFIO_EBPF_TC_OBJ "$3/wafio_tc.o" \
    && env_default "$1" WAFIO_TRACE_OBJ "$3/wafio_trace.o" \
    && env_default "$1" WAFIO_GEOIP_DB "$4" \
    && env_default "$1" WAFIO_LOCAL_API_TOKEN_GROUP wafio
}

# waf_unit_dropin DEST_DIR SECURITY_DATA_DIR: the bundled WAF unit lets the agent write only
# /etc/wafio/security-data; the data this installer fetches lives elsewhere.
waf_unit_dropin() {
  mkdir -p "$1/wafio-waf-agent.service.d" \
    && printf '[Service]\nReadWritePaths=-%s\n' "$2" > "$1/wafio-waf-agent.service.d/10-security-data.conf"
}

# ensure_wafio_account user|group: the bundled WAF unit runs as user wafio, the bundled host
# unit names group wafio (systemd refuses to start a unit that names a missing group).
ensure_wafio_account() {
  if [[ "$1" == user ]]; then
    id wafio &>/dev/null && return 0
    if getent group wafio >/dev/null; then
      useradd --system --no-create-home --shell /usr/sbin/nologin -g wafio wafio || die "Cannot create user wafio"
    else
      useradd --system --no-create-home --shell /usr/sbin/nologin wafio || die "Cannot create user wafio"
    fi
  else
    getent group wafio >/dev/null || groupadd --system wafio || die "Cannot create group wafio"
  fi
}

# waf_socket_groups DIR: the groups, other than root and wafio, of the unix sockets in DIR
# (php-fpm keeps its sockets in /run/php). The agent runs as user wafio and reaches a FastCGI
# upstream on such a socket only as a member of that group.
waf_socket_groups() {
  local s
  for s in "$1"/*.sock; do [[ -S "$s" ]] && stat -c %G "$s"; done \
    | awk '$0 != "root" && $0 != "wafio" && !seen[$0]++'
}

# waf_unit_setup DEST_DIR SECURITY_DATA_DIR CERT_DIR [SOCKET_DIR]: what the bundled WAF unit
# (user wafio) needs on the host: the account, the drop-in for the security data it writes,
# read access to its credentials through the group, and a note about FastCGI sockets.
waf_unit_setup() {
  local g
  ensure_wafio_account user
  waf_unit_dropin "$1" "$2" || die "Cannot write the security-data drop-in"
  chown -R root:wafio "$3" && chmod 0750 "$3" && chmod 0640 "$3/client.key" \
    || die "Cannot give group wafio read access to $3"
  if [[ -d "$2" ]]; then
    chown -R wafio:wafio "$2" || warn "Cannot hand $2 to wafio: the agent cannot sync security data"
  fi
  for g in $(waf_socket_groups "${4:-/run/php}"); do
    warn "A FastCGI app on a php-fpm unix socket needs group $g: run 'systemctl edit wafio-waf-agent', add SupplementaryGroups=$g under [Service], then restart wafio-waf-agent"
  done
}
# <<< wafio-unit-lib ───────────────────────────────────────────────────────────

# >>> wafio-glibc-lib
# The Rust WAF agent is linked against the glibc of its build host and does not start on an older
# one ("version `GLIBC_x.y' not found"). The binary names the symbol versions it needs; a static
# binary names none, so the check passes it. The block is the same in deploy/install.sh
# and deploy/install-waf-agent.sh; scripts/tests/test_install_units.sh extracts it, so keep it to
# functions.

# glibc_floor BINARY: the highest GLIBC_x.y[.z] version BINARY names, as x.y[.z]; empty when none.
glibc_floor() {
  { LC_ALL=C grep -aoE 'GLIBC_[0-9]+(\.[0-9]+)+' "$1" 2>/dev/null || true; } | sed 's/^GLIBC_//' | sort -uV | tail -n1
}

# glibc_check BINARY: stops the install when the glibc of this host is older than BINARY needs.
# A host whose version cannot be read gets a warning and goes on.
glibc_check() {
  local need have
  need=$(glibc_floor "$1")
  [[ -n "$need" ]] || return 0
  have=$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $2}' || true)
  if [[ -z "$have" ]]; then
    warn "Cannot read the glibc version of this host; the WAF agent needs glibc ${need} or newer."
    return 0
  fi
  [[ "$(printf '%s\n%s\n' "$need" "$have" | sort -V | head -n1)" == "$need" ]] \
    || die "The WAF agent in this release needs glibc ${need} or newer; this host has glibc ${have}. The WAF agent here was not installed or changed. Use a host with a newer distribution release."
}
# <<< wafio-glibc-lib

# >>> wafio-engine-lib
# A bundle of the normal release carries libwafio_semantic_engine.so and its .sha256 next to the open agent. The agent loads
# the library from ENGINE_LIB_DIR (the default of its --engine-lib) and refuses it unless root owns the file and the
# directory and group and others cannot write to either. The block is the same in deploy/install.sh and
# deploy/install-waf-agent.sh; scripts/tests/test_install_engine_lib.sh extracts it, so keep it to functions. It needs
# die, ok, warn, glibc_check and env_default from the rest of the installer.
#
# The order of an install, in both installers: verify_engine_lib (the checksum and the glibc; it changes nothing), then
# stage_engine_lib and stage_binary (both files are written beside their destinations under temporary names, so every write
# that can fail has happened), then check_staged_engine (the staged agent must load the staged library on this host), and
# only then, with the service stopped where the installer stops it, commit_engine_lib and commit_binary (two renames, the
# library first) and the restart. A refusal before the renames leaves the host as it was, a running agent included.
ENGINE_LIB_DIR="${ENGINE_LIB_DIR:-/usr/lib/wafio}"
ENGINE_LIB_NAME=libwafio_semantic_engine.so
ENGINE_LIB_OWNER="${ENGINE_LIB_OWNER:-root:root}"
# The staged files of stage_engine_lib (empty when none) and whether a library was put in place by this run.
ENGINE_LIB_STAGED=""
ENGINE_LIB_INSTALLED=false

# verify_engine_lib BUNDLE_DIR: checks the library of the bundle, when it has one, and changes nothing: the checksum of the
# bundle first, so a library damaged on its way here is not installed, then the glibc of this host.
verify_engine_lib() {
  local src="$1/$ENGINE_LIB_NAME" sum
  [[ -f "$src" ]] || return 0
  [[ -f "$src.sha256" ]] || die "The bundle has ${ENGINE_LIB_NAME} but no ${ENGINE_LIB_NAME}.sha256. The engine library was not installed or changed."
  sum=$(awk '{print $1; exit}' "$src.sha256")
  [[ -n "$sum" && "$(sha256sum "$src" | awk '{print $1}')" == "$sum" ]] \
    || die "${ENGINE_LIB_NAME} does not match its checksum in the bundle. The engine library was not installed or changed."
  glibc_check "$src"
}

# stage_engine_lib BUNDLE_DIR: verifies the library and writes it and its checksum into ENGINE_LIB_DIR under temporary
# names, owned by root with mode 0644. The library in place is not touched. commit_engine_lib puts the files in place.
stage_engine_lib() {
  local src="$1/$ENGINE_LIB_NAME" sum tmp
  ENGINE_LIB_STAGED=""
  [[ -f "$src" ]] || return 0
  verify_engine_lib "$1"
  sum=$(awk '{print $1; exit}' "$src.sha256")
  install -d -m 0755 -o "${ENGINE_LIB_OWNER%%:*}" -g "${ENGINE_LIB_OWNER##*:}" "$ENGINE_LIB_DIR" \
    || die "Cannot create ${ENGINE_LIB_DIR}"
  # install -d leaves an existing directory as it is, and the agent refuses one that others can write.
  chmod 0755 "$ENGINE_LIB_DIR" && chown "$ENGINE_LIB_OWNER" "$ENGINE_LIB_DIR" || die "Cannot close ${ENGINE_LIB_DIR} to group and others"
  tmp="$ENGINE_LIB_DIR/.$ENGINE_LIB_NAME.$$"
  install -m 0644 -o "${ENGINE_LIB_OWNER%%:*}" -g "${ENGINE_LIB_OWNER##*:}" "$src" "$tmp" \
    || { rm -f "$tmp"; die "Cannot install ${ENGINE_LIB_DIR}/${ENGINE_LIB_NAME}"; }
  printf '%s  %s\n' "$sum" "$ENGINE_LIB_NAME" > "$tmp.sha256" \
    && chmod 0644 "$tmp.sha256" && chown "$ENGINE_LIB_OWNER" "$tmp.sha256" \
    || { rm -f "$tmp" "$tmp.sha256"; die "Cannot install ${ENGINE_LIB_DIR}/${ENGINE_LIB_NAME}"; }
  ENGINE_LIB_STAGED="$tmp"
}

# discard_engine_lib: removes the staged files, for an installer that stops after staging.
discard_engine_lib() {
  [[ -z "$ENGINE_LIB_STAGED" ]] || rm -f "$ENGINE_LIB_STAGED" "$ENGINE_LIB_STAGED.sha256"
  ENGINE_LIB_STAGED=""
}

# commit_engine_lib: renames the staged files into place, the checksum first. A rename is atomic, so a running agent keeps the
# file it loaded and never sees half of one. Call it just before commit_binary, so that no start pairs the new binary with the
# previous library.
commit_engine_lib() {
  local tmp="$ENGINE_LIB_STAGED"
  [[ -n "$tmp" ]] || return 0
  mv -f "$tmp.sha256" "$ENGINE_LIB_DIR/$ENGINE_LIB_NAME.sha256" \
    && mv -f "$tmp" "$ENGINE_LIB_DIR/$ENGINE_LIB_NAME" \
    || { rm -f "$tmp" "$tmp.sha256"; die "Cannot install ${ENGINE_LIB_DIR}/${ENGINE_LIB_NAME}"; }
  ENGINE_LIB_STAGED=""
  ENGINE_LIB_INSTALLED=true
  ok "Installed ${ENGINE_LIB_DIR}/${ENGINE_LIB_NAME} (owner ${ENGINE_LIB_OWNER}, mode 0644) and its checksum"
}

# install_engine_lib BUNDLE_DIR: stage_engine_lib and commit_engine_lib in one step.
install_engine_lib() {
  stage_engine_lib "$1" && commit_engine_lib
}

# staged_binary DEST: the temporary name stage_binary writes beside DEST.
staged_binary() { printf '%s/.%s.%s' "$(dirname "$1")" "$(basename "$1")" "$$"; }

# stage_binary SRC DEST: writes SRC beside DEST under its temporary name, mode 0755. Returns 1, leaving nothing behind, when it
# cannot (a read-only directory, a full disk). DEST is not touched.
stage_binary() {
  local tmp; tmp=$(staged_binary "$2")
  install -m 0755 "$1" "$tmp" || { rm -f "$tmp"; return 1; }
}

# commit_binary DEST: renames the staged binary over DEST. A rename is atomic: until it, DEST is the binary that was there, and a
# running process keeps the file it was started from.
commit_binary() {
  local tmp; tmp=$(staged_binary "$1")
  mv -f "$tmp" "$1" || { rm -f "$tmp"; return 1; }
}

# discard_binary DEST: removes the staged binary, for an installer that stops after staging.
discard_binary() { rm -f "$(staged_binary "$1")"; }

# check_staged_engine DEST: when a library is staged, runs the staged binary of DEST with --features and --engine-lib naming the
# staged library, in a clean environment (an inherited WAFIO_ENGINE_LIB_REQUIRED=1 would make an unusable library fatal and
# an inherited WAFIO_ENGINE_LIB would name another one), and requires the engine to be reported. It shows that this agent
# loads this library on this host, before any service is stopped or file replaced. A failure removes both staged files.
check_staged_engine() {
  local bin out
  bin=$(staged_binary "$1")
  [[ -n "$ENGINE_LIB_STAGED" ]] || return 0
  local -a limit=()
  ! command -v timeout >/dev/null 2>&1 || limit=(timeout 30)
  out=$(env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin ${limit[@]+"${limit[@]}"} "$bin" --features --engine-lib "$ENGINE_LIB_STAGED" 2>&1) || true
  grep -Eq '^engine: wafio-semantic-engine' <<<"$out" && return 0
  discard_binary "$1"; discard_engine_lib
  die "The new WAF agent does not load its engine library on this host: $(printf '%s' "$out" | tail -n 3 | tr '\n' ' '). Nothing was installed or changed and no service was stopped."
}

# engine_lib_env FILE: after a run that installed a library, WAFIO_ENGINE_LIB_REQUIRED=1 in FILE (an operator's value stays). The
# agent then refuses to start when the library is missing or fails a check, and says why in the journal, instead of
# serving without a semantic engine.
engine_lib_env() {
  $ENGINE_LIB_INSTALLED || return 0
  env_default "$1" WAFIO_ENGINE_LIB_REQUIRED 1
}

# warn_engine_lib_leftovers FILE: after a run that installed no library (the bundle has none), one warning when an earlier install
# left a library in ENGINE_LIB_DIR or WAFIO_ENGINE_LIB_REQUIRED=1 in FILE. Nothing is deleted: the files may be the operator's.
# An agent without the engine linked in loads that library, and with the setting does not start when it does not fit.
warn_engine_lib_leftovers() {
  $ENGINE_LIB_INSTALLED && return 0
  local left=""
  [[ ! -e "$ENGINE_LIB_DIR/$ENGINE_LIB_NAME" ]] || left="${ENGINE_LIB_DIR}/${ENGINE_LIB_NAME} (with its .sha256)"
  if grep -Eq '^[[:space:]]*WAFIO_ENGINE_LIB_REQUIRED=1[[:space:]]*$' "$1" 2>/dev/null; then
    left="${left:+$left and }WAFIO_ENGINE_LIB_REQUIRED=1 in $1"
  fi
  [[ -n "$left" ]] || return 0
  warn "This bundle has no engine library, and an earlier install left ${left}. The installer does not remove them. When this agent is to run without that library, delete the file and its .sha256 and the WAFIO_ENGINE_LIB_REQUIRED line, then restart wafio-waf-agent."
}
# <<< wafio-engine-lib

# ─── Banner ──────────────────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}${CYAN}"
cat <<'BANNER'
  ██╗    ██╗ █████╗ ███████╗██╗ ██████╗
  ██║    ██║██╔══██╗██╔════╝██║██╔═══██╗
  ██║ █╗ ██║███████║█████╗  ██║██║   ██║
  ██║███╗██║██╔══██║██╔══╝  ██║██║   ██║
  ╚███╔███╔╝██║  ██║██║     ██║╚██████╔╝
   ╚══╝╚══╝ ╚═╝  ╚═╝╚═╝     ╚═╝ ╚═════╝
BANNER
echo -e "${NC}"
echo -e "  ${BOLD}WAFio — Web Application Firewall Platform${NC}"
echo -e "  ${GRAY}Installer v2.0 — All-in-One Setup${NC}"
echo ""
hr

# ─── Prerequisites ───────────────────────────────────────────────────────────
[[ $EUID -eq 0 ]] || die "Run as root: sudo bash $0"
command -v curl    &>/dev/null || die "curl required: apt-get install curl"
command -v tar     &>/dev/null || die "tar required"
command -v openssl &>/dev/null || die "openssl required"
command -v python3 &>/dev/null || die "python3 required"

# ─── Defaults ────────────────────────────────────────────────────────────────
PORTAL_API_URL="${PORTAL_API_URL:-https://wafio.cloud}"
INSTALL_DIR="/opt/wafio"
CONFIG_DIR="/etc/wafio"
LOG_DIR="/var/log/wafio"
DATA_DIR="/var/lib/wafio"
SECURITY_DATA_DIR="${INSTALL_DIR}/security-data"
CONFIG_FILE="${CONFIG_DIR}/config.yaml"
CERTS_DIR="${CONFIG_DIR}/certs"
CP_HTTP_PORT=9087
CP_GRPC_PORT=9090
COMPONENT=""
# Detect a usable controlling terminal for interactive prompts. `curl | bash`
# keeps stdin on the pipe, so prompts read from /dev/tty; if it can't be opened
# we run non-interactively and rely on env vars / flags + sane defaults.
if { exec 3</dev/tty; } 2>/dev/null; then HAVE_TTY=true; exec 3<&-; else HAVE_TTY=false; fi
ADMIN_EMAIL=""; ADMIN_PASS=""; ADMIN_NAME=""; PROJECT_ID=""; PROJECT_NAME=""
GRPC_DOMAIN=""; JWT=""
PG_HOST="localhost"; PG_PORT="5432"; PG_USER="postgres"; PG_PASS=""; PG_DB="wafio"
DB_MODE=""   # --db docker|host|existing (else WAFIO_DB_MODE, else asked)

# Agent enrollment / connection inputs (flags win over the environment).
ENROLL_URL="${WAFIO_DASHBOARD_URL:-}"
ENROLL_HOST_KEY="${WAFIO_HOST_KEY:-}"
ENROLL_CA_SHA256="${WAFIO_CA_SHA256:-}"
ENROLL_AGENT_NAME="${WAFIO_AGENT_NAME:-}"
ENROLL_GRPC_SERVER="${WAFIO_GRPC_SERVER:-}"
ENROLL_SERVER_NAME="${WAFIO_GRPC_SERVER_NAME:-}"
ENROLL_DASHBOARD_CACERT="${WAFIO_DASHBOARD_CACERT:-}"
CRED_BUNDLE="${WAFIO_CREDENTIAL_BUNDLE:-}"
HOST_KEY_STDIN=false

# ─── Parse flags ─────────────────────────────────────────────────────────────
# need_val FLAG VALUE — a flag that takes a value got one.
need_val() { [[ -n "${2:-}" && "${2:0:2}" != "--" ]] || die "$1 needs a value."; }
while [[ $# -gt 0 ]]; do
  case "$1" in
    --component) need_val "$1" "${2:-}"; COMPONENT="$2"; shift 2 ;;
    controlplane|waf-agent|host-agent|all) COMPONENT="$1"; shift ;;
    --url|--dashboard-url) need_val "$1" "${2:-}"; ENROLL_URL="$2"; shift 2 ;;
    --url=*|--dashboard-url=*) ENROLL_URL="${1#*=}"; shift ;;
    --host-key) need_val "$1" "${2:-}"; ENROLL_HOST_KEY="$2"; shift 2 ;;
    --host-key=*) ENROLL_HOST_KEY="${1#*=}"; shift ;;
    --host-key-stdin) HOST_KEY_STDIN=true; shift ;;
    --ca-sha256) need_val "$1" "${2:-}"; ENROLL_CA_SHA256="$2"; shift 2 ;;
    --ca-sha256=*) ENROLL_CA_SHA256="${1#*=}"; shift ;;
    --agent-name) need_val "$1" "${2:-}"; ENROLL_AGENT_NAME="$2"; shift 2 ;;
    --agent-name=*) ENROLL_AGENT_NAME="${1#*=}"; shift ;;
    --control-plane) need_val "$1" "${2:-}"; ENROLL_GRPC_SERVER="$2"; shift 2 ;;
    --control-plane=*) ENROLL_GRPC_SERVER="${1#*=}"; shift ;;
    --server-name) need_val "$1" "${2:-}"; ENROLL_SERVER_NAME="$2"; shift 2 ;;
    --server-name=*) ENROLL_SERVER_NAME="${1#*=}"; shift ;;
    --dashboard-cacert) need_val "$1" "${2:-}"; ENROLL_DASHBOARD_CACERT="$2"; shift 2 ;;
    --dashboard-cacert=*) ENROLL_DASHBOARD_CACERT="${1#*=}"; shift ;;
    --bundle) need_val "$1" "${2:-}"; CRED_BUNDLE="$2"; shift 2 ;;
    --bundle=*) CRED_BUNDLE="${1#*=}"; shift ;;
    --db) need_val "$1" "${2:-}"; DB_MODE="$2"; shift 2 ;;
    --db=*) DB_MODE="${1#*=}"; shift ;;
    -h|--help)
      cat <<'HELP'
Usage: sudo bash wafio-install.sh [controlplane|waf-agent|host-agent|all] [options]

One-command agent install (host-key enrollment; the private key is made here
and never leaves this host):
  sudo bash wafio-install.sh host-agent --url https://dashboard.example.com \
       --ca-sha256 <CA SHA-256 from the dashboard> [--host-key wafh_…]
  sudo bash wafio-install.sh waf-agent  --url … --ca-sha256 … [--host-key …] [--agent-name NAME]

  --url URL            dashboard / control plane HTTPS address (http:// only for loopback)
  --ca-sha256 HEX      SHA-256 of the agent CA (Connect this host shows it); required
  --host-key-stdin     read the host's key from the first line of stdin (keeps it
                       out of argv, ps and sudo's log):
                       printf '%s\n' 'wafh_…' | sudo bash wafio-install.sh host-agent --host-key-stdin …
  --host-key KEY       the host's key on the command line (visible in ps and
                       sudo's log); omit both to be asked without echo (or set
                       WAFIO_HOST_KEY). A key enrolls only within 24 h of being
                       issued or rotated, each agent once per key
  --agent-name NAME    agent name (default <hostname>@ebpf / <hostname>@waf)
  --control-plane H:P  gRPC address agents dial (default: what the control plane reports)
  --server-name NAME   name in the control plane's gRPC certificate (default: reported)
  --dashboard-cacert F CA file for a dashboard with a private TLS certificate

Control plane database (controlplane / all):
  --db docker          PostgreSQL 17 + TimescaleDB in its own Docker container
                       (wafio-db, 127.0.0.1 only, data in /var/lib/wafio/postgresql);
                       a PostgreSQL already on this host is not touched
  --db host            install PostgreSQL 17 + TimescaleDB on this host
  --db existing        a PostgreSQL 17+ you already run (asks for its connection)
  Without --db the installer asks (no terminal: host). WAFIO_DB_IMAGE,
  WAFIO_DB_PORT, WAFIO_DB_MEMORY (TimescaleDB tuning, default 1GB) and
  WAFIO_DB_CONTAINER adjust the Docker database.

Manual install (a project credential from the Credentials page):
  --bundle FILE.tar    the credential .tar (ca.crt, client.crt, client.key); or put
                       those files in /etc/wafio/certs/<host|waf>/ before running
  --control-plane H:P, --server-name NAME, --host-key KEY as above
HELP
      exit 0 ;;
    *) warn "Ignoring unknown argument: $1"; shift ;;
  esac
done
if $HOST_KEY_STDIN; then
  [[ -t 0 ]] && die "--host-key-stdin reads the key from a pipe: printf '%s\\n' '<host key>' | sudo bash wafio-install.sh … --host-key-stdin"
  read_host_key_stdin
fi
ENROLL_MODE=false
[[ -n "$ENROLL_URL" ]] && ENROLL_MODE=true
if [[ -n "$ENROLL_CA_SHA256" ]]; then
  _pin="$(normalize_sha256 "$ENROLL_CA_SHA256")"
  [[ -n "$_pin" ]] || die "--ca-sha256 must be 64 hexadecimal characters."
  ENROLL_CA_SHA256="$_pin"
fi

# ─── 1. Component selection ──────────────────────────────────────────────────
step "Component Selection"
if [[ -z "$COMPONENT" ]]; then
  echo ""
  echo "  What would you like to install?"
  echo ""
  echo "    1) All Components (recommended)  — Control Plane + WAF Agent + Host Agent"
  echo "    2) Control Plane only            — WAFio server + web dashboard"
  echo "    3) WAF Agent only                — HTTP L7 reverse proxy and inspection"
  echo "    4) Host Agent only               — eBPF kernel firewall (Linux 5.10+)"
  echo ""
  if $HAVE_TTY; then
    while true; do
      prompt "Your choice [1-4] (Enter = 1): "
      CHOICE=""; read -r CHOICE < /dev/tty || CHOICE=""
      CHOICE="${CHOICE:-1}"
      case "$CHOICE" in
        1) COMPONENT="all" ;;
        2) COMPONENT="controlplane" ;;
        3) COMPONENT="waf-agent" ;;
        4) COMPONENT="host-agent" ;;
        *) printf "  %b✗ Invalid choice '%s'. Enter 1-4 (or just Enter for 1).%b\n" "$RED" "$(_plain "$CHOICE")" "$NC"; continue ;;
      esac
      break
    done
  else
    COMPONENT="all"
    info "No interactive terminal detected — defaulting to All Components."
  fi
fi

INSTALL_CP=false; INSTALL_WAF=false; INSTALL_HOST=false
case "$COMPONENT" in
  all)          INSTALL_CP=true;  INSTALL_WAF=true;  INSTALL_HOST=true ;;
  controlplane) INSTALL_CP=true ;;
  waf-agent)    INSTALL_WAF=true ;;
  host-agent)   INSTALL_HOST=true ;;
  *) die "Unknown component: $COMPONENT" ;;
esac

# ─── Agent connection inputs: checked before anything is downloaded ──────────
[[ -z "$ENROLL_GRPC_SERVER" ]] || valid_grpc_addr "$ENROLL_GRPC_SERVER" \
  || die "--control-plane must be host:port (e.g. cp.example.com:9090)."
[[ -z "$ENROLL_SERVER_NAME" ]] || valid_server_name "$ENROLL_SERVER_NAME" \
  || die "--server-name must be a host name or IP address."
[[ -z "$ENROLL_HOST_KEY" ]] || valid_host_key "$ENROLL_HOST_KEY" \
  || die "The host key is not valid (expected wafh_ followed by 24 characters)."
[[ -z "$CRED_BUNDLE" || -f "$CRED_BUNDLE" ]] || die "Bundle not found: ${CRED_BUNDLE}"
if $ENROLL_MODE; then
  $INSTALL_CP && die "--url enrolls an agent on this host with a host key; use it with host-agent or waf-agent, not with the control plane."
  [[ -z "$CRED_BUNDLE" ]] || die "--url (enrollment) and --bundle (a project credential) exclude each other; pick one."
  check_dashboard_url "$ENROLL_URL" \
    || die "--url must be https://… (http:// is accepted only for 127.0.0.1, localhost or [::1]): the host key travels in the request."
  [[ -n "$ENROLL_CA_SHA256" ]] \
    || die "--ca-sha256 is required with --url: the installer writes nothing unless the control plane's CA has this fingerprint (Connect this host in the dashboard shows the command with it)."
  [[ -z "$ENROLL_DASHBOARD_CACERT" || -f "$ENROLL_DASHBOARD_CACERT" ]] || die "--dashboard-cacert: file not found."
  [[ -z "$ENROLL_AGENT_NAME" ]] || valid_agent_name "$ENROLL_AGENT_NAME" \
    || die "--agent-name may use letters, digits and . _ @ : - (at most 128, starting with a letter or digit)."
  if [[ -z "$ENROLL_HOST_KEY" ]]; then
    $HAVE_TTY || die "No host key: pass --host-key, set WAFIO_HOST_KEY, or run in a terminal to be asked for it."
    echo ""
    while true; do
      ask_secret ENROLL_HOST_KEY "Host key (input hidden): "
      valid_host_key "$ENROLL_HOST_KEY" && break
      echo -e "  ${RED}✗ Expected wafh_ followed by 24 characters (dashboard → Hosts → the host's key).${NC}"
    done
  fi
fi

echo ""
echo -e "  Will install: ${BOLD}"
$INSTALL_CP   && echo "    • Control Plane"
$INSTALL_WAF  && echo "    • WAF Agent"
$INSTALL_HOST && echo "    • Host Agent"
echo -e "${NC}"

# ─── Dashboard mount path (control plane only) ───────────────────────────────
# The pre-built frontend ships with a base-path placeholder (/__WAFIO_BASE__).
# Pick where the dashboard is mounted: domain root (default) or a subpath
# (e.g. /wafio-cp behind a reverse proxy). install_component rewrites the
# placeholder via sed at install time — no frontend rebuild needed.
# Set WAFIO_BASE_PATH env to skip the prompt (non-interactive installs).
WAFIO_BASE_PATH="${WAFIO_BASE_PATH:-__UNSET__}"
if $INSTALL_CP; then
  if [[ "$WAFIO_BASE_PATH" == "__UNSET__" ]]; then
    prompt "Dashboard mount path (empty = domain root, e.g. /wafio-cp) [/]: "
    read -r WAFIO_BASE_PATH < /dev/tty || WAFIO_BASE_PATH=""
  fi
  [[ "$WAFIO_BASE_PATH" == "__UNSET__" ]] && WAFIO_BASE_PATH=""
  WAFIO_BASE_PATH="${WAFIO_BASE_PATH%/}"          # strip trailing slash
  [[ "$WAFIO_BASE_PATH" == "/" ]] && WAFIO_BASE_PATH=""
  if [[ -n "$WAFIO_BASE_PATH" && "${WAFIO_BASE_PATH:0:1}" != "/" ]]; then
    WAFIO_BASE_PATH="/$WAFIO_BASE_PATH"           # ensure leading slash
  fi
  printf '  Dashboard mount path: %b%s%b\n' "$BOLD" "$(_plain "${WAFIO_BASE_PATH:-/ (domain root)}")" "$NC"
else
  WAFIO_BASE_PATH=""
fi

# ─── 1b. Upgrade detection ───────────────────────────────────────────────────
# If an existing WAFio install is found (config present), switch to UPGRADE mode:
# preserve config (JWT secret, DB creds), skip admin/project/credential creation,
# and only refresh binaries + frontend + migrations, then restart services.
# This makes re-running the installer safe and idempotent.
UPGRADE_MODE=false
if $INSTALL_CP && [[ -f "${CONFIG_FILE}" ]]; then
  UPGRADE_MODE=true
elif { $INSTALL_WAF && [[ -f "${CONFIG_DIR}/waf-agent.env" ]]; } \
  || { $INSTALL_HOST && [[ -f "${CONFIG_DIR}/host-agent.env" ]]; }; then
  # Agent-only existing install (no control plane config on this box)
  UPGRADE_MODE=true
fi

if $UPGRADE_MODE; then
  echo ""
  echo -e "  ${BOLD}${YELLOW}Existing WAFio installation detected.${NC}"
  echo "  Running in UPGRADE mode — your config, admin account, projects, and"
  echo "  agent credentials will be preserved. Only binaries, frontend assets,"
  echo "  database migrations, and security data will be refreshed."
  if $ENROLL_MODE; then
    echo "  The agent is enrolled again with the host key: its certificate is"
    echo "  renewed (the previous one is revoked) and its env file updated."
  fi
  echo ""
fi

# ─── 2. WAFio is free — no API key or signup required ────────────────────────
step "WAFio Download"
echo ""
ok "No API key or signup required — WAFio is free to download."

HOSTNAME_VAL=$(hostname -f 2>/dev/null || hostname)
OS_INFO=$(uname -a 2>/dev/null || true)

# ─── 3. Verify portal reachability ───────────────────────────────────────────
step "Checking wafio.cloud reachability"
HTTP_CODE=$(curl -s --max-time 10 -o /dev/null -w "%{http_code}" \
  "${PORTAL_API_URL}/api/download/manifest" 2>/dev/null) \
  || die "Cannot reach ${PORTAL_API_URL}. Check internet connectivity."
[[ "$HTTP_CODE" == "200" || "$HTTP_CODE" == "503" ]] \
  || die "Portal unreachable (HTTP ${HTTP_CODE}). Check ${PORTAL_API_URL}"
ok "Portal reachable"

# ─── 5. OS detection ─────────────────────────────────────────────────────────
step "Operating System Detection"
OS_FAMILY="unknown"; OS_MAJOR=8; PRETTY_NAME="unknown"
if [[ -f /etc/os-release ]]; then
  . /etc/os-release
  case "${ID:-}" in
    ubuntu|debian|raspbian|linuxmint) OS_FAMILY="debian" ;;
    centos|rhel|fedora|rocky|almalinux|ol|amzn)
      OS_FAMILY="rhel"
      OS_MAJOR=$(echo "${VERSION_ID:-8}" | cut -d. -f1) ;;
    *) warn "Unrecognized OS: ${ID:-unknown}. Dependency auto-install disabled." ;;
  esac
fi
ok "OS: ${PRETTY_NAME:-unknown} (family: ${OS_FAMILY})"

pkg_install() {
  case "$OS_FAMILY" in
    debian) DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@" ;;
    rhel)   yum install -y "$@" 2>/dev/null || dnf install -y "$@" ;;
    *) warn "Cannot auto-install: $*. Install manually." ;;
  esac
}
pkg_update() {
  case "$OS_FAMILY" in
    debian) DEBIAN_FRONTEND=noninteractive apt-get update -qq ;;
    rhel)   yum makecache -q 2>/dev/null || dnf makecache -q ;;
    *) : ;;
  esac
}

# >>> wafio-db-setup (wafio-cp-backend: cmd/wafio/install_db_test.go) ────────
# merge_timescale_preload ensures 'timescaledb' is present in the
# shared_preload_libraries directive WITHOUT clobbering any libraries another
# application already configured (pg_stat_statements, pgaudit, pg_cron, etc.).
# Postgres only honours the LAST shared_preload_libraries line, so a naive
# `echo >> conf` would silently disable pre-existing preloads.
merge_timescale_preload() {
  local conf="$1"
  [[ -f "$conf" ]] || { warn "postgresql.conf not found at $conf — set shared_preload_libraries='timescaledb' manually"; return 0; }

  # Already preloaded? nothing to do.
  if grep -Eq "^[[:space:]]*shared_preload_libraries[[:space:]]*=.*timescaledb" "$conf"; then
    return 0
  fi

  # Find the last active (uncommented) shared_preload_libraries line.
  local existing
  existing=$(grep -E "^[[:space:]]*shared_preload_libraries[[:space:]]*=" "$conf" | tail -1)

  if [[ -z "$existing" ]]; then
    # No active directive — append a fresh one.
    echo "shared_preload_libraries = 'timescaledb'  # added by WAFio installer" >> "$conf"
    return 0
  fi

  # Extract current value between the quotes (single or double).
  local current
  current=$(echo "$existing" | sed -E "s/.*shared_preload_libraries[[:space:]]*=[[:space:]]*['\"]?([^'\"]*)['\"]?.*/\1/")
  current=$(echo "$current" | tr -d '[:space:]')

  local merged
  if [[ -z "$current" ]]; then
    merged="timescaledb"
  else
    merged="${current},timescaledb"
  fi

  # Comment out ALL existing active directives, then append the merged one.
  sed -i -E "s/^([[:space:]]*shared_preload_libraries[[:space:]]*=)/# (replaced by WAFio) \1/" "$conf"
  echo "shared_preload_libraries = '${merged}'  # merged by WAFio installer" >> "$conf"
  info "Merged shared_preload_libraries → '${merged}'"
}

# ─── Control-plane database ──────────────────────────────────────────────────
# Three places for the control plane's PostgreSQL 17 + TimescaleDB (--db,
# WAFIO_DB_MODE or the menu):
#   docker    its own container (DB_IMAGE), published on 127.0.0.1 only, data
#             in ${DATA_DIR}/postgresql — another PostgreSQL on this host is
#             never touched
#   host      PostgreSQL 17 packages on this host (its 17/main cluster, on
#             whatever port that cluster has)
#   existing  a server the operator already runs, here or elsewhere
# Every step talks to the server chosen. Until 2026-10-25 the TimescaleDB step
# read the version and the extension over this host's local socket on the
# given port, so a container or a remote server made it install the package
# for, edit and restart this host's own PostgreSQL. It now edits and restarts
# a server only when it is a cluster on this host whose files it can name.
DB_MODE="${DB_MODE:-${WAFIO_DB_MODE:-}}"
DB_CONTAINER="${WAFIO_DB_CONTAINER:-wafio-db}"
DB_IMAGE="${WAFIO_DB_IMAGE:-timescale/timescaledb:2.30.2-pg17}"
DB_DOCKER=false
PG_EXISTS="n"; PG_ADMIN="postgres"; PG_ADMIN_PASS=""
PG_ETC="${WAFIO_PG_ETC:-/etc/postgresql}"
SYSTEMD_DIR="${WAFIO_SYSTEMD_DIR:-/etc/systemd/system}"

# pg_client: the PostgreSQL client itself, not Debian's /usr/bin/psql wrapper
# (see grant_settings_reader); WAFIO_PSQL overrides it (tests).
pg_client() {
  local c bin="${WAFIO_PSQL:-}"
  if [[ -z "$bin" ]]; then
    bin=psql
    for c in /usr/lib/postgresql/*/bin/psql; do [[ -x "$c" ]] && bin="$c"; done
  fi
  printf '%s' "$bin"
}

# port_in_use PORT: something listens on TCP PORT on this host.
port_in_use() { [[ -n "$(ss -ltnH "sport = :$1" 2>/dev/null)" ]]; }

# local_pg_running: a PostgreSQL server already runs on this host.
local_pg_running() { pgrep -x postgres >/dev/null 2>&1; }

# debian_cluster_on_port PORT: "<version> <name>" of the Debian/Ubuntu cluster
# configured on PORT, empty when there is none (or no pg_lsclusters).
debian_cluster_on_port() {
  command -v pg_lsclusters >/dev/null 2>&1 || return 0
  pg_lsclusters -h 2>/dev/null | awk -v p="$1" '$3 == p { print $1, $2; exit }'
}

# db_pick_port: the first TCP port from 5432 that nothing listens on and no
# local cluster is configured for; WAFIO_DB_PORT wins.
db_pick_port() {
  if [[ -n "${WAFIO_DB_PORT:-}" ]]; then printf '%s\n' "$WAFIO_DB_PORT"; return 0; fi
  local p
  for p in $(seq 5432 5450); do
    port_in_use "$p" && continue
    [[ -n "$(debian_cluster_on_port "$p")" ]] && continue
    printf '%s\n' "$p"; return 0
  done
  return 1
}

# pg_admin SQL [DB]: SQL as the superuser of the chosen server, unaligned
# tuples only. The SQL goes on stdin (passwords stay out of argv), never the
# installer's own stdin, which holds the rest of the script under `curl | bash`.
pg_admin() {
  local sql="$1" db="${2:-postgres}" psql_bin
  if $DB_DOCKER; then
    docker exec -i "$DB_CONTAINER" psql -w -X -q -v ON_ERROR_STOP=1 -U postgres -d "$db" -tA <<<"$sql"
    return
  fi
  psql_bin=$(pg_client)
  if [[ -z "$PG_ADMIN_PASS" && "$PG_HOST" == "localhost" ]]; then
    sudo -u postgres "$psql_bin" -w -X -q -v ON_ERROR_STOP=1 -p "$PG_PORT" -d "$db" -tA <<<"$sql"
  else
    PGPASSWORD="$PG_ADMIN_PASS" "$psql_bin" -w -X -q -v ON_ERROR_STOP=1 -h "$PG_HOST" -p "$PG_PORT" \
      -U "$PG_ADMIN" -d "$db" -tA <<<"$sql"
  fi
}

# db_check_login: the control plane's own role can log in to PG_DB.
db_check_login() {
  if $DB_DOCKER; then
    PGPASSWORD="$PG_PASS" docker exec -e PGPASSWORD "$DB_CONTAINER" \
      psql -w -X -q -h 127.0.0.1 -U "$PG_USER" -d "$PG_DB" -c '\q' </dev/null >/dev/null 2>&1
    return
  fi
  PGPASSWORD="$PG_PASS" "$(pg_client)" -w -X -q -h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$PG_DB" \
    -c '\q' </dev/null >/dev/null 2>&1
}

# db_wait_ready SECONDS: the chosen server answers a query (a container that
# keeps restarting fails at once).
db_wait_ready() {
  local i restarts
  for ((i = 0; i < $1; i += 2)); do
    if $DB_DOCKER; then
      docker exec "$DB_CONTAINER" pg_isready -q -h 127.0.0.1 -U postgres </dev/null >/dev/null 2>&1 && return 0
      restarts=$(docker inspect -f '{{.RestartCount}}' "$DB_CONTAINER" 2>/dev/null)
      [[ "${restarts:-0}" =~ ^[0-9]+$ && "$restarts" -ge 3 ]] && return 1
    else
      [[ "$(pg_admin "SELECT 1" 2>/dev/null)" == 1 ]] && return 0
    fi
    sleep 2
  done
  return 1
}

# db_container_port: the 127.0.0.1 port DB_CONTAINER publishes PostgreSQL on.
db_container_port() {
  docker port "$DB_CONTAINER" 5432/tcp 2>/dev/null | sed -nE 's/^127\.0\.0\.1:([0-9]+)$/\1/p' | head -1
}

# db_container_ours: DB_CONTAINER exists and carries the WAFio database label.
db_container_ours() {
  [[ "$(docker inspect -f '{{ index .Config.Labels "cloud.wafio.role" }}' "$DB_CONTAINER" 2>/dev/null)" == db ]]
}

# db_docker_unit_dropin: start the control plane after Docker at boot.
db_docker_unit_dropin() {
  mkdir -p "${SYSTEMD_DIR}/wafio.service.d"
  cat > "${SYSTEMD_DIR}/wafio.service.d/10-database-container.conf" <<DROPIN_EOF
# Written by the WAFio installer: the database runs in Docker container ${DB_CONTAINER}.
[Unit]
After=docker.service
Wants=docker.service
DROPIN_EOF
}

# db_docker_setup: start (or reuse) the database container and create the
# wafio role and database in it; sets PG_HOST, PG_PORT, PG_USER, PG_PASS, PG_DB.
db_docker_setup() {
  command -v docker >/dev/null 2>&1 \
    || die "Docker is not installed (https://docs.docker.com/engine/install/). Install it, or choose another database option."
  docker info >/dev/null 2>&1 \
    || die "The Docker daemon is not reachable (systemctl start docker), or choose another database option."
  local port data_root="${DATA_DIR}/postgresql" env_file="${CONFIG_DIR}/db-container.env"
  if docker inspect "$DB_CONTAINER" >/dev/null 2>&1; then
    db_container_ours \
      || die "A container named ${DB_CONTAINER} exists and is not the WAFio database. Rename it, or set WAFIO_DB_CONTAINER."
    port=$(db_container_port)
    [[ -n "$port" ]] || die "Container ${DB_CONTAINER} does not publish PostgreSQL on 127.0.0.1; remove it and re-run."
    info "Reusing database container ${DB_CONTAINER} (127.0.0.1:${port})"
    docker start "$DB_CONTAINER" >/dev/null || die "Could not start container ${DB_CONTAINER}."
  else
    port=$(db_pick_port) || die "No free TCP port in 5432-5450 for the database container; set WAFIO_DB_PORT."
    [[ "$port" =~ ^[0-9]{1,5}$ ]] || die "WAFIO_DB_PORT must be a port number."
    port_in_use "$port" && die "Port ${port} is in use; set WAFIO_DB_PORT to a free port."
    # The data directory has the same path inside the container, so the
    # data_directory the control plane reads is a path on this host
    # (free-disk alert). Its parent stays traversable for the
    # container's postgres user; the data directory itself is 0700.
    mkdir -p "$CONFIG_DIR" && install -d -m 0755 "$data_root" || die "Cannot create ${data_root}."
    ( umask 077
      printf 'POSTGRES_PASSWORD=%s\nPGDATA=%s\nTIMESCALEDB_TELEMETRY=off\nTS_TUNE_MEMORY=%s\n' \
        "$(openssl rand -hex 24)" "${data_root}/data" "${WAFIO_DB_MEMORY:-1GB}" > "$env_file" ) \
      || die "Cannot write ${env_file}."
    info "Pulling ${DB_IMAGE}..."
    docker pull -q "$DB_IMAGE" >/dev/null || die "Could not pull ${DB_IMAGE}."
    docker run -d --name "$DB_CONTAINER" --label cloud.wafio.role=db --restart unless-stopped \
      -p "127.0.0.1:${port}:5432" --shm-size 256m --log-opt max-size=10m --log-opt max-file=3 \
      --env-file "$env_file" -v "${data_root}:${data_root}" "$DB_IMAGE" >/dev/null \
      || die "Could not start the database container (docker logs ${DB_CONTAINER})."
  fi
  DB_DOCKER=true
  info "Waiting for the database container..."
  if ! db_wait_ready 180; then
    docker logs --tail 15 "$DB_CONTAINER" 2>&1 | sed 's/^/    /'
    die "Database container ${DB_CONTAINER} did not become ready (docker logs ${DB_CONTAINER})."
  fi
  PG_HOST="127.0.0.1"; PG_PORT="$port"; PG_USER="wafio"; PG_DB="wafio"; PG_PASS=$(openssl rand -hex 16)
  info "Creating database user 'wafio' and database 'wafio'..."
  db_create_role && pg_admin "GRANT pg_read_all_settings TO wafio;" >/dev/null 2>&1 \
    || die "Could not create the wafio role and database in ${DB_CONTAINER}."
  db_docker_unit_dropin
  ok "Database container ${DB_CONTAINER} ready (127.0.0.1:${port}, data in ${data_root})"
}

# db_docker_resume: on an upgrade, a configured database that is this host's
# WAFio container is started (and waited for) before the migrations.
db_docker_resume() {
  [[ "$PG_HOST" == 127.0.0.1 || "$PG_HOST" == localhost ]] || return 0
  command -v docker >/dev/null 2>&1 || return 0
  db_container_ours || return 0
  [[ "$(db_container_port)" == "$PG_PORT" ]] || return 0
  DB_DOCKER=true
  docker start "$DB_CONTAINER" >/dev/null 2>&1 || warn "Could not start database container ${DB_CONTAINER}."
  db_wait_ready 120 || warn "Database container ${DB_CONTAINER} is not ready: docker logs ${DB_CONTAINER}"
}

# db_host_setup: PostgreSQL 17 packages on this host; the role and database go
# into the 17/main cluster on the port it has (pgdg puts it on 5433 and up
# when another version holds 5432).
db_host_setup() {
  info "Installing PostgreSQL 17..."
  case "$OS_FAMILY" in
    debian)
      pkg_update && pkg_install gnupg2 lsb-release ca-certificates
      curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
        | gpg --dearmor -o /usr/share/keyrings/postgresql.gpg
      echo "deb [signed-by=/usr/share/keyrings/postgresql.gpg] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \
        > /etc/apt/sources.list.d/pgdg.list
      pkg_update && pkg_install postgresql-17 || die "PostgreSQL 17 install failed."
      pg_lsclusters -h 17 main >/dev/null 2>&1 || pg_createcluster 17 main >/dev/null \
        || die "Could not create the PostgreSQL 17 cluster."
      PG_PORT=$(pg_lsclusters -h 17 main | awk '{ print $3; exit }')
      [[ "$PG_PORT" =~ ^[0-9]+$ ]] || die "Cannot read the port of PostgreSQL 17/main (pg_lsclusters)."
      systemctl enable postgresql >/dev/null 2>&1 || true
      systemctl start postgresql@17-main || die "PostgreSQL 17/main did not start: journalctl -u postgresql@17-main"
      info "PostgreSQL 17 cluster 'main' on port ${PG_PORT}"
      ;;
    rhel)
      # Amazon Linux is in the family for dnf, but the PGDG packages below do not install there (its release has no
      # /etc/redhat-release) and its own PostgreSQL has other paths and unit names.
      [[ "${ID:-}" != amzn ]] \
        || die "PostgreSQL 17 from PGDG does not install on Amazon Linux. Use --db docker, or install postgresql17-server from the Amazon Linux repository and use --db existing."
      local pgdg="https://download.postgresql.org/pub/repos/yum/reporpms/EL-${OS_MAJOR}-x86_64/pgdg-redhat-repo-latest.noarch.rpm"
      yum install -y "$pgdg" 2>/dev/null || dnf install -y "$pgdg"
      yum install -y postgresql17-server 2>/dev/null || dnf install -y postgresql17-server
      /usr/pgsql-17/bin/postgresql-17-setup initdb 2>/dev/null || true
      systemctl enable --now postgresql-17
      PG_PORT=5432
      ;;
    *) die "Please install PostgreSQL 17+ manually, then re-run." ;;
  esac
  db_wait_ready 20 || die "PostgreSQL 17 is not answering on port ${PG_PORT}."
  PG_HOST="localhost"; PG_USER="wafio"; PG_DB="wafio"; PG_PASS=$(openssl rand -hex 16)
  info "Creating database user '${PG_USER}' and database '${PG_DB}'..."
  db_create_role || die "Could not create the wafio role and database."
  ok "Database '${PG_DB}' created"
}

# db_create_role: the wafio role (fresh password) and PG_DB owned by it.
db_create_role() {
  pg_admin "DO \$\$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'wafio') THEN CREATE ROLE wafio LOGIN; END IF; END \$\$;
ALTER ROLE wafio WITH LOGIN PASSWORD '${PG_PASS}';
SELECT 'CREATE DATABASE ${PG_DB} OWNER wafio' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${PG_DB}') \\gexec
GRANT ALL ON DATABASE ${PG_DB} TO wafio;" >/dev/null
}

# db_existing_setup: a server the operator runs; asks for its connection.
db_existing_setup() {
  $HAVE_TTY || die "An existing PostgreSQL needs its connection details: run the installer in a terminal, or use --db docker|host."
  PG_EXISTS="y"
  prompt "PostgreSQL host [localhost]: ";  read -r PG_HOST < /dev/tty; PG_HOST="${PG_HOST:-localhost}"
  prompt "PostgreSQL port [5432]: ";       read -r PG_PORT < /dev/tty; PG_PORT="${PG_PORT:-5432}"
  prompt "PostgreSQL admin user [postgres]: "; read -r PG_ADMIN < /dev/tty; PG_ADMIN="${PG_ADMIN:-postgres}"
  prompt "PostgreSQL admin password (leave empty for peer auth): "; read -rs PG_ADMIN_PASS < /dev/tty; echo ""
  prompt "WAFio database name [wafio]: ";  read -r PG_DB < /dev/tty;   PG_DB="${PG_DB:-wafio}"
  [[ "$PG_PORT" =~ ^[0-9]{1,5}$ ]] || die "The port must be a number."
  [[ "$PG_DB" =~ ^[a-z_][a-z0-9_]{0,62}$ ]] || die "Use a database name of lowercase letters, digits and _."
  command -v "$(pg_client)" >/dev/null 2>&1 || die "psql not found: install the PostgreSQL client (postgresql-client), then re-run."
  info "Testing PostgreSQL connection..."
  [[ "$(pg_admin "SELECT 1" 2>/dev/null)" == 1 ]] || {
    [[ -z "$PG_ADMIN_PASS" && "$PG_HOST" == localhost ]] \
      && die "Cannot connect to PostgreSQL via peer auth. Try setting an admin password."
    die "Cannot connect to PostgreSQL. Verify credentials and retry."
  }
  PG_USER="wafio"; PG_PASS=$(openssl rand -hex 16)
  info "Creating database user 'wafio' and database '${PG_DB}'..."
  db_create_role || die "Failed to create or set the password of PostgreSQL user 'wafio'"
  ok "Database '${PG_DB}' ready"
}

# db_install_timescaledb MAJOR AVAILABLE: install (when not AVAILABLE) and
# preload TimescaleDB on the chosen server, then restart it — only when it is
# a cluster of this host the installer can name.
db_install_timescaledb() {
  local major="$1" avail="$2" conf unit name ver answer
  local how="install package timescaledb-2-postgresql-${major}, set shared_preload_libraries = 'timescaledb' and restart it, or re-run the installer with --db docker"
  case "$PG_HOST" in
    ""|localhost|127.0.0.1|::1|/*) ;;
    *) die "TimescaleDB is not set up on ${PG_HOST}:${PG_PORT}. On that server ${how}." ;;
  esac
  case "$OS_FAMILY" in
    debian)
      read -r ver name <<<"$(debian_cluster_on_port "$PG_PORT")"
      [[ -n "${name:-}" && "$ver" == "$major" ]] \
        || die "Port ${PG_PORT} is not a PostgreSQL ${major} cluster of this host (pg_lsclusters), so the installer will not change it. On that server ${how}."
      conf="${PG_ETC}/${ver}/${name}/postgresql.conf"; unit="postgresql@${ver}-${name}"
      if [[ -z "$avail" ]]; then
        local codename; codename=$(lsb_release -cs 2>/dev/null || echo "jammy")
        curl -fsSL https://packagecloud.io/timescale/timescaledb/gpgkey \
          | gpg --dearmor -o /usr/share/keyrings/timescaledb.gpg 2>/dev/null
        echo "deb [signed-by=/usr/share/keyrings/timescaledb.gpg] https://packagecloud.io/timescale/timescaledb/ubuntu/ ${codename} main" \
          > /etc/apt/sources.list.d/timescaledb.list
        pkg_update
        pkg_install "timescaledb-2-postgresql-${major}" \
          || die "TimescaleDB install failed. See: https://docs.timescale.com/self-hosted/latest/install/"
      fi
      ;;
    rhel)
      conf="/var/lib/pgsql/${major}/data/postgresql.conf"; unit="postgresql-${major}"
      if [[ -z "$avail" ]]; then
        yum install -y "timescaledb-2-postgresql-${major}" 2>/dev/null \
          || dnf install -y "timescaledb-2-postgresql-${major}" 2>/dev/null \
          || die "TimescaleDB install failed. See: https://docs.timescale.com/self-hosted/latest/install/rhel/"
      fi
      ;;
    *) die "Cannot auto-install TimescaleDB on this OS. See: https://docs.timescale.com/self-hosted/latest/install/" ;;
  esac
  # Preload timescaledb — required before CREATE EXTENSION.
  merge_timescale_preload "$conf"
  # Only auto-tune memory/workers on a FRESH install. On a pre-existing
  # PostgreSQL (shared with other databases), changing global tuning could
  # disrupt other workloads — leave operator's settings untouched.
  if [[ "$PG_EXISTS" =~ ^[Yy] ]]; then
    info "Existing PostgreSQL detected — skipping timescaledb-tune (preserving your tuning)"
    if $HAVE_TTY; then
      prompt "Restart ${unit} now to load TimescaleDB (its other databases disconnect briefly)? [Y/n]: "
      read -r answer < /dev/tty
      [[ "${answer:-y}" =~ ^[Yy] ]] || die "Not restarted. Restart ${unit}, then re-run the installer."
    fi
  else
    local pgc=()
    [[ -x "/usr/lib/postgresql/${major}/bin/pg_config" ]] && pgc=(--pg-config="/usr/lib/postgresql/${major}/bin/pg_config")
    timescaledb-tune --quiet --yes --conf-path="$conf" ${pgc[@]+"${pgc[@]}"} 2>/dev/null || true
  fi
  systemctl restart "$unit" || die "Could not restart ${unit}: journalctl -u ${unit}"
  db_wait_ready 30 || die "PostgreSQL did not come back after the restart: journalctl -u ${unit}"
}

# db_timescaledb: TimescaleDB enabled in PG_DB on the chosen server.
db_timescaledb() {
  local num major avail preload
  num=$(pg_admin "SHOW server_version_num") || die "Cannot query PostgreSQL on ${PG_HOST}:${PG_PORT}."
  num="${num//[^0-9]/}"
  [[ -n "$num" ]] || die "Cannot read the PostgreSQL version on ${PG_HOST}:${PG_PORT}."
  major=$(( num / 10000 ))
  info "Detected PostgreSQL major version: ${major}"
  if [[ "$(pg_admin "SELECT 1 FROM pg_extension WHERE extname = 'timescaledb'" "$PG_DB")" == 1 ]]; then
    ok "TimescaleDB extension already enabled"
    return 0
  fi
  avail=$(pg_admin "SELECT 1 FROM pg_available_extensions WHERE name = 'timescaledb'")
  preload=$(pg_admin "SHOW shared_preload_libraries")
  if [[ "$avail" != 1 || "$preload" != *timescaledb* ]]; then
    info "Installing TimescaleDB for PostgreSQL ${major}..."
    [[ "$avail" == 1 ]] || avail=""
    db_install_timescaledb "$major" "$avail"
  fi
  pg_admin "CREATE EXTENSION IF NOT EXISTS timescaledb;" "$PG_DB" >/dev/null \
    && ok "TimescaleDB installed and enabled" \
    || die "Could not enable the TimescaleDB extension in ${PG_DB} on ${PG_HOST}:${PG_PORT}."
}

# db_choose_mode: DB_MODE from --db / WAFIO_DB_MODE, else the menu (no
# terminal: host, as before the menu existed).
db_choose_mode() {
  local def="host" choice
  if [[ -z "$DB_MODE" ]]; then
    local_pg_running && command -v docker >/dev/null 2>&1 && def="docker"
    if $HAVE_TTY; then
      echo "  Where should the control plane's database run?"
      echo "    1) docker    — PostgreSQL 17 + TimescaleDB in its own Docker container (127.0.0.1 only)"
      echo "    2) host      — install PostgreSQL 17 + TimescaleDB on this host"
      echo "    3) existing  — a PostgreSQL 17+ server you already run (this host or another)"
      local_pg_running && echo "  A PostgreSQL server already runs here: docker or existing keeps WAFio apart from it."
      prompt "Database [${def}]: "; read -r choice < /dev/tty
      case "${choice:-$def}" in
        1|docker) DB_MODE="docker" ;;
        2|host) DB_MODE="host" ;;
        3|existing) DB_MODE="existing" ;;
        *) die "Choose 1, 2 or 3." ;;
      esac
    else
      DB_MODE="host"
    fi
  fi
  case "$DB_MODE" in
    docker|host|existing) ;;
    *) die "--db must be docker, host or existing." ;;
  esac
}
# <<< wafio-db-setup ──────────────────────────────────────────────────────────

# >>> wafio-grant-settings-reader ───────────────────────────────────────────────
# grant_settings_reader lets the control plane's database role read the
# server settings (pg_read_all_settings), so it can find data_directory and
# watch the free space of the disk that holds the database.
# The role gains read access to every server setting (including any secret
# written inline into one, e.g. primary_conninfo) and no file or data access.
# Only for a database on this host (the control plane cannot see another
# host's disk), as the postgres superuser over peer auth, on install and on
# every upgrade; WAFIO_SKIP_SETTINGS_GRANT=1 skips it. Best effort: when the
# control plane's own connection does not see data_directory afterwards, the
# free-disk alert stays off and the GRANT to run is printed (Administration ›
# Data retention names it too).
grant_settings_reader() {
  local grant="GRANT pg_read_all_settings TO ${PG_USER};"
  if [[ "${WAFIO_SKIP_SETTINGS_GRANT:-0}" == 1 ]]; then
    info "WAFIO_SKIP_SETTINGS_GRANT=1: database role not granted pg_read_all_settings (free-disk alert off unless granted)."
    return 0
  fi
  local sock=()
  case "$PG_HOST" in
    ""|localhost|127.0.0.1|::1) ;;
    /*) sock=(-h "$PG_HOST") ;;
    *) info "Database on ${PG_HOST}: for the free-disk alert, run '${grant}' there."
       return 0 ;;
  esac
  if [[ ! "$PG_USER" =~ ^[a-z_][a-z0-9_]{0,62}$ ]]; then
    warn "Database role '${PG_USER}' not granted pg_read_all_settings (unusual name); run the GRANT yourself for the free-disk alert."
    return 0
  fi
  [[ "$PG_USER" == "postgres" ]] && return 0
  local seen=""
  if ${DB_DOCKER:-false}; then
    # The WAFio database container (db_docker_setup): grant as its superuser
    # and confirm through the role's own TCP login, inside the container.
    docker exec -i "$DB_CONTAINER" psql -w -X -q -U postgres -d "${PG_DB:-wafio}" -c "$grant" </dev/null >/dev/null 2>&1 || true
    seen=$(PGPASSWORD="${PG_PASS:-}" docker exec -e PGPASSWORD -e PGDATABASE="${PG_DB:-wafio}" -e PGCONNECT_TIMEOUT=10 \
      "$DB_CONTAINER" psql -w -X -q -h 127.0.0.1 -U "$PG_USER" \
      -tAc "SELECT count(*) FROM pg_catalog.pg_settings WHERE name = 'data_directory'" </dev/null 2>/dev/null) || seen=""
    if [[ "$seen" == "1" ]]; then
      ok "Database role '${PG_USER}' may read server settings (free-disk alert)"
    else
      warn "Database role '${PG_USER}' cannot read data_directory; the free-disk alert stays off until you run '${grant}' in ${DB_CONTAINER}."
    fi
    return 0
  fi
  # The PostgreSQL client itself, not Debian's /usr/bin/psql: that Perl
  # pg_wrapper looks up the caller's shadow entry, and a WAFio host agent on
  # this host reports the /etc/shadow read as a CRITICAL incident on every
  # upgrade. WAFIO_PSQL overrides the choice (tests).
  local psql_bin="${WAFIO_PSQL:-}" c
  if [[ -z "$psql_bin" ]]; then
    psql_bin=psql
    for c in /usr/lib/postgresql/*/bin/psql; do [[ -x "$c" ]] && psql_bin="$c"; done
  fi
  # Never prompt (-n, -w) and never read stdin: run as `curl … | sudo bash`,
  # the rest of this script is on stdin, and a psql asking for a password
  # would read it and the installer would skip everything after this line.
  sudo -n -u postgres env PGCONNECT_TIMEOUT=10 "$psql_bin" -w -X -q ${sock[@]+"${sock[@]}"} -p "${PG_PORT:-5432}" -c "$grant" </dev/null >/dev/null 2>&1 || true
  # Confirm through the control plane's own connection: the grant may have
  # reached another local cluster, or the role may not inherit it. The
  # database name goes in PGDATABASE, which psql never reads as a connection
  # string (a -d value with "=" could name another host).
  local host=()
  [[ -n "$PG_HOST" ]] && host=(-h "$PG_HOST")
  seen=$(PGPASSWORD="${PG_PASS:-}" PGDATABASE="${PG_DB:-wafio}" PGCONNECT_TIMEOUT=10 \
    "$psql_bin" -w -X -q ${host[@]+"${host[@]}"} -p "${PG_PORT:-5432}" -U "$PG_USER" \
    -tAc "SELECT count(*) FROM pg_catalog.pg_settings WHERE name = 'data_directory'" </dev/null 2>/dev/null) || seen=""
  if [[ "$seen" == "1" ]]; then
    ok "Database role '${PG_USER}' may read server settings (free-disk alert)"
  else
    warn "Database role '${PG_USER}' cannot read data_directory; the free-disk alert stays off until you run '${grant}' as postgres."
  fi
  return 0
}
# <<< wafio-grant-settings-reader ───────────────────────────────────────────────

# ─── 6. PostgreSQL (control plane only) ──────────────────────────────────────
# UPGRADE: skip PostgreSQL setup entirely. The user + database already exist and
# their credentials are preserved from the existing config (see config-preservation
# below). Re-running CREATE USER / ALTER USER … PASSWORD here would force-reset the
# live DB password to a fresh random value while the preserved config keeps the old
# one — breaking control-plane DB authentication on every upgrade. Migrations below
# verify connectivity with the preserved credentials and fail loudly if wrong.
if $INSTALL_CP && $UPGRADE_MODE; then
  info "Upgrade mode — skipping PostgreSQL setup (preserving existing database + credentials)."
fi
if $INSTALL_CP && ! $UPGRADE_MODE; then
  step "Database Setup (PostgreSQL)"
  echo ""
  echo "  WAFio Control Plane requires PostgreSQL 17+ with TimescaleDB."
  echo ""
  db_choose_mode
  case "$DB_MODE" in
    docker)   db_docker_setup ;;
    host)     db_host_setup ;;
    existing) db_existing_setup ;;
  esac

  info "Testing database connection..."
  db_check_login || die "Cannot connect to PostgreSQL. Verify credentials and retry."
  ok "PostgreSQL connection verified"

  # ─── TimescaleDB ─────────────────────────────────────────────────────────────
  step "TimescaleDB Setup"
  db_timescaledb
fi

# ─── 7. Download binaries ─────────────────────────────────────────────────────
step "Downloading WAFio Binaries"
LATEST_JSON=$(curl -fsSL --max-time 15 "${PORTAL_API_URL}/api/download/manifest" 2>/dev/null || echo '{"version":"dev"}')
VERSION=$(echo "$LATEST_JSON" | python3 -c "import sys,json;print(json.load(sys.stdin).get('version','dev'))" 2>/dev/null || echo "dev")
[[ "$VERSION" =~ ^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$ ]] \
  || die "The release server returned an invalid version ('$(sanitize "$VERSION" | head -c 64)')."
info "WAFio version: ${VERSION}"

mkdir -p "$INSTALL_DIR" "$CONFIG_DIR" "${CERTS_DIR}/waf" "${CERTS_DIR}/host" \
  "$LOG_DIR" "$DATA_DIR" "${INSTALL_DIR}/migrations"

# The agent units the bundles carry, kept in their bundle layout (systemd/<name>.service)
# until the systemd section installs them.
UNIT_STAGE=$(mktemp -d) || die "Cannot create a directory for the agent units."

# >>> wafio-ed25519-lib
# The check of the release signature. OpenSSL 3 verifies an Ed25519 signature with `pkeyutl -rawin`; OpenSSL 1.1.1 (AlmaLinux 8,
# Debian 11, Ubuntu 20.04) cannot do it from the command line at all, and there python3 checks it with its standard library.
# scripts/tests/test_ed25519_verify.py extracts this block, so keep it to functions. The files hold the raw 32-byte public key,
# the raw 64-byte signature and the signed bytes.

# ed25519_pem RAWKEY: the PEM public key of the 32-byte key in the file RAWKEY, on stdout.
ed25519_pem() {
  { printf '\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00'; cat "$1"; } \
    | base64 | fold -w 64 \
    | { echo "-----BEGIN PUBLIC KEY-----"; cat; echo "-----END PUBLIC KEY-----"; }
}

# ed25519_openssl PUB SIG MSG: the verdict of openssl.
ed25519_openssl() {
  local pem rc; pem=$(mktemp) || return 2
  ed25519_pem "$1" > "$pem"
  openssl pkeyutl -verify -pubin -inkey "$pem" -rawin -in "$3" -sigfile "$2" &>/dev/null; rc=$?
  rm -f "$pem"; return $rc
}

# ed25519_openssl_works: whether this openssl verifies Ed25519 from its command line. It asks for the signature of test 2 in
# RFC 8032 section 7.1, which it must accept, and for the same signature over the message with one bit changed, which it
# must refuse (an openssl that answers yes to everything does not verify anything). So the answer depends on the program and
# never on the file that is being checked.
ed25519_openssl_works() {
  local w rc=1; w=$(mktemp -d) || return 2
  printf '%s' 'PUAXw+hDiVqStwqnTRt+vJyYLM8uxJaMwM1V8Sr0Zgw=' | base64 -d > "$w/pub"
  printf '%s' 'kqAJqfDUyrhyDoILX2QlQKKye1QWUD+Ps3YiI+vbadoIWsHkPhWZbkWPNhPQ8R2MOHsurrQwKu6wDSkWErsMAA==' | base64 -d > "$w/sig"
  printf 'r' > "$w/msg"; printf 's' > "$w/changed"
  if ed25519_openssl "$w/pub" "$w/sig" "$w/msg" && ! ed25519_openssl "$w/pub" "$w/sig" "$w/changed"; then rc=0; fi
  rm -rf "$w"; return $rc
}

# ed25519_python PUB SIG MSG: the check of RFC 8032 section 5.1.7 in python3 (-I: the current directory and PYTHONPATH are not
# searched). It refuses a signature of the wrong length, an S that is not below the group order, and a key or R that is not
# a point of the curve. scripts/tests/test_ed25519_verify.py runs this program against the test vectors of the RFC.
ed25519_python() {
  python3 -I - "$1" "$2" "$3" <<'PY'
import hashlib
import sys

P = 2 ** 255 - 19                                            # the field
L = 2 ** 252 + 27742317777372353535851937790883648493        # order of the base point
D = -121665 * pow(121666, P - 2, P) % P                      # curve: -x*x + y*y = 1 + D*x*x*y*y
SQRT_M1 = pow(2, (P - 1) // 4, P)


def inv(x):
    return pow(x, P - 2, P)


def add(a, b):
    # The addition law of the curve. It is complete on Ed25519: it holds for every pair of points, doubling included.
    (x1, y1), (x2, y2) = a, b
    t = D * x1 * x2 * y1 * y2 % P
    return ((x1 * y2 + x2 * y1) * inv(1 + t) % P, (y1 * y2 + x1 * x2) * inv(1 - t) % P)


def mul(k, pt):
    r = (0, 1)
    for bit in bin(k)[2:]:
        r = add(r, r)
        if bit == "1":
            r = add(r, pt)
    return r


def decode(s):
    # 255 bits of y, then the low bit of x. None when s is not the canonical encoding of a point.
    if len(s) != 32:
        return None
    n = int.from_bytes(s, "little")
    y, sign = n & (2 ** 255 - 1), n >> 255
    if y >= P:
        return None
    x2 = (y * y - 1) * inv(D * y * y + 1) % P
    x = pow(x2, (P + 3) // 8, P)
    if (x * x - x2) % P:
        x = x * SQRT_M1 % P
    if (x * x - x2) % P:
        return None
    if x == 0 and sign:
        return None
    return (x if x & 1 == sign else P - x, y)


BASE = decode((4 * inv(5) % P).to_bytes(32, "little"))


def verify(pub, sig, msg):
    if len(pub) != 32 or len(sig) != 64:
        return False
    a, r = decode(pub), decode(sig[:32])
    s = int.from_bytes(sig[32:], "little")
    if a is None or r is None or s >= L:
        return False
    k = int.from_bytes(hashlib.sha512(sig[:32] + pub + msg).digest(), "little") % L
    return mul(s, BASE) == add(r, mul(k, a))


def read(path):
    with open(path, "rb") as f:
        return f.read()


if __name__ == "__main__":
    sys.exit(0 if verify(read(sys.argv[1]), read(sys.argv[2]), read(sys.argv[3])) else 1)
PY
}

# ed25519_verify PUB SIG MSG: 0 when SIG is a valid signature of MSG under PUB. openssl answers when it can verify Ed25519
# (ed25519_openssl_works) and its answer is final, a refusal included; python3 answers only on a host where it cannot.
ed25519_verify() {
  if ed25519_openssl_works; then
    ed25519_openssl "$1" "$2" "$3"
  else
    ed25519_python "$1" "$2" "$3"
  fi
}
# <<< wafio-ed25519-lib

# >>> wafio-download-lib
# Every bundle is downloaded, verified and unpacked, and the WAF agent's glibc is checked, before the
# first service is stopped or the first file is replaced: a refusal then leaves the host as it was.
# scripts/tests/test_install_units.sh extracts this block, so keep it to the two arrays and functions.
declare -A FETCHED_DIR=() FETCHED_TMP=()

# fetch_component COMP BINARY_NAME: downloads, verifies and unpacks the bundle, checks the glibc a WAF
# agent needs, and records where it was unpacked. Touches nothing outside a temporary directory.
fetch_component() {
  local COMP="$1" BINARY_NAME="$2"
  local BUNDLE="wafio-${COMP}-${VERSION}-linux-amd64.tar.gz"
  local URL="${PORTAL_API_URL}/api/download/${COMP}"
  local TMP; TMP=$(mktemp -d) || die "Cannot create a directory for the release download."

  # Check for pre-staged bundle in /tmp (bypasses download for offline/slow installs)
  local STAGED="/tmp/${BUNDLE}"
  if [[ -f "$STAGED" ]]; then
    info "Using pre-staged bundle: ${STAGED}"
    cp "$STAGED" "${TMP}/${BUNDLE}"
  else
    info "Downloading ${BUNDLE}..."
    local _tries=0 _ok=false
    while [[ $_tries -lt 3 ]]; do
      _tries=$((_tries+1))
      curl -fL --retry 3 --retry-delay 5 --retry-max-time 120 \
        -H "X-WAFio-Hostname: ${HOSTNAME_VAL:-$(hostname)}" \
        -H "X-WAFio-OS: ${OS_INFO:-}" \
        -H "X-WAFio-Script-Version: ${VERSION:-dev}" \
        --progress-bar "${URL}" -o "${TMP}/${BUNDLE}" && { _ok=true; break; }
      warn "Download attempt ${_tries}/3 failed, retrying..."
      sleep 5
    done
    if ! $_ok; then rm -rf "$TMP"; die "Failed to download ${URL} after 3 attempts"; fi
  fi

  local SHA256_EXPECTED
  SHA256_EXPECTED=$(echo "$LATEST_JSON" | python3 -c \
    "import sys,json; d=json.load(sys.stdin); print(d.get('bundles',{}).get('${COMP}',{}).get('sha256',''))" 2>/dev/null || true)
  [[ "$SHA256_EXPECTED" =~ ^[0-9a-fA-F]{64}$ ]] \
    || die "Release ${COMP} has no valid SHA-256 in the manifest. Refusing to install."
  SHA256_EXPECTED="${SHA256_EXPECTED,,}"
  local SHA256_ACTUAL
  if command -v sha256sum &>/dev/null; then
    SHA256_ACTUAL=$(sha256sum "${TMP}/${BUNDLE}" | awk '{print $1}')
  else
    SHA256_ACTUAL=$(shasum -a 256 "${TMP}/${BUNDLE}" | awk '{print $1}')
  fi
  [[ "$SHA256_ACTUAL" == "$SHA256_EXPECTED" ]] \
    || die "SHA256 mismatch for ${BUNDLE}. Expected: ${SHA256_EXPECTED}, Got: ${SHA256_ACTUAL}"
  ok "SHA256 verified: ${COMP}"

  # Signatures bind the version and bundle hash to the release key compiled
  # into WAFio. An unsigned or key-substituted manifest cannot authorize code.
  local SIGNATURE PUB MANIFEST_PUB VDIR
  SIGNATURE=$(echo "$LATEST_JSON" | python3 -c \
    "import sys,json; d=json.load(sys.stdin); print(d.get('bundles',{}).get('${COMP}',{}).get('signature',''))" 2>/dev/null || true)
  [[ -n "$SIGNATURE" ]] || die "Release ${COMP} has no Ed25519 signature. Refusing to install."
  PUB="${WAFIO_RELEASE_PUBKEY:-YAo+j/UrWNHCrmgAQDbt9FZRsm5WlcNI0KsesVEAx+k=}"
  MANIFEST_PUB=$(echo "$LATEST_JSON" | python3 -c \
    "import sys,json; print(json.load(sys.stdin).get('public_key',''))" 2>/dev/null || true)
  [[ -z "$MANIFEST_PUB" || "$MANIFEST_PUB" == "$PUB" ]] \
    || die "Release public key differs from the trusted key. Refusing to install."
  VDIR=$(mktemp -d) || die "Cannot create a directory for release signature verification."
  printf '%s' "$PUB" | base64 -d > "${VDIR}/raw.bin" \
    || die "Release public key is invalid base64. Refusing to install."
  [[ $(wc -c < "${VDIR}/raw.bin") -eq 32 ]] \
    || die "Release public key has invalid length. Refusing to install."
  printf 'wafio-release-v1\n%s\n%s' "$VERSION" "$SHA256_EXPECTED" > "${VDIR}/payload"
  printf '%s' "$SIGNATURE" | base64 -d > "${VDIR}/sig.bin" \
    || die "Release signature is invalid base64. Refusing to install."
  [[ $(wc -c < "${VDIR}/sig.bin") -eq 64 ]] \
    || die "Release signature has invalid length. Refusing to install."
  if ed25519_verify "${VDIR}/raw.bin" "${VDIR}/sig.bin" "${VDIR}/payload"; then
    ok "Ed25519 signature verified: ${COMP} (${VERSION})"
  else
    die "Signature verification FAILED for ${COMP}. Refusing to install."
  fi
  rm -rf "$VDIR"

  # A bundle that cannot be unpacked whole (cut short, damaged) stops the install: a cut-off binary must not pass.
  tar xzf "${TMP}/${BUNDLE}" -C "${TMP}" 2>/dev/null \
    || { rm -rf "$TMP"; die "Cannot unpack ${BUNDLE}: the download is damaged or cut short. Nothing was installed or changed."; }
  # Filter macOS metadata entries (._*) to find the real top-level directory
  local EXDIR="${TMP}/$(tar tzf "${TMP}/${BUNDLE}" 2>/dev/null | grep -v '^\._\|/\._' | head -1 | cut -d/ -f1)"
  [[ -d "$EXDIR" && "$EXDIR" != "${TMP}/" ]] || { rm -rf "$TMP"; die "${BUNDLE} has no top-level directory. Nothing was installed or changed."; }
  # The Rust agent needs the glibc it was built with, and its engine library the same and its own checksum: refuse an older
  # host or a damaged library before any service is stopped.
  if [[ "$COMP" == "waf-agent" ]]; then
    glibc_check "${EXDIR}/${BINARY_NAME}"
    verify_engine_lib "$EXDIR"
  fi
  FETCHED_DIR[$COMP]="$EXDIR"
  FETCHED_TMP[$COMP]="$TMP"
}

# The destinations staged by this run, and the state of the WAF agent while the installer holds it stopped. WAF_FILES says which
# agent binary and engine library are in place: "old" (the ones that ran), "mixed" while the two renames are under way, "new".
STAGED_DESTS=()
WAF_STOPPED=false
WAF_FILES=old

# waf_recover STATUS: at a failed exit, removes what was staged and no rename took, and starts the WAF agent again when this run
# stopped it and the binary and library in place are a pair (the old pair, or the new one), saying which. After a failure
# between the two renames the pair may not fit, and the agent is left stopped.
waf_recover() {
  local rc="$1" d
  [[ "$rc" != 0 ]] || return 0
  for d in ${STAGED_DESTS[@]+"${STAGED_DESTS[@]}"}; do discard_binary "$d"; done
  discard_engine_lib
  $WAF_STOPPED || return 0
  WAF_STOPPED=false
  if [[ "$WAF_FILES" == mixed ]]; then
    warn "The install failed after wafio-waf-agent was stopped, while its binary and engine library were being replaced, so the two may not belong together. wafio-waf-agent was left stopped. Run the installer again, or put the files right by hand and run: systemctl start wafio-waf-agent"
    return 0
  fi
  local which="previous"; [[ "$WAF_FILES" == new ]] && which="new"
  if systemctl start wafio-waf-agent; then
    warn "The install failed after wafio-waf-agent was stopped. It was started again with its ${which} binary and engine library; the rest of the install (unit, settings, credentials) did not finish, so run the installer again."
  else
    warn "The install failed after wafio-waf-agent was stopped, and it could not be started again. The binary and engine library in place are the ${which} pair: check journalctl -u wafio-waf-agent, then run the installer again."
  fi
}
exit_hooks() { waf_recover "$1"; }

# stage_component COMP BINARY_NAME DEST: writes the binary of the bundle beside DEST and, for the WAF agent, its library beside
# its own destination, then checks that the staged agent loads the staged library on this host. It changes nothing in place and
# runs for every component before the first service is stopped, so a refusal here leaves the host as it was.
stage_component() {
  local COMP="$1" BINARY_NAME="$2" DEST="$3" EXDIR="${FETCHED_DIR[$1]}"
  STAGED_DESTS+=("$DEST")
  [[ "$COMP" != "waf-agent" ]] || stage_engine_lib "$EXDIR"
  stage_binary "${EXDIR}/${BINARY_NAME}" "$DEST" \
    || die "Cannot write ${DEST}. Nothing was changed and no service was stopped."
  [[ "$COMP" != "waf-agent" ]] || check_staged_engine "$DEST"
}

# install_component COMP BINARY_NAME DEST: replaces the binary with the one stage_component staged (a rename, the library of the
# WAF agent first), after it stopped the running service.
install_component() {
  local COMP="$1" BINARY_NAME="$2" DEST="$3"
  local EXDIR="${FETCHED_DIR[$COMP]}" TMP="${FETCHED_TMP[$COMP]}"
  local SVC=""
  case "$COMP" in
    controlplane) SVC="wafio" ;;
    waf-agent)    SVC="wafio-waf-agent" ;;
    host-agent)   SVC="wafio-host-agent" ;;
  esac
  if [[ -n "$SVC" ]] && systemctl is-active --quiet "$SVC" 2>/dev/null; then
    info "Stopping ${SVC} before replacing binary..."
    systemctl stop "$SVC" 2>/dev/null || true
    [[ "$COMP" != "waf-agent" ]] || WAF_STOPPED=true
    sleep 1
  fi
  [[ "$COMP" != "waf-agent" ]] || { WAF_FILES=mixed; commit_engine_lib; }
  commit_binary "$DEST" || die "Cannot replace ${DEST}"
  [[ "$COMP" != "waf-agent" ]] || WAF_FILES=new
  [[ -x "$DEST" ]] || die "Cannot install ${DEST}"
  ok "Installed ${DEST}"
  if [[ "$COMP" == "controlplane" ]]; then
    if [[ -d "${EXDIR}/frontend" ]]; then
      # Keep the previous build's hashed chunks: a browser that cached the old
      # index.html still asks for them, and without them the page stays blank
      # until a hard reload. Names are content hashes, so they never clash.
      OLD_IMMUTABLE=""
      if [[ -d "${INSTALL_DIR}/frontend/_app/immutable" ]]; then
        OLD_IMMUTABLE="$(mktemp -d)"
        cp -a "${INSTALL_DIR}/frontend/_app/immutable/." "${OLD_IMMUTABLE}/" 2>/dev/null || true
      fi
      rm -rf "${INSTALL_DIR}/frontend"
      if [[ -f "${EXDIR}/frontend/index.html" ]]; then
        cp -r "${EXDIR}/frontend" "${INSTALL_DIR}/frontend"
        # Rewrite the base-path placeholder to the chosen mount path (empty =
        # root). Covers asset/router base + API base baked into the static files.
        find "${INSTALL_DIR}/frontend" -type f \
          \( -name '*.html' -o -name '*.js' -o -name '*.json' -o -name '*.css' \) \
          -exec sed -i "s#/__WAFIO_BASE__#${WAFIO_BASE_PATH}#g" {} +
        if [[ -n "${OLD_IMMUTABLE}" ]]; then
          # Old chunks already carry the base path; copy only what the new
          # build lacks, then drop carried-over chunks older than 30 days.
          mkdir -p "${INSTALL_DIR}/frontend/_app/immutable"
          cp -a -n "${OLD_IMMUTABLE}/." "${INSTALL_DIR}/frontend/_app/immutable/" 2>/dev/null || true
          find "${INSTALL_DIR}/frontend/_app/immutable" -type f -mtime +30 -delete 2>/dev/null || true
          rm -rf "${OLD_IMMUTABLE}"
        fi
        ok "Frontend assets installed (mount path: ${WAFIO_BASE_PATH:-/ root})"
      else
        die "Bundle is missing frontend/index.html. Re-build the bundle with: ./scripts/release.sh ${VERSION}"
      fi
    else
      die "Bundle is missing frontend/ directory. Re-build the bundle with: ./scripts/release.sh ${VERSION}"
    fi
    [[ -d "${EXDIR}/migrations" ]] && { rm -rf "${INSTALL_DIR}/migrations"; cp -r "${EXDIR}/migrations" "${INSTALL_DIR}/migrations"; ok "Migrations directory installed"; }
  fi
  if [[ "$COMP" == "host-agent" ]]; then
    # Extract eBPF objects (CO-RE compiled, pre-built) from bundle
    if [[ -d "${EXDIR}/ebpf" ]]; then
      mkdir -p "${INSTALL_DIR}/ebpf"
      cp "${EXDIR}/ebpf/"*.o "${INSTALL_DIR}/ebpf/" 2>/dev/null || true
      rm -f "${INSTALL_DIR}/ebpf/wafio_lsm.o"  # left by a version that shipped it
      ok "eBPF objects installed to ${INSTALL_DIR}/ebpf/"
    fi
  fi
  stage_bundled_unit "$EXDIR" "$SVC" "$UNIT_STAGE" || die "Cannot stage ${SVC}.service from the ${COMP} bundle."
  rm -rf "$TMP"
}

# install_components: fetches every selected bundle, then installs them.
install_components() {
  if $INSTALL_CP;   then fetch_component "controlplane" "wafio"; fi
  if $INSTALL_WAF;  then fetch_component "waf-agent"    "wafio-waf-agent"; fi
  if $INSTALL_HOST; then fetch_component "host-agent"   "wafio-host-agent"; fi
  # Everything that can fail is written and checked before the first service is stopped.
  trap 'exit_hooks "$?"' EXIT
  if $INSTALL_CP;   then stage_component "controlplane" "wafio"            "/usr/local/bin/wafio"; fi
  if $INSTALL_WAF;  then stage_component "waf-agent"    "wafio-waf-agent"  "/usr/local/bin/wafio-waf-agent"; fi
  if $INSTALL_HOST; then stage_component "host-agent"   "wafio-host-agent" "/usr/local/bin/wafio-host-agent"; fi
  if $INSTALL_CP;   then install_component "controlplane" "wafio"            "/usr/local/bin/wafio"; fi
  if $INSTALL_WAF;  then install_component "waf-agent"    "wafio-waf-agent"  "/usr/local/bin/wafio-waf-agent"; fi
  if $INSTALL_HOST; then install_component "host-agent"   "wafio-host-agent" "/usr/local/bin/wafio-host-agent"; fi
}
# <<< wafio-download-lib
install_components

# ─── 8. Security data ─────────────────────────────────────────────────────────
step "Downloading Security Data"
info "Fetching: GeoIP, FireHOL, JA4 fingerprints, Bot signatures..."
info "This may take 2-5 minutes depending on connection speed."
echo ""
# >>> wafio-fetch-lib (scripts/tests/test_install_fetch.sh)
# security_data_fetcher CP WAF HOST prints "<binary> <profile>" for the
# security data download. The control plane binary fetches whenever it is
# installed; an agent-only server has none, so the agent binary just
# installed fetches its own data (both agents have fetch-data; the host
# agent alone needs only the GeoIP country database).
security_data_fetcher() {
  local cp=$1 waf=$2 host=$3
  if [[ "$cp" == true ]]; then
    if [[ "$waf" == true || "$host" == true ]]; then
      echo "/usr/local/bin/wafio all"
    else
      echo "/usr/local/bin/wafio control-plane"
    fi
  elif [[ "$waf" == true ]]; then
    echo "/usr/local/bin/wafio-waf-agent agent"
  elif [[ "$host" == true ]]; then
    echo "/usr/local/bin/wafio-host-agent host-agent"
  else
    echo "/usr/local/bin/wafio all"
  fi
}
# <<< wafio-fetch-lib

read -r FETCH_BIN FETCH_PROFILE < <(security_data_fetcher "$INSTALL_CP" "$INSTALL_WAF" "$INSTALL_HOST")
FETCH_NAME=$(basename "$FETCH_BIN")
if [[ -x "$FETCH_BIN" ]]; then
  if (cd "${CONFIG_DIR}" 2>/dev/null || cd /; "$FETCH_BIN" fetch-data --dir "${SECURITY_DATA_DIR}" --profile "${FETCH_PROFILE}") 2>/dev/null; then
    ok "Security data stored at ${SECURITY_DATA_DIR}"
  else
    warn "Security data download incomplete. Re-run: ${FETCH_NAME} fetch-data --dir ${SECURITY_DATA_DIR} --profile ${FETCH_PROFILE}"
  fi
else
  warn "Binary not yet available — run: ${FETCH_NAME} fetch-data --dir ${SECURITY_DATA_DIR} --profile ${FETCH_PROFILE}"
fi

# ─── 9. Config + migrations + admin setup (control plane) ────────────────────
if $INSTALL_CP; then
  step "Configuring Control Plane"
  GRPC_DOMAIN=$(hostname -f 2>/dev/null || hostname)

  if $UPGRADE_MODE && [[ -f "${CONFIG_FILE}" ]]; then
    # Preserve existing secrets/credentials — never regenerate on upgrade
    # (regenerating JWT logs out all users; regenerating DB creds breaks login).
    info "Preserving existing config (JWT secret + database credentials)..."
    _OLD_JWT=$(grep -E '^\s*secret:' "${CONFIG_FILE}" | head -1 | sed -E 's/.*secret:\s*"?([^"]*)"?.*/\1/')
    _OLD_PG_HOST=$(grep -E '^\s*host:' "${CONFIG_FILE}" | head -1 | sed -E 's/.*host:\s*"?([^"]*)"?.*/\1/')
    _OLD_PG_PORT=$(grep -E '^\s*port:' "${CONFIG_FILE}" | head -1 | sed -E 's/.*port:\s*([0-9]+).*/\1/')
    _OLD_PG_USER=$(grep -E '^\s*user:' "${CONFIG_FILE}" | head -1 | sed -E 's/.*user:\s*"?([^"]*)"?.*/\1/')
    _OLD_PG_PASS=$(grep -E '^\s*password:' "${CONFIG_FILE}" | head -1 | sed -E 's/.*password:\s*"?([^"]*)"?.*/\1/')
    _OLD_PG_DB=$(grep -E '^\s*name:' "${CONFIG_FILE}" | head -1 | sed -E 's/.*name:\s*"?([^"]*)"?.*/\1/')
    [[ -n "$_OLD_JWT" ]]     && JWT_SECRET="$_OLD_JWT"
    [[ -n "$_OLD_PG_HOST" ]] && PG_HOST="$_OLD_PG_HOST"
    [[ -n "$_OLD_PG_PORT" ]] && PG_PORT="$_OLD_PG_PORT"
    [[ -n "$_OLD_PG_USER" ]] && PG_USER="$_OLD_PG_USER"
    [[ -n "$_OLD_PG_PASS" ]] && PG_PASS="$_OLD_PG_PASS"
    [[ -n "$_OLD_PG_DB" ]]   && PG_DB="$_OLD_PG_DB"
    # Preserve TOTP encryption key — regenerating it makes existing TOTP
    # secrets undecryptable (users would have to re-enroll 2FA).
    _OLD_TOTP=$(grep -E '^\s*enc_key:' "${CONFIG_FILE}" | head -1 | sed -E 's/.*enc_key:\s*"?([^"]*)"?.*/\1/')
    [[ -n "$_OLD_TOTP" ]] && TOTP_ENC_KEY="$_OLD_TOTP"
    # Back up the old config before the upgrade touches it
    cp "${CONFIG_FILE}" "${CONFIG_FILE}.bak.$(date +%s 2>/dev/null || echo old)" 2>/dev/null || true
  fi
  : "${JWT_SECRET:=$(openssl rand -hex 32)}"
  : "${TOTP_ENC_KEY:=$(openssl rand -hex 32)}"

  if $UPGRADE_MODE && [[ -f "${CONFIG_FILE}" ]]; then
    # Keep the operator's config as it is: everything beyond the secrets
    # (smtp, server.base_url, trusted_proxies, log level, limits …) used to be
    # lost on every upgrade because the file was regenerated from the
    # template. New settings have defaults, so an older file still boots; the
    # one key the control plane refuses to start without is totp.enc_key,
    # which older installers did not write — add it only when it is missing.
    if grep -qE '^[[:space:]]+enc_key:[[:space:]]*"?[^"[:space:]]+' "${CONFIG_FILE}"; then
      : # set — keep it (regenerating it makes stored TOTP secrets unreadable)
    elif grep -qE '^[[:space:]]+enc_key:' "${CONFIG_FILE}"; then
      sed -i -E "s|^([[:space:]]+)enc_key:.*$|\\1enc_key: \"${TOTP_ENC_KEY}\"|" "${CONFIG_FILE}"
      info "Filled the empty totp.enc_key in ${CONFIG_FILE}"
    elif grep -qE '^totp:[[:space:]]*$' "${CONFIG_FILE}"; then
      sed -i "/^totp:[[:space:]]*$/a\\  enc_key: \"${TOTP_ENC_KEY}\"" "${CONFIG_FILE}"
      info "Added the missing totp.enc_key to ${CONFIG_FILE}"
    else
      printf '\ntotp:\n  enc_key: "%s"\n' "${TOTP_ENC_KEY}" >> "${CONFIG_FILE}"
      info "Added the missing totp.enc_key to ${CONFIG_FILE}"
    fi
  else
  cat > "${CONFIG_FILE}" <<YAML_EOF
server:
  env: production
  http_addr: ":${CP_HTTP_PORT}"
  agent_grpc_addr: ":${CP_GRPC_PORT}"
  grpc_domain: "${GRPC_DOMAIN}"
  frontend_path: "${INSTALL_DIR}/frontend"

database:
  host: "${PG_HOST}"
  port: ${PG_PORT}
  user: "${PG_USER}"
  password: "${PG_PASS}"
  name: "${PG_DB}"
  sslmode: disable

jwt:
  secret: "${JWT_SECRET}"
  expire_hours: 720

geo:
  country_db_path: "${SECURITY_DATA_DIR}/geoip/country.mmdb"
  city_db_path: "${SECURITY_DATA_DIR}/geoip/city.mmdb"
  asn_db_path: "${SECURITY_DATA_DIR}/geoip/asn.mmdb"

bot_defaults:
  ua_bad_bot_file: "${SECURITY_DATA_DIR}/user-agents/bot.txt"
  ja4_blacklist_file: "${SECURITY_DATA_DIR}/ja4/ja4.txt"
  ja4_allowlist_file: "${SECURITY_DATA_DIR}/ja4/ja4_allowlist.txt"

totp:
  enc_key: "${TOTP_ENC_KEY}"

mtls:
  certs_dir: "${CERTS_DIR}/agent"
  cert_validity_days: 365
YAML_EOF
  fi
  chmod 600 "${CONFIG_FILE}"
  # Create config/ subdir symlink: setup handler looks for config/config.yaml relative to WorkingDirectory
  mkdir -p "${INSTALL_DIR}/config"
  ln -sf "${CONFIG_FILE}" "${INSTALL_DIR}/config/config.yaml"
  # Also symlink at root level for backward compat (migrate command)
  ln -sf "${CONFIG_FILE}" "${INSTALL_DIR}/config.yaml"
  if $UPGRADE_MODE; then ok "Config kept: ${CONFIG_FILE} (backup next to it)"; else ok "Config written to ${CONFIG_FILE}"; fi

  $UPGRADE_MODE && db_docker_resume
  grant_settings_reader

  step "Running Database Migrations"
  MIGRATIONS_PATH="${INSTALL_DIR}/migrations"
  [[ -d "$MIGRATIONS_PATH" ]] || die "Migrations not found at ${MIGRATIONS_PATH}. Check bundle integrity."
  info "Applying migrations to ${PG_DB}..."
  # Pass --migrations explicitly so the binary always finds them regardless of cwd
  (cd "${INSTALL_DIR}" && /usr/local/bin/wafio migrate up --migrations "${MIGRATIONS_PATH}") \
    || die "Migration failed. Check DB credentials in ${CONFIG_FILE}."
  ok "All database migrations applied"

if $UPGRADE_MODE; then
  info "Upgrade mode — skipping admin/project/credential creation (already provisioned)."
else
  step "Creating Admin Account"
  echo ""
  info "Starting WAFio temporarily for initial setup..."
  (cd "${INSTALL_DIR}" && /usr/local/bin/wafio serve > /tmp/wafio-setup.log 2>&1) &
  SETUP_PID=$!

  # Wait for ready
  READY=false
  for i in $(seq 1 40); do
    if curl -sf "http://127.0.0.1:${CP_HTTP_PORT}/health" &>/dev/null 2>&1; then
      READY=true; break
    fi
    sleep 1
  done
  if ! $READY; then
    echo "--- Last 20 lines of /tmp/wafio-setup.log ---" >&2
    tail -20 /tmp/wafio-setup.log >&2 || true
    # Terminate using python to avoid bash kill variable restriction
    python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGKILL)" 2>/dev/null || true
    die "Control plane did not start within 40s. See /tmp/wafio-setup.log"
  fi
  ok "Control plane is ready for setup"

  echo ""
  echo "  Create your WAFio administrator account:"
  echo ""
  $HAVE_TTY || die "Interactive terminal required to create the admin account. Run the installer in a terminal."
  ask_req ADMIN_NAME  "Full name: "
  ask_req ADMIN_EMAIL "Email address: " '^[^@[:space:]]+@[^@[:space:]]+\.[^@[:space:]]+$' "Enter a valid email address (e.g. you@example.com)."
  while true; do
    prompt "Password (min 8 chars): ";           read -rs ADMIN_PASS < /dev/tty  || ADMIN_PASS="";  echo ""
    prompt "Confirm password: ";                 read -rs ADMIN_PASS2 < /dev/tty || ADMIN_PASS2=""; echo ""
    if [[ "$ADMIN_PASS" == "$ADMIN_PASS2" ]] && [[ ${#ADMIN_PASS} -ge 8 ]]; then
      break
    fi
    echo -e "  ${RED}✗ Passwords do not match or too short. Try again.${NC}"
  done

  # Create the first administrator with the wafio CLI, which reads /etc/wafio/config.yaml via INSTALL_DIR.
  info "Creating administrator account (wafio admin create)..."
  ADMIN_RESP=$(cd "${INSTALL_DIR}" && /usr/local/bin/wafio admin create \
    --email "${ADMIN_EMAIL}" --name "${ADMIN_NAME}" --password "${ADMIN_PASS}" 2>&1) || {
    python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGKILL)" 2>/dev/null || true
    die "Admin creation failed: ${ADMIN_RESP}"
  }
  ok "Admin account created: ${ADMIN_EMAIL}"

  info "Logging in to provision project and agent credentials..."
  LOGIN_RESP=$(curl -sf -X POST "http://127.0.0.1:${CP_HTTP_PORT}/api/login" \
    -H "Content-Type: application/json" \
    -d "{\"email\":\"${ADMIN_EMAIL}\",\"password\":\"${ADMIN_PASS}\"}" 2>&1) || {
    python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGKILL)" 2>/dev/null || true
    die "Login failed: ${LOGIN_RESP}"
  }
  JWT=$(echo "$LOGIN_RESP" | python3 -c "import sys,json;print(json.load(sys.stdin)['token'])" 2>/dev/null) || {
    python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGKILL)" 2>/dev/null || true
    die "Could not extract JWT from login response"
  }

  echo ""
  prompt "Project name [My Infrastructure]: "; read -r PROJECT_NAME < /dev/tty
  PROJECT_NAME="${PROJECT_NAME:-My Infrastructure}"

  PROJECT_RESP=$(curl -sf -X POST "http://127.0.0.1:${CP_HTTP_PORT}/api/projects" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer ${JWT}" \
    -d "{\"name\":\"${PROJECT_NAME}\"}" 2>&1) || {
    python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGKILL)" 2>/dev/null || true
    die "Create project failed: ${PROJECT_RESP}"
  }
  PROJECT_ID=$(echo "$PROJECT_RESP" | python3 -c "import sys,json;print(json.load(sys.stdin)['id'])" 2>/dev/null) || {
    python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGKILL)" 2>/dev/null || true
    die "Could not extract project ID"
  }
  # The id goes into URLs and the summary: a UUID, nothing else.
  [[ "$PROJECT_ID" =~ ^[0-9a-fA-F-]{36}$ ]] || {
    python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGKILL)" 2>/dev/null || true
    die "The control plane returned an invalid project ID."
  }
  ok "Project '${PROJECT_NAME}' created (ID: ${PROJECT_ID})"

  if $INSTALL_WAF; then
    info "Provisioning WAF agent gRPC credentials..."
    CRED_RESP=$(curl -sf -X POST "http://127.0.0.1:${CP_HTTP_PORT}/api/projects/${PROJECT_ID}/agent-grpc-credentials" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer ${JWT}" \
      -d '{"name":"waf-agent-1"}' 2>&1) || { warn "WAF credential failed — provision via dashboard later"; CRED_RESP=""; }
    if [[ -n "$CRED_RESP" ]]; then
      WAF_CA=$(echo "$CRED_RESP"   | python3 -c "import sys,json;print(json.load(sys.stdin).get('ca_cert',''))"     2>/dev/null || true)
      WAF_CERT=$(echo "$CRED_RESP" | python3 -c "import sys,json;print(json.load(sys.stdin).get('client_cert',''))" 2>/dev/null || true)
      WAF_KEY=$(echo "$CRED_RESP"  | python3 -c "import sys,json;print(json.load(sys.stdin).get('client_key',''))"  2>/dev/null || true)
      if [[ -n "$WAF_CA" ]] && [[ -n "$WAF_KEY" ]]; then
        echo "$WAF_CA"   > "${CERTS_DIR}/waf/ca.crt"
        echo "$WAF_CERT" > "${CERTS_DIR}/waf/client.crt"
        echo "$WAF_KEY"  > "${CERTS_DIR}/waf/client.key"
        chmod 600 "${CERTS_DIR}/waf/client.key"
        ok "WAF agent certificates saved to ${CERTS_DIR}/waf/"
      fi
    fi
  fi

  if $INSTALL_HOST; then
    info "Registering host and provisioning host agent credentials..."
    HOST_RESP=$(curl -sf -X POST "http://127.0.0.1:${CP_HTTP_PORT}/api/projects/${PROJECT_ID}/hosts" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer ${JWT}" \
      -d "{\"name\":\"$(hostname)\",\"description\":\"Provisioned by install.sh\"}" 2>&1) || HOST_RESP=""
    H_KEY_VAL=$(echo "$HOST_RESP" | python3 -c "import sys,json;print(json.load(sys.stdin).get('host_key',''))" 2>/dev/null || true)
    valid_host_key "$H_KEY_VAL" || H_KEY_VAL=""
    [[ -n "$H_KEY_VAL" ]] && { echo "$H_KEY_VAL" > "${CONFIG_DIR}/host.key"; chmod 600 "${CONFIG_DIR}/host.key"; }

    HCRED_RESP=$(curl -sf -X POST "http://127.0.0.1:${CP_HTTP_PORT}/api/projects/${PROJECT_ID}/agent-grpc-credentials" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer ${JWT}" \
      -d '{"name":"host-agent-1"}' 2>&1) || { warn "Host credential failed — provision via dashboard later"; HCRED_RESP=""; }
    if [[ -n "$HCRED_RESP" ]]; then
      HC=$(echo "$HCRED_RESP"    | python3 -c "import sys,json;print(json.load(sys.stdin).get('ca_cert',''))"     2>/dev/null || true)
      HCERT=$(echo "$HCRED_RESP" | python3 -c "import sys,json;print(json.load(sys.stdin).get('client_cert',''))" 2>/dev/null || true)
      HKEY=$(echo "$HCRED_RESP"  | python3 -c "import sys,json;print(json.load(sys.stdin).get('client_key',''))"  2>/dev/null || true)
      if [[ -n "$HC" ]] && [[ -n "$HKEY" ]]; then
        echo "$HC"    > "${CERTS_DIR}/host/ca.crt"
        echo "$HCERT" > "${CERTS_DIR}/host/client.crt"
        echo "$HKEY"  > "${CERTS_DIR}/host/client.key"
        chmod 600 "${CERTS_DIR}/host/client.key"
        ok "Host agent certificates saved to ${CERTS_DIR}/host/"
      fi
    fi
  fi

  # Stop the temporary setup server
  python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGTERM)" 2>/dev/null || true
  sleep 2
  python3 -c "import os,signal; os.kill(${SETUP_PID}, signal.SIGKILL)" 2>/dev/null || true
  sleep 1
  # Ensure ports are fully released before systemd takes over
  PIDS_9087=$(lsof -ti:${CP_HTTP_PORT} 2>/dev/null || true)
  PIDS_9090=$(lsof -ti:${CP_GRPC_PORT} 2>/dev/null || true)
  [ -n "$PIDS_9087" ] && kill -9 $PIDS_9087 2>/dev/null || true
  [ -n "$PIDS_9090" ] && kill -9 $PIDS_9090 2>/dev/null || true
  [ -n "$PIDS_9087" ] || [ -n "$PIDS_9090" ] && sleep 1 || true
fi  # end if ! $UPGRADE_MODE (admin/project/credential setup)
fi  # end if $INSTALL_CP

# ─── Agent-only config (no control plane on same box) ────────────────────────
# Three ways in, per agent:
#   --url …          enrollment with the host key: key + CSR made here, the
#                    control plane issues a certificate bound to this host and
#                    agent (also on an existing install: that renews it);
#   upgrade          an existing env file is kept (only --control-plane /
#                    --server-name / --bundle given now are applied);
#   manual           a project credential: --bundle, files already in
#                    /etc/wafio/certs/<agent>/, or pasted PEM blocks (terminal).
# UPGRADE without flags never prompts: prompting via /dev/tty would abort a
# non-interactive `curl | sudo bash` upgrade AFTER the binary was swapped,
# leaving the service stopped. The systemd section below (re)starts services.

# manual_credential DIR — install the project credential of a manual install.
manual_credential() {
  local dest="$1" ca crt key
  if [[ -n "$CRED_BUNDLE" ]]; then
    extract_credential_bundle "$CRED_BUNDLE" "$dest"
    ok "Credential installed from ${CRED_BUNDLE}"
    return 0
  fi
  if have_credential_files "$dest"; then
    is_pem_cert "${dest}/ca.crt" && is_pem_cert "${dest}/client.crt" && is_pem_key "${dest}/client.key" \
      || die "${dest} holds ca.crt, client.crt and client.key, but they are not valid PEM files."
    chmod 600 "${dest}/client.key"
    ok "Using the credential already in ${dest}"
    return 0
  fi
  $HAVE_TTY || die "No credential: pass --bundle <credential .tar>, put ca.crt, client.crt and client.key in ${dest}, or enroll with --url (see --help)."
  echo ""
  read_pem ca  "CA certificate"
  read_pem crt "client certificate"
  read_pem key "client private key"
  ENROLL_WORK=$(mktemp -d "${CONFIG_DIR}/.manual.XXXXXX") || die "Cannot create a work directory in ${CONFIG_DIR}"
  trap 'rc=$?; enroll_cleanup; exit_hooks "$rc"' EXIT
  chmod 700 "$ENROLL_WORK"
  ( umask 077
    printf '%s' "$ca"  > "${ENROLL_WORK}/ca.crt"
    printf '%s' "$crt" > "${ENROLL_WORK}/client.crt"
    printf '%s' "$key" > "${ENROLL_WORK}/client.key" )
  install_credential_files "$ENROLL_WORK" "$dest"
  enroll_cleanup
  trap 'exit_hooks "$?"' EXIT
}

# manual_grpc_target — the gRPC address (flag/env or prompt) and the optional
# server name of a manual install, into ENR_GRPC_ENDPOINT / ENR_SERVER_NAME.
manual_grpc_target() {
  ENR_GRPC_ENDPOINT="$ENROLL_GRPC_SERVER"
  if [[ -z "$ENR_GRPC_ENDPOINT" ]]; then
    $HAVE_TTY || die "No gRPC address: pass --control-plane host:9090 (or set WAFIO_GRPC_SERVER)."
    while true; do
      ask_req ENR_GRPC_ENDPOINT "Control plane gRPC address (host:9090): " '^[^[:space:]]+:[0-9]+$' "Use host:port form, e.g. cp.example.com:9090."
      valid_grpc_addr "$ENR_GRPC_ENDPOINT" && break
      echo -e "  ${RED}✗ Use host:port form, e.g. cp.example.com:9090.${NC}"
    done
  fi
  ENR_SERVER_NAME="$ENROLL_SERVER_NAME"
  if [[ -z "$ENR_SERVER_NAME" ]] && $HAVE_TTY; then
    while true; do
      prompt "Name in the control plane's gRPC certificate (Enter = the address's host): "
      ENR_SERVER_NAME=""; read -r ENR_SERVER_NAME < /dev/tty || ENR_SERVER_NAME=""
      ENR_SERVER_NAME="${ENR_SERVER_NAME//[[:space:]]/}"
      [[ -z "$ENR_SERVER_NAME" ]] || valid_server_name "$ENR_SERVER_NAME" && break
      echo -e "  ${RED}✗ Enter a host name or IP address, or nothing.${NC}"
    done
  fi
}

# upgrade_apply_flags FILE CERT_DIR — on an upgrade, apply only what was asked.
upgrade_apply_flags() {
  local file="$1" certs="$2"
  [[ -n "$ENROLL_GRPC_SERVER" ]] && { env_set "$file" WAFIO_GRPC_SERVER "$ENROLL_GRPC_SERVER"; ok "WAFIO_GRPC_SERVER set in ${file}"; }
  [[ -n "$ENROLL_SERVER_NAME" ]] && { env_set "$file" WAFIO_GRPC_SERVER_NAME "$ENROLL_SERVER_NAME"; ok "WAFIO_GRPC_SERVER_NAME set in ${file}"; }
  [[ -n "$CRED_BUNDLE" ]] && { extract_credential_bundle "$CRED_BUNDLE" "$certs"; ok "Credential replaced from ${CRED_BUNDLE}"; }
  return 0
}

# drop_rule_set_env FILE: removes the three rule set variables v1 wrote, which the agent no longer reads. A FILE
# without WAFIO_SECURITY_DATA_DIR gets the directory WAFIO_CRS_DEFAULT_DIR pointed into (<dir>/crs,
# <dir>/crs/coreruleset or <dir>/crs/coreruleset/rules), so an upgrade keeps the data it already holds.
drop_rule_set_env() {
  local f="$1" old
  [[ -f "$f" ]] || return 0
  old=$(sed -n 's/^WAFIO_CRS_DEFAULT_DIR=//p' "$f" | tail -n1)
  if [[ -n "$old" ]] && ! grep -q '^WAFIO_SECURITY_DATA_DIR=' "$f"; then
    old="${old%/}"; old="${old%/rules}"; old="${old%/coreruleset}"; old="${old%/crs}"
    [[ -z "$old" ]] || env_set "$f" WAFIO_SECURITY_DATA_DIR "$old"
  fi
  env_unset "$f" WAFIO_CRS_DEFAULT_DIR
  env_unset "$f" WAFIO_CRS_SETUP_FILE
  env_unset "$f" WAFIO_CRS_RULES_GLOB
}

# write_waf_data_env FILE — the WAF agent's security-data paths.
write_waf_data_env() {
  local f="$1"
  drop_rule_set_env "$f"
  env_set "$f" WAFIO_SECURITY_DATA_DIR "${SECURITY_DATA_DIR}"
  env_set "$f" WAFIO_GEO_COUNTRY_DB_PATH "${SECURITY_DATA_DIR}/geoip/country.mmdb"
  env_set "$f" WAFIO_GEO_CITY_DB_PATH "${SECURITY_DATA_DIR}/geoip/city.mmdb"
  env_set "$f" WAFIO_GEO_ASN_DB_PATH "${SECURITY_DATA_DIR}/geoip/asn.mmdb"
  env_set "$f" WAFIO_UA_BAD_BOT_FILE "${SECURITY_DATA_DIR}/user-agents/bot.txt"
  env_set "$f" WAFIO_JA4_BLACKLIST_FILE "${SECURITY_DATA_DIR}/ja4/ja4.txt"
  env_set "$f" WAFIO_JA4_ALLOWLIST_FILE "${SECURITY_DATA_DIR}/ja4/ja4_allowlist.txt"
}

if $INSTALL_WAF && ! $INSTALL_CP && $ENROLL_MODE; then
  step "WAF Agent Enrollment"
  WAF_AGENT_NAME="${ENROLL_AGENT_NAME:-$(hostname)@waf}"
  enroll_agent waf "$WAF_AGENT_NAME" "${CERTS_DIR}/waf"
  enroll_resolve_target
  write_agent_env "${CONFIG_DIR}/waf-agent.env" "$WAF_AGENT_NAME" "${CERTS_DIR}/waf"
  write_waf_data_env "${CONFIG_DIR}/waf-agent.env"
  ok "WAF agent environment file written (${CONFIG_DIR}/waf-agent.env)"
elif $INSTALL_WAF && ! $INSTALL_CP && $UPGRADE_MODE; then
  info "Upgrade mode — preserving existing waf-agent.env (gRPC address + credentials)."
  upgrade_apply_flags "${CONFIG_DIR}/waf-agent.env" "${CERTS_DIR}/waf"
  drop_rule_set_env "${CONFIG_DIR}/waf-agent.env"
elif $INSTALL_WAF && ! $INSTALL_CP; then
  step "WAF Agent Configuration"
  echo ""
  echo "  Manual install with a project credential (dashboard → Credentials)."
  echo "  One-command install with the host key instead: see --help (--url)."
  echo ""
  manual_grpc_target
  WAF_AGENT_NAME="$ENROLL_AGENT_NAME"
  if [[ -z "$WAF_AGENT_NAME" ]] && $HAVE_TTY; then
    prompt "Agent name [waf-agent-1]: "; read -r WAF_AGENT_NAME < /dev/tty || WAF_AGENT_NAME=""
  fi
  WAF_AGENT_NAME="${WAF_AGENT_NAME:-waf-agent-1}"
  valid_agent_name "$WAF_AGENT_NAME" || die "Agent name '${WAF_AGENT_NAME}' is not valid (letters, digits and . _ @ : -)."
  manual_credential "${CERTS_DIR}/waf"
  write_agent_env "${CONFIG_DIR}/waf-agent.env" "$WAF_AGENT_NAME" "${CERTS_DIR}/waf"
  write_waf_data_env "${CONFIG_DIR}/waf-agent.env"
  ok "WAF agent environment file written"
fi

if $INSTALL_CP && $INSTALL_WAF && ! $UPGRADE_MODE; then
  cat > "${CONFIG_DIR}/waf-agent.env" <<ENV_EOF
WAFIO_GRPC_SERVER=127.0.0.1:${CP_GRPC_PORT}
WAFIO_GRPC_SERVER_NAME=${GRPC_DOMAIN}
WAFIO_AGENT_NAME=waf-agent-1
WAFIO_GRPC_CA_CERT=${CERTS_DIR}/waf/ca.crt
WAFIO_GRPC_CLIENT_CERT=${CERTS_DIR}/waf/client.crt
WAFIO_GRPC_CLIENT_KEY=${CERTS_DIR}/waf/client.key
WAFIO_SECURITY_DATA_DIR=${SECURITY_DATA_DIR}
WAFIO_GEO_COUNTRY_DB_PATH=${SECURITY_DATA_DIR}/geoip/country.mmdb
WAFIO_GEO_CITY_DB_PATH=${SECURITY_DATA_DIR}/geoip/city.mmdb
WAFIO_GEO_ASN_DB_PATH=${SECURITY_DATA_DIR}/geoip/asn.mmdb
WAFIO_UA_BAD_BOT_FILE=${SECURITY_DATA_DIR}/user-agents/bot.txt
WAFIO_JA4_BLACKLIST_FILE=${SECURITY_DATA_DIR}/ja4/ja4.txt
WAFIO_JA4_ALLOWLIST_FILE=${SECURITY_DATA_DIR}/ja4/ja4_allowlist.txt
ENV_EOF
  chmod 600 "${CONFIG_DIR}/waf-agent.env"
fi

if $INSTALL_HOST && ! $INSTALL_CP && $ENROLL_MODE; then
  step "Host Agent Enrollment"
  # The agent's own default name is <hostname>@ebpf; the env file pins it so
  # a later hostname change does not leave the enrolled name behind.
  HOST_AGENT_NAME="${ENROLL_AGENT_NAME:-$(hostname)@ebpf}"
  enroll_agent host "$HOST_AGENT_NAME" "${CERTS_DIR}/host"
  enroll_resolve_target
  write_agent_env "${CONFIG_DIR}/host-agent.env" "$HOST_AGENT_NAME" "${CERTS_DIR}/host"
  ok "Host agent environment file written (${CONFIG_DIR}/host-agent.env)"
elif $INSTALL_HOST && ! $INSTALL_CP && $UPGRADE_MODE; then
  info "Upgrade mode — preserving existing host-agent.env (gRPC address + host key + certs)."
  upgrade_apply_flags "${CONFIG_DIR}/host-agent.env" "${CERTS_DIR}/host"
  [[ -n "$ENROLL_HOST_KEY" ]] && { env_set "${CONFIG_DIR}/host-agent.env" WAFIO_HOST_KEY "$ENROLL_HOST_KEY"; ok "WAFIO_HOST_KEY updated"; }
elif $INSTALL_HOST && ! $INSTALL_CP; then
  step "Host Agent Configuration"
  echo ""
  echo "  Manual install with a project credential (dashboard → Hosts + Credentials)."
  echo "  One-command install with the host key instead: see --help (--url)."
  echo ""
  manual_grpc_target
  H_KEY_INPUT="$ENROLL_HOST_KEY"
  if [[ -z "$H_KEY_INPUT" ]]; then
    $HAVE_TTY || die "No host key: pass --host-key or set WAFIO_HOST_KEY."
    while true; do
      ask_secret H_KEY_INPUT "Host key (dashboard → Hosts; input hidden): "
      valid_host_key "$H_KEY_INPUT" && break
      echo -e "  ${RED}✗ Expected wafh_ followed by 24 characters.${NC}"
    done
  fi
  manual_credential "${CERTS_DIR}/host"
  HOST_AGENT_NAME="${ENROLL_AGENT_NAME:-}"
  write_agent_env "${CONFIG_DIR}/host-agent.env" "${HOST_AGENT_NAME:-$(hostname)@ebpf}" "${CERTS_DIR}/host"
  # A project credential needs the host key to bind the agent to its host.
  env_set "${CONFIG_DIR}/host-agent.env" WAFIO_HOST_KEY "$H_KEY_INPUT"
  ok "Host agent environment file written"
fi

if $INSTALL_CP && $INSTALL_HOST && ! $UPGRADE_MODE; then
  H_KEY_VAL=$(cat "${CONFIG_DIR}/host.key" 2>/dev/null || echo "")
  cat > "${CONFIG_DIR}/host-agent.env" <<ENV_EOF
WAFIO_GRPC_SERVER=127.0.0.1:${CP_GRPC_PORT}
WAFIO_GRPC_SERVER_NAME=${GRPC_DOMAIN}
WAFIO_GRPC_CA_CERT=${CERTS_DIR}/host/ca.crt
WAFIO_GRPC_CLIENT_CERT=${CERTS_DIR}/host/client.crt
WAFIO_GRPC_CLIENT_KEY=${CERTS_DIR}/host/client.key
WAFIO_HOST_KEY=${H_KEY_VAL}

WAFIO_SERVER_URL=http://127.0.0.1:${CP_HTTP_PORT}
ENV_EOF
  chmod 600 "${CONFIG_DIR}/host-agent.env"
fi

# ─── 12. Systemd services ─────────────────────────────────────────────────────
step "Installing Systemd Services"

if $INSTALL_CP; then
  cat > /etc/systemd/system/wafio.service <<SVC_EOF
[Unit]
Description=WAFio Control Plane
After=network.target postgresql.service

[Service]
Type=simple
User=root
WorkingDirectory=${INSTALL_DIR}
ExecStart=/usr/local/bin/wafio serve
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
SyslogIdentifier=wafio
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
SVC_EOF
  systemctl daemon-reload
  systemctl enable wafio
  systemctl start wafio
  sleep 3
  systemctl is-active --quiet wafio \
    && ok "wafio control plane service started" \
    || warn "wafio service issue — check: journalctl -u wafio -n 50"
fi

# The host agent starts first: its restart makes the local API token readable by group wafio, and
# a WAF agent that starts earlier logs "IP jail inactive" for a token that is about to be readable.
if $INSTALL_HOST && [[ -s "${CERTS_DIR}/host/client.key" ]]; then
  _NIC=$(ip -o link show | grep -v 'lo:' | grep 'state UP' | head -1 | awk -F': ' '{print $2}' | awk '{print $1}' 2>/dev/null || echo "eth0")
  _EBPF_DIR="${INSTALL_DIR}/ebpf"
  if install_bundled_unit "$UNIT_STAGE" wafio-host-agent /etc/systemd/system /usr/local/bin; then
    ensure_wafio_account group
    host_unit_env "${CONFIG_DIR}/host-agent.env" "${_NIC:-eth0}" "$_EBPF_DIR" "${SECURITY_DATA_DIR}/geoip/country.mmdb" \
      || die "Cannot write the host agent settings"
    ok "Installed the host agent unit from the bundle"
  else
    cat > /etc/systemd/system/wafio-host-agent.service <<SVC_EOF
[Unit]
Description=WAFio Host Agent (eBPF)
After=network.target

[Service]
Type=simple
User=root
EnvironmentFile=${CONFIG_DIR}/host-agent.env
ExecStart=/usr/local/bin/wafio-host-agent \
  --interface=${_NIC} \
  --geoip-db=${SECURITY_DATA_DIR}/geoip/country.mmdb \
  --xdp-obj=${_EBPF_DIR}/wafio_xdp.o \
  --tc-obj=${_EBPF_DIR}/wafio_tc.o \
  --trace-obj=${_EBPF_DIR}/wafio_trace.o \
  --ebpf \
  --trace
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
SyslogIdentifier=wafio-host-agent
LimitNOFILE=65536
# /run/wafio holds the per-boot local API token the WAF agent reads
# for IP-jail pushes; kept across stops for other wafio units.
RuntimeDirectory=wafio
RuntimeDirectoryMode=0755
RuntimeDirectoryPreserve=yes

[Install]
WantedBy=multi-user.target
SVC_EOF
  fi
  systemctl daemon-reload
  systemctl enable wafio-host-agent
  # restart, not start: a renewed certificate must replace the one a
  # running agent holds (the control plane revoked it at renewal).
  systemctl restart wafio-host-agent
  sleep 3
  systemctl is-active --quiet wafio-host-agent \
    && ok "wafio-host-agent service started" \
    || warn "wafio-host-agent issue — check: journalctl -u wafio-host-agent -n 30"
elif $INSTALL_HOST; then
  warn "Host agent certificates not found — provision credentials from dashboard, then:"
  warn "  sudo systemctl start wafio-host-agent"
fi

if $INSTALL_WAF && [[ -s "${CERTS_DIR}/waf/client.key" ]]; then
  # With an engine library in place the agent must not start without it.
  engine_lib_env "${CONFIG_DIR}/waf-agent.env" || die "Cannot write the WAF agent settings"
  warn_engine_lib_leftovers "${CONFIG_DIR}/waf-agent.env"
  # An upgrade of an all-in-one install keeps the env file v1 wrote: its rule set lines go here, for every WAF install.
  drop_rule_set_env "${CONFIG_DIR}/waf-agent.env"
  install_bundled_unit "$UNIT_STAGE" wafio-waf-agent /etc/systemd/system /usr/local/bin \
    || die "The WAF agent bundle has no systemd unit (systemd/wafio-waf-agent.service). Use a bundle of a current release."
  # The bundled unit runs as user wafio: it reads the credential through the
  # group and writes the security data it syncs.
  waf_unit_setup /etc/systemd/system "$SECURITY_DATA_DIR" "${CERTS_DIR}/waf"
  ok "Installed the WAF agent unit from the bundle"
  systemctl daemon-reload
  systemctl enable wafio-waf-agent
  # restart, not start: a renewed certificate must replace the one a
  # running agent holds (the control plane revoked it at renewal).
  systemctl restart wafio-waf-agent
  WAF_STOPPED=false
  sleep 2
  systemctl is-active --quiet wafio-waf-agent \
    && ok "wafio-waf-agent service started" \
    || warn "wafio-waf-agent issue — check: journalctl -u wafio-waf-agent -n 30"
elif $INSTALL_WAF; then
  warn "WAF agent certificates not found — provision credentials from dashboard, then:"
  warn "  sudo systemctl start wafio-waf-agent"
fi

rm -rf "$UNIT_STAGE"

# ─── 13. Health check ─────────────────────────────────────────────────────────
if $INSTALL_CP; then
  step "Final Health Check"
  HOST_IP=$(hostname -I | awk '{print $1}')
  HEALTHY=false
  for i in $(seq 1 20); do
    curl -sf "http://127.0.0.1:${CP_HTTP_PORT}/health" &>/dev/null && { HEALTHY=true; break; }
    sleep 2
  done
  $HEALTHY \
    && ok "Control plane is healthy at http://${HOST_IP}:${CP_HTTP_PORT}" \
    || warn "Health check failed — check: journalctl -u wafio -n 50"
fi

# ─── Done ─────────────────────────────────────────────────────────────────────
HOST_IP=$(hostname -I | awk '{print $1}' 2>/dev/null || echo "YOUR_SERVER_IP")

echo ""
hr
echo -e "  ${GREEN}${BOLD}✓  WAFio Installation Complete!${NC}"
hr
echo ""
$INSTALL_CP && printf '  %bDashboard URL:%b    %s\n' "$BOLD" "$NC" "$(sanitize "http://${HOST_IP}:${CP_HTTP_PORT}")"
$INSTALL_CP && [[ -n "$ADMIN_EMAIL" ]]  && printf '  %bAdmin email:%b      %s\n' "$BOLD" "$NC" "$(sanitize "$ADMIN_EMAIL")"
$INSTALL_CP && [[ -n "$PROJECT_ID" ]]   && printf '  %bProject ID:%b       %s\n' "$BOLD" "$NC" "$(sanitize "$PROJECT_ID")"
echo ""
echo -e "  ${BOLD}Service status:${NC}"
$INSTALL_CP   && echo "    sudo systemctl status wafio"
$INSTALL_WAF  && echo "    sudo systemctl status wafio-waf-agent"
$INSTALL_HOST && echo "    sudo systemctl status wafio-host-agent"
echo ""
echo -e "  ${BOLD}View logs:${NC}"
$INSTALL_CP   && echo "    sudo journalctl -u wafio -f"
$INSTALL_WAF  && echo "    sudo journalctl -u wafio-waf-agent -f"
$INSTALL_HOST && echo "    sudo journalctl -u wafio-host-agent -f"
echo ""
echo -e "  ${BOLD}Documentation:${NC}   https://wafio.cloud/docs"
echo ""
hr
echo ""
