#!/usr/bin/env sh
# VelaHub One-Line Linux Self-Hosted Installer (Proprietary Binary Distribution)
# Website: https://velacloud.app/velahub
#
# Quick start (defaults: ports 28416/28417, Public P2P Acceleration ON, auto egress IP & firewall):
#   curl --proto '=https' --tlsv1.2 -fsSL https://download.velacloud.app/velahub/install.sh | sudo sh
#
# Customize host, ports, firewall, or disable public P2P acceleration via environment variables:
#   curl --proto '=https' --tlsv1.2 -fsSL https://download.velacloud.app/velahub/install.sh | \
#     sudo VELAHUB_PUBLIC_HOST=hub.example.com \
#          VELAHUB_SIGNAL_PORT=38416 \
#          VELAHUB_RELAY_PORT=38417 \
#          VELAHUB_PUBLIC_P2P_ACCEL=true \
#          VELAHUB_AUTO_FIREWALL=true sh

set -eu

VELAHUB_VERSION="${VELAHUB_VERSION:-0.5.0}"
VELAHUB_DOWNLOAD_BASE="${VELAHUB_DOWNLOAD_BASE:-https://download.velacloud.app/velahub}"
VELAHUB_ALLOW_INSECURE_DOWNLOAD_BASE="${VELAHUB_ALLOW_INSECURE_DOWNLOAD_BASE:-false}"
VELAHUB_SIGNAL_PORT_EXPLICIT="${VELAHUB_SIGNAL_PORT:-}"
VELAHUB_RELAY_PORT_EXPLICIT="${VELAHUB_RELAY_PORT:-}"
VELAHUB_SIGNAL_PORT="${VELAHUB_SIGNAL_PORT:-28416}"
VELAHUB_RELAY_PORT="${VELAHUB_RELAY_PORT:-28417}"
VELAHUB_RELAY_RATE_MBPS="${VELAHUB_RELAY_RATE_MBPS:-100}"
VELAHUB_PUBLIC_P2P_ACCEL="${VELAHUB_PUBLIC_P2P_ACCEL:-true}"
VELAHUB_PUBLIC_HOST_EXPLICIT="${VELAHUB_PUBLIC_HOST:-}"
VELAHUB_PUBLIC_HOST="${VELAHUB_PUBLIC_HOST:-}"
VELAHUB_AUTO_PUBLIC_IP="${VELAHUB_AUTO_PUBLIC_IP:-true}"
VELAHUB_AUTO_FIREWALL="${VELAHUB_AUTO_FIREWALL:-true}"
VELAHUB_WSS_URL="${VELAHUB_WSS_URL:-}"
VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS_EXPLICIT="${VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS:-}"
VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS="${VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS:-}"
VELAHUB_DUAL_STACK_EXPLICIT="${VELAHUB_DUAL_STACK:-}"
VELAHUB_DUAL_STACK="${VELAHUB_DUAL_STACK:-false}"

BIN_PATH="/usr/local/bin/velahub"
DATA_DIR="/var/lib/velahub"
ENV_DIR="/etc/velahub"
ENV_FILE="${ENV_DIR}/velahub.env"
UNIT_PATH="/etc/systemd/system/velahub.service"

DETECTED_PUBLIC_IP=""
DETECTED_PUBLIC_FAMILY=""
FIREWALL_STATUS=""
PUBLIC_HOST_SOURCE=""

NL='
'
CR="$(printf '\r')"

log() {
  printf '\033[1;36m[velahub]\033[0m %s\n' "$1"
}

warn() {
  printf '\033[1;33m[velahub]\033[0m %s\n' "$1" >&2
}

die() {
  printf '\033[1;31m[velahub] ERROR:\033[0m %s\n' "$1" >&2
  exit 1
}

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || die "Required command '$1' not found. Please install it first."
}

has_newline_or_cr() {
  case "$1" in
    *"${NL}"*|*"${CR}"*) return 0 ;;
    *) return 1 ;;
  esac
}

is_truthy() {
  case "$1" in
    true|1|yes|on) return 0 ;;
    *) return 1 ;;
  esac
}

validate_version() {
  if [ -z "$1" ] || has_newline_or_cr "$1"; then
    die "Invalid VELAHUB_VERSION '$1': must match semver"
  fi
  if ! printf '%s\n' "$1" | awk '
    NR == 1 && /^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9]+)*$/ { ok = 1 }
    NR > 1 { ok = 0 }
    END { exit(ok ? 0 : 1) }
  '; then
    die "Invalid VELAHUB_VERSION '$1': must match ^[0-9]+\\.[0-9]+\\.[0-9]+([.-][A-Za-z0-9]+)*\$"
  fi
}

validate_uint() {
  _var_name="$1"
  _val="$2"
  if [ -z "${_val}" ] || has_newline_or_cr "${_val}"; then
    die "Invalid ${_var_name} '${_val}': must be a non-negative integer"
  fi
  case "${_val}" in
    *[!0-9]*) die "Invalid ${_var_name} '${_val}': must be a non-negative integer" ;;
  esac
}

validate_port() {
  if [ -z "$1" ] || has_newline_or_cr "$1"; then
    die "Invalid port '$1': must be an integer 1..65535"
  fi
  case "$1" in
    *[!0-9]*) die "Invalid port '$1': must be an integer 1..65535" ;;
  esac
  if [ "$1" -lt 1 ] || [ "$1" -gt 65535 ]; then
    die "Invalid port '$1': must be 1..65535"
  fi
}

is_valid_port() {
  if [ -z "$1" ] || has_newline_or_cr "$1"; then
    return 1
  fi
  case "$1" in
    *[!0-9]*) return 1 ;;
  esac
  [ "$1" -ge 1 ] && [ "$1" -le 65535 ]
}

validate_bool() {
  if has_newline_or_cr "$1"; then
    die "Invalid boolean '$1': expected true or false"
  fi
  case "$1" in
    true|false|1|0|yes|no|on|off) ;;
    *) die "Invalid boolean '$1': expected true or false" ;;
  esac
}

validate_host() {
  if has_newline_or_cr "$1"; then
    die "Invalid VELAHUB_PUBLIC_HOST: must not contain newlines"
  fi
  case "$1" in
    *[!A-Za-z0-9.:_\[\]-]*)
      die "Invalid VELAHUB_PUBLIC_HOST '$1': contains disallowed characters"
      ;;
  esac
}

validate_wss_url() {
  _url="$1"
  if [ -z "${_url}" ] || has_newline_or_cr "${_url}"; then
    die "Invalid VELAHUB_WSS_URL: must be a single-line wss:// URL"
  fi
  case "${_url}" in
    *[[:space:]]*|*\;*|*\$*|*\`*|*\'*|*\"*|*\\*)
      die "Invalid VELAHUB_WSS_URL '${_url}': contains disallowed whitespace or shell metacharacters"
      ;;
  esac
  if ! printf '%s\n' "${_url}" | awk '
    BEGIN { ok = 0 }
    NR > 1 { ok = 0; exit }
    /^wss:\/\// {
      rest = substr($0, 7)
      slash = match(rest, /[\/?#]/)
      if (slash > 0) {
        auth = substr(rest, 1, slash - 1)
        tail = substr(rest, slash)
      } else {
        auth = rest
        tail = ""
      }
      # Authority strictly restricted to [A-Za-z0-9._:\[\]-] (no userinfo @ or unsafe symbols)
      if (auth == "" || auth !~ /^[][A-Za-z0-9._:-]+$/) next
      if (substr(auth, 1, 1) == "[") {
        if (auth !~ /^\[[0-9A-Fa-f:]+\](:[0-9]+)?$/) next
        if (index(auth, "]:") > 0) {
          port = substr(auth, index(auth, "]:") + 2)
          if (port !~ /^[0-9]+$/ || port + 0 < 1 || port + 0 > 65535) next
        }
      } else {
        if (index(auth, "[") > 0 || index(auth, "]") > 0) next
        if (index(auth, ":") > 0) {
          host = auth
          sub(/:[^:]*$/, "", host)
          if (index(host, ":") > 0) next
          port = substr(auth, length(host) + 2)
          if (host == "" || port !~ /^[0-9]+$/ || port + 0 < 1 || port + 0 > 65535) next
        } else {
          host = auth
        }
        if (host !~ /^[A-Za-z0-9._-]+$/ || host ~ /^\./ || host ~ /\.$/ || index(host, "..") > 0) next
      }
      if (tail != "" && tail !~ /^[\/?#][A-Za-z0-9._~:\/?#@!&()*+,=%-]*$/) next
      ok = 1
    }
    END { exit(ok ? 0 : 1) }
  '; then
    die "Invalid VELAHUB_WSS_URL '${_url}': must be a valid wss:// URL"
  fi
}

validate_download_base() {
  _base="$1"
  if [ -z "${_base}" ] || has_newline_or_cr "${_base}"; then
    die "Invalid VELAHUB_DOWNLOAD_BASE: must not be empty or contain newlines"
  fi
  case "${_base}" in
    *[[:space:]]*|*\;*|*\$*|*\`*|*\'*|*\"*|*\\*)
      die "Invalid VELAHUB_DOWNLOAD_BASE '${_base}': contains disallowed whitespace or shell metacharacters"
      ;;
  esac
  if is_truthy "${VELAHUB_ALLOW_INSECURE_DOWNLOAD_BASE:-false}"; then
    case "${_base}" in
      https://*|http://*|file://*) ;;
      *) die "Invalid VELAHUB_DOWNLOAD_BASE '${_base}': must start with https://, http://, or file://" ;;
    esac
  else
    case "${_base}" in
      https://*) ;;
      *) die "Invalid VELAHUB_DOWNLOAD_BASE '${_base}': must start with https:// (set VELAHUB_ALLOW_INSECURE_DOWNLOAD_BASE=true for offline tests only)" ;;
    esac
  fi
}

resolve_trust_loopback_proxy_headers() {
  if [ -n "${VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS_EXPLICIT:-}" ]; then
    printf '%s' "${VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS_EXPLICIT}"
  elif [ -n "${1:-}" ]; then
    printf 'true'
  else
    printf 'false'
  fi
}

normalize_metrics_probe_addr() {
  _addr="${1:-127.0.0.1:9100}"
  [ -n "${_addr}" ] || _addr="127.0.0.1:9100"
  case "${_addr}" in
    0.0.0.0:*)
      printf '127.0.0.1:%s' "${_addr#0.0.0.0:}"
      ;;
    '[::]:'*)
      printf '[::1]:%s' "${_addr#\[::\]:}"
      ;;
    '*:'*)
      printf '127.0.0.1:%s' "${_addr#\*:}"
      ;;
    *)
      printf '%s' "${_addr}"
      ;;
  esac
}

# Look up the expected 64-hex SHA-256 digest for an artifact in SHA256SUMS.
# Accepts both bare `<filename>` and `releases/<filename>` (with optional leading `*` or `./`).
lookup_sha256_in_sums() {
  _artifact="$1"
  _sums_file="$2"
  awk -v f="${_artifact}" '
    NF >= 2 {
      h = tolower($1)
      if (length(h) != 64 || h !~ /^[0-9a-f]+$/) next
      p = $2
      sub(/^\*/, "", p)
      sub(/^\.\//, "", p)
      if (p == f || p == ("releases/" f)) {
        print h
        exit
      }
    }
  ' "${_sums_file}"
}

verify_artifact_sha256() {
  _artifact="$1"
  _artifact_path="$2"
  _sums_file="$3"
  _sha_tool="$4"

  _expected_sha="$(lookup_sha256_in_sums "${_artifact}" "${_sums_file}")"
  [ -n "${_expected_sha}" ] || die "SHA256SUMS does not contain an entry for ${_artifact}."
  _actual_sha="$(${_sha_tool} "${_artifact_path}" | awk '{ print tolower($1) }')"
  if [ "${_expected_sha}" != "${_actual_sha}" ]; then
    die "SHA-256 checksum mismatch for ${_artifact} (expected ${_expected_sha}, got ${_actual_sha})."
  fi
  VERIFIED_SHA256="${_actual_sha}"
}

is_valid_public_ipv4() {
  if [ -z "$1" ] || has_newline_or_cr "$1"; then
    return 1
  fi
  printf '%s\n' "$1" | awk '
    BEGIN { ok = 0 }
    NR > 1 { ok = 0; exit }
    /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ {
      n = split($0, a, ".")
      if (n == 4) {
        valid = 1
        for (i = 1; i <= 4; i++) {
          if (length(a[i]) == 0 || length(a[i]) > 3 || a[i] + 0 > 255) valid = 0
          if (length(a[i]) > 1 && substr(a[i], 1, 1) == "0") valid = 0
        }
        if (valid) {
          o1 = a[1] + 0; o2 = a[2] + 0
          if (o1 == 0 || o1 == 10 || o1 == 127 || o1 >= 224) valid = 0
          if (o1 == 169 && o2 == 254) valid = 0
          if (o1 == 172 && o2 >= 16 && o2 <= 31) valid = 0
          if (o1 == 192 && o2 == 168) valid = 0
          if (o1 == 100 && o2 >= 64 && o2 <= 127) valid = 0
          if (valid) ok = 1
        }
      }
    }
    END { exit(ok ? 0 : 1) }
  '
}

is_valid_public_ipv6() {
  if [ -z "$1" ] || has_newline_or_cr "$1"; then
    return 1
  fi
  printf '%s\n' "$1" | awk '
    BEGIN { ok = 0 }
    NR > 1 { ok = 0; exit }
    /^[0-9a-fA-F:]+$/ {
      s = tolower($0)
      if (length(s) >= 5 && length(s) <= 39 && index(s, ":") > 0 && index(s, ":::") == 0) {
        if (s ~ /^:/ || s ~ /[^:]:$/) next
        has_dc = (index(s, "::") > 0)
        if (has_dc) {
          c = s
          sub(/::/, "", c)
          if (index(c, "::") > 0) next
        }
        n = split(s, g, ":")
        # Accept Global Unicast 2000::/3 only (first hextet 2000..3fff)
        if (g[1] !~ /^[23][0-9a-f][0-9a-f][0-9a-f]$/) next
        non_empty = 0
        valid = 1
        for (i = 1; i <= n; i++) {
          if (length(g[i]) > 4) valid = 0
          if (length(g[i]) > 0) non_empty++
        }
        if (valid) {
          if (has_dc && non_empty >= 1 && non_empty <= 7) ok = 1
          else if (!has_dc && n == 8 && non_empty == 8) ok = 1
        }
      }
    }
    END { exit(ok ? 0 : 1) }
  '
}

probe_trace_ip() {
  curl "$1" --proto '=https' --tlsv1.2 -fsS --max-filesize 4096 --connect-timeout 3 --max-time 5 "$2" 2>/dev/null \
    | awk -F= '$1 == "ip" { gsub(/\r/, "", $2); gsub(/[ \t]/, "", $2); print $2; exit }' || true
}

probe_plain_ip() {
  curl "$1" --proto '=https' --tlsv1.2 -fsS --max-filesize 4096 --connect-timeout 3 --max-time 5 "$2" 2>/dev/null \
    | tr -d '\r\n \t' || true
}

ip_in_list() {
  _needle="$1"
  _haystack="$2"
  case "${NL}${_haystack}" in
    *"${NL}${_needle}${NL}"*) return 0 ;;
    *) return 1 ;;
  esac
}

detect_public_ip() {
  DETECTED_PUBLIC_IP=""
  DETECTED_PUBLIC_FAMILY=""

  # Prefer IPv4 first (universally reachable across IPv4-only and dual-stack clients).
  _cand="$(probe_trace_ip -4 "https://velacloud.app/cdn-cgi/trace")"
  if [ -n "${_cand}" ] && is_valid_public_ipv4 "${_cand}"; then
    DETECTED_PUBLIC_IP="${_cand}"
    DETECTED_PUBLIC_FAMILY="ipv4"
    return 0
  fi

  # Primary source failed: prefer 2-source cross-agreement across independent fallback endpoints,
  # falling back to the first valid address only if fewer than 2 fallback endpoints agree.
  _first_v4=""
  _seen_v4=""
  for _url in \
    "https://api4.ipify.org" \
    "https://ipv4.icanhazip.com" \
    "https://ifconfig.me/ip" \
    "https://ip.sb"
  do
    _cand="$(probe_plain_ip -4 "${_url}")"
    if [ -n "${_cand}" ] && is_valid_public_ipv4 "${_cand}"; then
      if ip_in_list "${_cand}" "${_seen_v4}"; then
        DETECTED_PUBLIC_IP="${_cand}"
        DETECTED_PUBLIC_FAMILY="ipv4"
        return 0
      fi
      _seen_v4="${_seen_v4}${_cand}${NL}"
      if [ -z "${_first_v4}" ]; then
        _first_v4="${_cand}"
      fi
    fi
  done
  if [ -n "${_first_v4}" ]; then
    DETECTED_PUBLIC_IP="${_first_v4}"
    DETECTED_PUBLIC_FAMILY="ipv4"
    return 0
  fi

  # Fall back to IPv6 for IPv6-only VPS environments.
  _cand="$(probe_trace_ip -6 "https://velacloud.app/cdn-cgi/trace")"
  if [ -n "${_cand}" ] && is_valid_public_ipv6 "${_cand}"; then
    DETECTED_PUBLIC_IP="${_cand}"
    DETECTED_PUBLIC_FAMILY="ipv6"
    return 0
  fi

  _first_v6=""
  _seen_v6=""
  for _url in \
    "https://api6.ipify.org" \
    "https://ipv6.icanhazip.com" \
    "https://6.ident.me"
  do
    _cand="$(probe_plain_ip -6 "${_url}")"
    if [ -n "${_cand}" ] && is_valid_public_ipv6 "${_cand}"; then
      if ip_in_list "${_cand}" "${_seen_v6}"; then
        DETECTED_PUBLIC_IP="${_cand}"
        DETECTED_PUBLIC_FAMILY="ipv6"
        return 0
      fi
      _seen_v6="${_seen_v6}${_cand}${NL}"
      if [ -z "${_first_v6}" ]; then
        _first_v6="${_cand}"
      fi
    fi
  done
  if [ -n "${_first_v6}" ]; then
    DETECTED_PUBLIC_IP="${_first_v6}"
    DETECTED_PUBLIC_FAMILY="ipv6"
    return 0
  fi

  return 1
}

download_file() {
  _url="$1"
  _out="$2"
  case "${_url}" in
    https://*)
      curl --proto '=https' --tlsv1.2 -fsSL --retry 3 --connect-timeout 15 --max-time 180 -o "${_out}" "${_url}"
      ;;
    *)
      if is_truthy "${VELAHUB_ALLOW_INSECURE_DOWNLOAD_BASE:-false}"; then
        curl -fsSL --retry 3 --connect-timeout 15 --max-time 180 -o "${_out}" "${_url}"
      else
        die "Refusing non-HTTPS download URL: ${_url}"
      fi
      ;;
  esac
}

read_env_value() {
  awk -F= -v k="$2" '
    $0 ~ "^[ \t]*" k "=" {
      v = substr($0, index($0, "=") + 1)
      gsub(/\r/, "", v)
      sub(/^[ \t]+/, "", v)
      sub(/[ \t]+$/, "", v)
      if (length(v) >= 2) {
        c1 = substr(v, 1, 1)
        c2 = substr(v, length(v), 1)
        if ((c1 == "\"" && c2 == "\"") || (c1 == "\047" && c2 == "\047")) {
          v = substr(v, 2, length(v) - 2)
        }
      }
      print v
      exit
    }
  ' "$1" 2>/dev/null || true
}

set_env_value() {
  _file="$1"
  _key="$2"
  _val="$3"
  if has_newline_or_cr "${_val}"; then
    die "Refusing to write multiline or CR value for ${_key} into ${_file}"
  fi
  _dir="$(dirname "${_file}")"
  _base="$(basename "${_file}")"
  umask 027
  _tmp="$(mktemp "${_dir}/.${_base}.tmp.XXXXXX")"
  if ! awk -v k="${_key}" -v v="${_val}" '
    BEGIN { updated = 0 }
    $0 ~ "^[ \t]*" k "=" {
      if (!updated) {
        print k "=" v
        updated = 1
      }
      next
    }
    { print }
    END {
      if (!updated) print k "=" v
    }
  ' "${_file}" > "${_tmp}"; then
    rm -f "${_tmp}" 2>/dev/null || true
    die "Failed updating ${_key} in ${_file}"
  fi
  if [ "$(id -u)" -eq 0 ] && id -u velahub >/dev/null 2>&1; then
    chown root:velahub "${_tmp}"
  fi
  chmod 0640 "${_tmp}"
  mv -f "${_tmp}" "${_file}"
}

extract_port_from_addr() {
  printf '%s' "$1" | awk -F: '{ print $NF }'
}

ensure_velahub_user_group() {
  if ! grep -q '^velahub:' /etc/group 2>/dev/null \
     && ! (command -v getent >/dev/null 2>&1 && getent group velahub >/dev/null 2>&1); then
    log "Creating dedicated system group 'velahub'..."
    if command -v groupadd >/dev/null 2>&1; then
      groupadd --system velahub
    elif command -v addgroup >/dev/null 2>&1; then
      addgroup -S velahub
    else
      die "Neither groupadd nor addgroup found to create system group 'velahub'."
    fi
  fi
  if ! id -u velahub >/dev/null 2>&1; then
    log "Creating dedicated static system user 'velahub'..."
    if command -v useradd >/dev/null 2>&1; then
      useradd --system --gid velahub --no-create-home --shell /usr/sbin/nologin velahub
    elif command -v adduser >/dev/null 2>&1; then
      adduser -S -D -H -G velahub -s /sbin/nologin velahub
    else
      die "Neither useradd nor adduser found to create system user 'velahub'."
    fi
  fi
}

run_as_velahub() {
  if command -v runuser >/dev/null 2>&1; then
    runuser -u velahub -- "$@"
  else
    _cmd=""
    for _arg in "$@"; do
      _esc="$(printf '%s' "${_arg}" | sed "s/'/'\\\\''/g")"
      _cmd="${_cmd:+${_cmd} }'${_esc}'"
    done
    su -s /bin/sh -c "${_cmd}" velahub
  fi
}

open_ufw_port() {
  LC_ALL=C ufw allow "$1" comment "$2" >/dev/null 2>&1 \
    || LC_ALL=C ufw allow "$1" >/dev/null 2>&1
}

iptables_input_insert_line() {
  LC_ALL=C "$1" -w 5 -S INPUT 2>/dev/null | awk '
    /^-P INPUT (DROP|REJECT)/ { policy_restrictive = 1 }
    /^-A INPUT / {
      rule_num++
      line = $0
      sub(/^-A INPUT /, "", line)
      sub(/^-c [0-9]+ [0-9]+ /, "", line)
      sub(/^-m comment --comment ("[^"]*"|[^ \t]+) /, "", line)
      sub(/^-c [0-9]+ [0-9]+ /, "", line)
      if (line ~ /^-j (DROP|REJECT)([ \t]|$)/) {
        if (insert_at == 0) insert_at = rule_num
      }
    }
    END {
      if (insert_at > 0) print insert_at
      else if (policy_restrictive) print "APPEND"
    }
  '
}

open_iptables_port() {
  _ipt="$1"
  _proto="$2"
  _port="$3"
  if LC_ALL=C "${_ipt}" -w 5 -C INPUT -p "${_proto}" --dport "${_port}" -m comment --comment "VelaHub" -j ACCEPT >/dev/null 2>&1 \
     || LC_ALL=C "${_ipt}" -w 5 -C INPUT -p "${_proto}" --dport "${_port}" -j ACCEPT >/dev/null 2>&1; then
    return 0
  fi
  _pos="$(iptables_input_insert_line "${_ipt}")"
  if [ -n "${_pos}" ] && [ "${_pos}" != "APPEND" ]; then
    LC_ALL=C "${_ipt}" -w 5 -I INPUT "${_pos}" -p "${_proto}" --dport "${_port}" -m comment --comment "VelaHub" -j ACCEPT >/dev/null 2>&1 \
      || LC_ALL=C "${_ipt}" -w 5 -I INPUT "${_pos}" -p "${_proto}" --dport "${_port}" -j ACCEPT
  else
    LC_ALL=C "${_ipt}" -w 5 -A INPUT -p "${_proto}" --dport "${_port}" -m comment --comment "VelaHub" -j ACCEPT >/dev/null 2>&1 \
      || LC_ALL=C "${_ipt}" -w 5 -A INPUT -p "${_proto}" --dport "${_port}" -j ACCEPT
  fi
}

iptables_has_dynamic_chains() {
  for _tool in iptables ip6tables; do
    if command -v "${_tool}" >/dev/null 2>&1; then
      if LC_ALL=C "${_tool}" -w 5 -S 2>/dev/null | grep -Eq '(^-N | -j )(DOCKER|f2b-)'; then
        return 0
      fi
      if LC_ALL=C "${_tool}" -w 5 -t nat -S 2>/dev/null | grep -Eq '(^-N | -j )(DOCKER|f2b-)'; then
        return 0
      fi
    fi
  done
  return 1
}

discover_restrictive_nft_input_chains() {
  LC_ALL=C nft -n list ruleset 2>/dev/null | awk '
    /^table [a-z0-9]+ [a-zA-Z0-9_.-]+ \{/ {
      fam = $2; tbl = $3; in_chain = 0; ch = ""; is_input = 0; restrictive = 0
      next
    }
    /^[ \t]+chain [a-zA-Z0-9_.-]+ \{/ {
      ch = $2; in_chain = 1; is_input = 0; restrictive = 0
      next
    }
    in_chain && /hook input/ {
      is_input = 1
      if ($0 ~ /policy drop/) restrictive = 1
    }
    in_chain && is_input && /^[ \t]+(counter([ \t]+packets[ \t]+[0-9]+[ \t]+bytes[ \t]+[0-9]+)?[ \t]+)?(drop|reject)([ \t;]|$)/ {
      restrictive = 1
    }
    in_chain && /^[ \t]+\}/ {
      if (is_input && restrictive && fam != "" && tbl != "" && ch != "") {
        print fam " " tbl " " ch
      }
      in_chain = 0; ch = ""; is_input = 0; restrictive = 0
    }
  '
}

nft_catchall_drop_handle() {
  LC_ALL=C nft -n -a list chain "$1" "$2" "$3" 2>/dev/null | awk '
    /^[ \t]+(counter([ \t]+packets[ \t]+[0-9]+[ \t]+bytes[ \t]+[0-9]+)?[ \t]+)?(drop|reject)([ \t;]|$)/ {
      if (match($0, /#[ \t]*handle[ \t]+[0-9]+/)) {
        h = substr($0, RSTART, RLENGTH)
        sub(/^#[ \t]*handle[ \t]+/, "", h)
        print h
        exit
      }
    }
  '
}

open_nft_port() {
  _fam="$1"
  _tbl="$2"
  _ch="$3"
  _proto="$4"
  _port="$5"
  if LC_ALL=C nft -n list chain "${_fam}" "${_tbl}" "${_ch}" 2>/dev/null \
     | grep -Eq "^[[:space:]]*${_proto} dport ${_port}([[:space:]]|$).*accept"; then
    return 0
  fi
  _handle="$(nft_catchall_drop_handle "${_fam}" "${_tbl}" "${_ch}" || true)"
  if [ -n "${_handle}" ]; then
    LC_ALL=C nft insert rule "${_fam}" "${_tbl}" "${_ch}" position "${_handle}" "${_proto}" dport "${_port}" accept comment \"velahub\" >/dev/null 2>&1 \
      || LC_ALL=C nft insert rule "${_fam}" "${_tbl}" "${_ch}" position "${_handle}" "${_proto}" dport "${_port}" accept >/dev/null 2>&1
  else
    LC_ALL=C nft add rule "${_fam}" "${_tbl}" "${_ch}" "${_proto}" dport "${_port}" accept comment \"velahub\" >/dev/null 2>&1 \
      || LC_ALL=C nft add rule "${_fam}" "${_tbl}" "${_ch}" "${_proto}" dport "${_port}" accept >/dev/null 2>&1
  fi
}

save_iptables_file() {
  _save_cmd="$1"
  _dest="$2"
  _save_dir="$(dirname "${_dest}")"
  _save_base="$(basename "${_dest}")"
  umask 077
  _save_tmp="$(mktemp "${_save_dir}/.${_save_base}.velahub.XXXXXX")" || return 1
  if "${_save_cmd}" > "${_save_tmp}" 2>/dev/null && [ -s "${_save_tmp}" ]; then
    chmod 0600 "${_save_tmp}"
    mv -f "${_save_tmp}" "${_dest}"
    return 0
  fi
  rm -f "${_save_tmp}" 2>/dev/null || true
  return 1
}

# Automatically open ONLY the VelaHub signaling and blind relay ports (NEVER 9100/tcp).
configure_firewall() {
  _sig="$1"
  _rel="$2"
  FIREWALL_STATUS=""

  if ! is_truthy "${VELAHUB_AUTO_FIREWALL}"; then
    log "Skipping automatic firewall configuration (VELAHUB_AUTO_FIREWALL=${VELAHUB_AUTO_FIREWALL})."
    FIREWALL_STATUS="skipped (VELAHUB_AUTO_FIREWALL=${VELAHUB_AUTO_FIREWALL})"
    return 0
  fi

  # 1. firewalld (RHEL / Rocky / Alma / CentOS / Fedora / openSUSE)
  if command -v firewall-cmd >/dev/null 2>&1 && LC_ALL=C firewall-cmd --state >/dev/null 2>&1; then
    if LC_ALL=C firewall-cmd --permanent --add-port="${_sig}/udp" >/dev/null 2>&1 \
       && LC_ALL=C firewall-cmd --permanent --add-port="${_sig}/tcp" >/dev/null 2>&1 \
       && LC_ALL=C firewall-cmd --permanent --add-port="${_rel}/udp" >/dev/null 2>&1 \
       && LC_ALL=C firewall-cmd --permanent --add-port="${_rel}/tcp" >/dev/null 2>&1 \
       && LC_ALL=C firewall-cmd --reload >/dev/null 2>&1; then
      log "Opened firewall ports via firewalld: ${_sig}/udp, ${_sig}/tcp, ${_rel}/udp, ${_rel}/tcp"
      FIREWALL_STATUS="opened automatically via firewalld (also verify cloud security group if applicable)"
    else
      warn "Detected active firewalld, but failed to open ports automatically. Run: firewall-cmd --permanent --add-port=${_sig}/udp --add-port=${_sig}/tcp --add-port=${_rel}/udp --add-port=${_rel}/tcp && firewall-cmd --reload"
      FIREWALL_STATUS="firewalld update failed (open ports manually)"
    fi
    return 0
  fi

  # 2. UFW (Ubuntu / Debian) — only modify if already active (never enable an inactive UFW to avoid SSH lockout)
  if command -v ufw >/dev/null 2>&1 \
     && LC_ALL=C ufw status 2>/dev/null | awk 'NR == 1 { print tolower($0) }' | grep -q "status: active"; then
    if open_ufw_port "${_sig}/udp" "VelaHub signaling & STUN" \
       && open_ufw_port "${_sig}/tcp" "VelaHub TCP signaling" \
       && open_ufw_port "${_rel}/udp" "VelaHub UDP blind relay" \
       && open_ufw_port "${_rel}/tcp" "VelaHub TCP blind relay"; then
      log "Opened firewall ports via ufw: ${_sig}/udp, ${_sig}/tcp, ${_rel}/udp, ${_rel}/tcp"
      FIREWALL_STATUS="opened automatically via ufw (also verify cloud security group if applicable)"
    else
      warn "Detected active ufw, but failed to open ports automatically. Run: ufw allow ${_sig}/udp && ufw allow ${_sig}/tcp && ufw allow ${_rel}/udp && ufw allow ${_rel}/tcp"
      FIREWALL_STATUS="ufw update failed (open ports manually)"
    fi
    return 0
  fi

  # 3. Restrictive iptables / ip6tables INPUT chain (e.g. Oracle Cloud, iptables-persistent, static rulesets)
  _v4_mode=""
  _v6_mode=""
  if command -v iptables >/dev/null 2>&1; then
    _v4_mode="$(iptables_input_insert_line iptables || true)"
  fi
  if command -v ip6tables >/dev/null 2>&1; then
    _v6_mode="$(iptables_input_insert_line ip6tables || true)"
  fi

  if [ -n "${_v4_mode}" ] || [ -n "${_v6_mode}" ]; then
    _ipt_ok=1
    _ipt_tools=""
    if [ -n "${_v4_mode}" ]; then
      _ipt_tools="iptables"
      if ! (open_iptables_port iptables udp "${_sig}" \
            && open_iptables_port iptables tcp "${_sig}" \
            && open_iptables_port iptables udp "${_rel}" \
            && open_iptables_port iptables tcp "${_rel}"); then
        _ipt_ok=0
      fi
    fi
    if [ -n "${_v6_mode}" ]; then
      _ipt_tools="${_ipt_tools:+${_ipt_tools}+}ip6tables"
      if ! (open_iptables_port ip6tables udp "${_sig}" \
            && open_iptables_port ip6tables tcp "${_sig}" \
            && open_iptables_port ip6tables udp "${_rel}" \
            && open_iptables_port ip6tables tcp "${_rel}"); then
        _ipt_ok=0
      fi
    fi

    if [ "${_ipt_ok}" -eq 1 ]; then
      _persisted=""
      if iptables_has_dynamic_chains; then
        warn "Detected dynamic DOCKER or fail2ban (f2b-) iptables chains; skipping automatic overwrite of static iptables persistence files to avoid freezing ephemeral rules. Persist VelaHub ports (${_sig}/udp+tcp, ${_rel}/udp+tcp) manually."
      elif command -v netfilter-persistent >/dev/null 2>&1; then
        if netfilter-persistent save >/dev/null 2>&1; then
          _persisted="persisted via netfilter-persistent"
        fi
      elif [ -f /etc/iptables/rules.v4 ] && command -v iptables-save >/dev/null 2>&1; then
        if [ -z "${_v4_mode}" ] || save_iptables_file iptables-save /etc/iptables/rules.v4; then
          _persisted="saved to /etc/iptables/rules.v4"
        fi
        if [ -n "${_v6_mode}" ] && [ -f /etc/iptables/rules.v6 ] && command -v ip6tables-save >/dev/null 2>&1; then
          save_iptables_file ip6tables-save /etc/iptables/rules.v6 || true
        fi
      elif [ -f /etc/sysconfig/iptables ] && command -v iptables-save >/dev/null 2>&1; then
        if [ -z "${_v4_mode}" ] || save_iptables_file iptables-save /etc/sysconfig/iptables; then
          _persisted="saved to /etc/sysconfig/iptables"
        fi
        if [ -n "${_v6_mode}" ] && [ -f /etc/sysconfig/ip6tables ] && command -v ip6tables-save >/dev/null 2>&1; then
          save_iptables_file ip6tables-save /etc/sysconfig/ip6tables || true
        fi
      fi

      if [ -n "${_persisted}" ]; then
        log "Opened firewall ports via ${_ipt_tools} (${_persisted}): ${_sig}/udp, ${_sig}/tcp, ${_rel}/udp, ${_rel}/tcp"
        FIREWALL_STATUS="opened automatically via ${_ipt_tools} (${_persisted}; also verify cloud security group if applicable)"
      else
        log "Opened firewall ports live via ${_ipt_tools}: ${_sig}/udp, ${_sig}/tcp, ${_rel}/udp, ${_rel}/tcp"
        warn "Rules were applied live to ${_ipt_tools}; persist them with iptables-save / netfilter-persistent if your host reloads static firewall rules on reboot."
        FIREWALL_STATUS="opened live via ${_ipt_tools} (persist across reboots & verify cloud security group)"
      fi
    else
      warn "Failed to update ${_ipt_tools} automatically. Open ${_sig}/udp+tcp and ${_rel}/udp+tcp manually."
      FIREWALL_STATUS="${_ipt_tools} update failed (open ports manually)"
    fi
    return 0
  fi

  # 4. Pure native nftables with restrictive input hook chain
  if command -v nft >/dev/null 2>&1; then
    _nft_chains="$(discover_restrictive_nft_input_chains || true)"
    if [ -n "${_nft_chains}" ]; then
      _nft_ok=1
      while IFS=' ' read -r _fam _tbl _ch; do
        [ -n "${_fam}" ] || continue
        if ! (open_nft_port "${_fam}" "${_tbl}" "${_ch}" udp "${_sig}" \
              && open_nft_port "${_fam}" "${_tbl}" "${_ch}" tcp "${_sig}" \
              && open_nft_port "${_fam}" "${_tbl}" "${_ch}" udp "${_rel}" \
              && open_nft_port "${_fam}" "${_tbl}" "${_ch}" tcp "${_rel}"); then
          _nft_ok=0
        fi
      done <<EOF
${_nft_chains}
EOF
      if [ "${_nft_ok}" -eq 1 ]; then
        log "Opened firewall ports live via nftables: ${_sig}/udp, ${_sig}/tcp, ${_rel}/udp, ${_rel}/tcp"
        if [ -f /etc/nftables.conf ]; then
          warn "nftables rules were applied live; ensure ${_sig}/udp+tcp and ${_rel}/udp+tcp are also allowed in /etc/nftables.conf to survive reboots."
        fi
        FIREWALL_STATUS="opened live via nftables (verify /etc/nftables.conf & cloud security group)"
      else
        warn "Detected restrictive nftables ruleset, but failed to apply rules automatically. Open ${_sig}/udp+tcp and ${_rel}/udp+tcp manually."
        FIREWALL_STATUS="nftables update failed (open ports manually)"
      fi
      return 0
    fi
  fi

  # 5. No active restrictive OS firewall detected
  log "No active host firewall blocking inbound ports detected (if using a cloud security group, ensure ${_sig}/udp+tcp and ${_rel}/udp+tcp are allowed)."
  FIREWALL_STATUS="no active host firewall (verify cloud security group if applicable)"
}

main() {
  if [ "$(id -u)" -ne 0 ]; then
    die "Please run as root (e.g. curl --proto '=https' --tlsv1.2 -fsSL ${VELAHUB_DOWNLOAD_BASE}/install.sh | sudo sh)"
  fi

  OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
  [ "${OS}" = "linux" ] || die "This installer supports Linux only (detected: ${OS})."

  ARCH_RAW="$(uname -m)"
  case "${ARCH_RAW}" in
    x86_64|amd64)  ARCH="amd64" ;;
    aarch64|arm64) ARCH="arm64" ;;
    *) die "Unsupported CPU architecture: ${ARCH_RAW} (supported: amd64, arm64)" ;;
  esac

  validate_version "${VELAHUB_VERSION}"
  validate_bool "${VELAHUB_ALLOW_INSECURE_DOWNLOAD_BASE}"
  validate_download_base "${VELAHUB_DOWNLOAD_BASE}"
  validate_port "${VELAHUB_SIGNAL_PORT}"
  validate_port "${VELAHUB_RELAY_PORT}"
  if [ "${VELAHUB_SIGNAL_PORT}" = "${VELAHUB_RELAY_PORT}" ]; then
    die "VELAHUB_SIGNAL_PORT and VELAHUB_RELAY_PORT must be different ports."
  fi
  validate_uint "VELAHUB_RELAY_RATE_MBPS" "${VELAHUB_RELAY_RATE_MBPS}"
  validate_bool "${VELAHUB_PUBLIC_P2P_ACCEL}"
  validate_bool "${VELAHUB_DUAL_STACK}"
  validate_bool "${VELAHUB_AUTO_PUBLIC_IP}"
  validate_bool "${VELAHUB_AUTO_FIREWALL}"
  if [ -n "${VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS_EXPLICIT}" ]; then
    validate_bool "${VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS_EXPLICIT}"
  fi
  if [ -n "${VELAHUB_PUBLIC_HOST}" ]; then
    validate_host "${VELAHUB_PUBLIC_HOST}"
  fi
  if [ -n "${VELAHUB_WSS_URL}" ]; then
    validate_wss_url "${VELAHUB_WSS_URL}"
  fi

  need_cmd curl
  if command -v sha256sum >/dev/null 2>&1; then
    SHA_TOOL="sha256sum"
  elif command -v shasum >/dev/null 2>&1; then
    SHA_TOOL="shasum -a 256"
  else
    die "Neither sha256sum nor shasum found for binary integrity verification."
  fi

  ARTIFACT="velahub-${VELAHUB_VERSION}-linux-${ARCH}"
  BIN_URL="${VELAHUB_DOWNLOAD_BASE}/${ARTIFACT}"
  SUMS_URL="${VELAHUB_DOWNLOAD_BASE}/SHA256SUMS"

  TMP_DIR="$(mktemp -d)"
  BIN_STAGING=""
  cleanup() {
    rm -rf "${TMP_DIR}"
    if [ -n "${BIN_STAGING}" ] && [ -e "${BIN_STAGING}" ]; then
      rm -f "${BIN_STAGING}" 2>/dev/null || true
    fi
  }
  trap cleanup EXIT INT TERM

  log "Downloading VelaHub v${VELAHUB_VERSION} (${ARCH}) from ${VELAHUB_DOWNLOAD_BASE}..."
  download_file "${BIN_URL}" "${TMP_DIR}/${ARTIFACT}" \
    || die "Failed to download ${BIN_URL}. Verify the release binary is published at ${VELAHUB_DOWNLOAD_BASE}."
  download_file "${SUMS_URL}" "${TMP_DIR}/SHA256SUMS" \
    || die "Failed to download ${SUMS_URL} for SHA-256 verification."

  verify_artifact_sha256 "${ARTIFACT}" "${TMP_DIR}/${ARTIFACT}" "${TMP_DIR}/SHA256SUMS" "${SHA_TOOL}"
  log "Verified SHA-256 checksum: ${VERIFIED_SHA256}"

  # Atomic same-directory swap prevents ETXTBSY when upgrading a running binary.
  BIN_DIR="$(dirname "${BIN_PATH}")"
  mkdir -p "${BIN_DIR}"
  BIN_STAGING="$(mktemp "${BIN_DIR}/.velahub.new.XXXXXX")"
  install -m 0755 "${TMP_DIR}/${ARTIFACT}" "${BIN_STAGING}"
  mv -f "${BIN_STAGING}" "${BIN_PATH}"
  BIN_STAGING=""

  ensure_velahub_user_group

  install -d -o velahub -g velahub -m 0700 "${DATA_DIR}"
  install -d -o root -g velahub -m 0750 "${ENV_DIR}"

  if [ ! -f "${DATA_DIR}/server.pk8" ]; then
    log "Generating persistent Ed25519 node identity (${DATA_DIR}/server.pk8, mode 0600)..."
    run_as_velahub "${BIN_PATH}" keygen --kind identity --data-dir "${DATA_DIR}" >/dev/null
  fi
  # Enforce strict private key ownership & mode on both fresh install and upgrade re-runs.
  if [ -f "${DATA_DIR}/server.pk8" ]; then
    chown velahub:velahub "${DATA_DIR}/server.pk8"
    chmod 0600 "${DATA_DIR}/server.pk8"
  fi
  if [ -f "${DATA_DIR}/server.prev.pk8" ]; then
    chown velahub:velahub "${DATA_DIR}/server.prev.pk8"
    chmod 0600 "${DATA_DIR}/server.prev.pk8"
  fi

  IS_UPGRADE=0
  if [ ! -f "${ENV_FILE}" ]; then
    if [ -n "${VELAHUB_PUBLIC_HOST}" ]; then
      PUBLIC_HOST_SOURCE="configured"
    elif is_truthy "${VELAHUB_AUTO_PUBLIC_IP}"; then
      log "Detecting public egress IP..."
      if detect_public_ip; then
        VELAHUB_PUBLIC_HOST="${DETECTED_PUBLIC_IP}"
        PUBLIC_HOST_SOURCE="auto-detected"
        if [ "${DETECTED_PUBLIC_FAMILY}" = "ipv6" ] && [ -z "${VELAHUB_DUAL_STACK_EXPLICIT}" ]; then
          VELAHUB_DUAL_STACK="true"
          log "Detected public IPv6 egress address: ${VELAHUB_PUBLIC_HOST} (enabling dual-stack [::] listen)"
        else
          log "Detected public ${DETECTED_PUBLIC_FAMILY} egress address: ${VELAHUB_PUBLIC_HOST}"
        fi
      else
        warn "Could not auto-detect public egress IP. Set VELAHUB_PUBLIC_HOST in ${ENV_FILE} manually."
      fi
    fi

    log "Generating private 256-bit Access Key and writing ${ENV_FILE} (mode 0640)..."
    GENERATED_AK="$("${BIN_PATH}" keygen --kind access-key)"
    BIND_HOST="0.0.0.0"
    if is_truthy "${VELAHUB_DUAL_STACK}"; then
      BIND_HOST="[::]"
    fi
    TRUST_PROXY_VAL="$(resolve_trust_loopback_proxy_headers "${VELAHUB_WSS_URL}")"
    umask 027
    cat > "${ENV_FILE}" <<EOF
# VelaHub Self-Hosted Configuration (generated by install.sh)
VELAHUB_MODE=self_hosted
VELAHUB_DATA_DIR=${DATA_DIR}
VELAHUB_SIGNAL_ADDR=${BIND_HOST}:${VELAHUB_SIGNAL_PORT}
VELAHUB_RELAY_ADDR=${BIND_HOST}:${VELAHUB_RELAY_PORT}
VELAHUB_METRICS_ADDR=127.0.0.1:9100
VELAHUB_ACCESS_KEY=${GENERATED_AK}
VELAHUB_RELAY_RATE_MBPS=${VELAHUB_RELAY_RATE_MBPS}
# Public P2P Acceleration (ON by default): allows everyone to use low-overhead STUN + blind-slot
# P2P hole-punching while keeping your blind relay strictly protected by VELAHUB_ACCESS_KEY.
# Set to false for a strictly private-only node.
VELAHUB_PUBLIC_P2P_ACCEL=${VELAHUB_PUBLIC_P2P_ACCEL}
VELAHUB_PUBLIC_HOST=${VELAHUB_PUBLIC_HOST}
VELAHUB_WSS_URL=${VELAHUB_WSS_URL}
VELAHUB_TRUST_LOOPBACK_PROXY_HEADERS=${TRUST_PROXY_VAL}
RUST_LOG=info
EOF
    chown root:velahub "${ENV_FILE}"
    chmod 0640 "${ENV_FILE}"
  else
    IS_UPGRADE=1
    log "Preserving existing ${ENV_FILE} (upgrade mode)."
    chown root:velahub "${ENV_FILE}"
    chmod 0640 "${ENV_FILE}"
    EXISTING_HOST="$(read_env_value "${ENV_FILE}" "VELAHUB_PUBLIC_HOST")"
    if [ -n "${VELAHUB_PUBLIC_HOST_EXPLICIT}" ]; then
      set_env_value "${ENV_FILE}" "VELAHUB_PUBLIC_HOST" "${VELAHUB_PUBLIC_HOST_EXPLICIT}"
      VELAHUB_PUBLIC_HOST="${VELAHUB_PUBLIC_HOST_EXPLICIT}"
      PUBLIC_HOST_SOURCE="configured"
      log "Updated VELAHUB_PUBLIC_HOST in ${ENV_FILE}: ${VELAHUB_PUBLIC_HOST}"
    elif [ -z "${EXISTING_HOST}" ] || [ "${EXISTING_HOST}" = "YOUR_PUBLIC_HOST" ]; then
      if is_truthy "${VELAHUB_AUTO_PUBLIC_IP}"; then
        log "Existing VELAHUB_PUBLIC_HOST is empty; detecting public egress IP..."
        if detect_public_ip; then
          set_env_value "${ENV_FILE}" "VELAHUB_PUBLIC_HOST" "${DETECTED_PUBLIC_IP}"
          VELAHUB_PUBLIC_HOST="${DETECTED_PUBLIC_IP}"
          PUBLIC_HOST_SOURCE="auto-detected"
          log "Filled VELAHUB_PUBLIC_HOST in ${ENV_FILE} with detected ${DETECTED_PUBLIC_FAMILY} egress address: ${VELAHUB_PUBLIC_HOST}"
          if [ "${DETECTED_PUBLIC_FAMILY}" = "ipv6" ]; then
            EXISTING_SIG_ADDR="$(read_env_value "${ENV_FILE}" "VELAHUB_SIGNAL_ADDR")"
            case "${EXISTING_SIG_ADDR}" in
              0.0.0.0:*)
                warn "Detected IPv6-only egress while ${ENV_FILE} binds 0.0.0.0; consider changing 0.0.0.0 to [::] in ${ENV_FILE} and restarting velahub."
                ;;
            esac
          fi
        else
          warn "Could not auto-detect public egress IP. Set VELAHUB_PUBLIC_HOST in ${ENV_FILE} manually."
        fi
      fi
    else
      VELAHUB_PUBLIC_HOST="${EXISTING_HOST}"
      PUBLIC_HOST_SOURCE="existing"
    fi
  fi

  # Derive effective ports and toggle from ENV_FILE so firewall, capabilities, and summary match runtime config.
  EFFECTIVE_SIGNAL_PORT="${VELAHUB_SIGNAL_PORT}"
  EFFECTIVE_RELAY_PORT="${VELAHUB_RELAY_PORT}"
  EFFECTIVE_P2P_ACCEL="${VELAHUB_PUBLIC_P2P_ACCEL}"

  _env_sig_addr="$(read_env_value "${ENV_FILE}" "VELAHUB_SIGNAL_ADDR")"
  _env_sig_port="$(read_env_value "${ENV_FILE}" "VELAHUB_SIGNAL_PORT")"
  if [ -n "${_env_sig_addr}" ]; then
    _p="$(extract_port_from_addr "${_env_sig_addr}")"
    is_valid_port "${_p}" && EFFECTIVE_SIGNAL_PORT="${_p}"
  elif [ -n "${_env_sig_port}" ] && is_valid_port "${_env_sig_port}"; then
    EFFECTIVE_SIGNAL_PORT="${_env_sig_port}"
  fi

  _env_rel_addr="$(read_env_value "${ENV_FILE}" "VELAHUB_RELAY_ADDR")"
  _env_rel_port="$(read_env_value "${ENV_FILE}" "VELAHUB_RELAY_PORT")"
  if [ -n "${_env_rel_addr}" ]; then
    _p="$(extract_port_from_addr "${_env_rel_addr}")"
    is_valid_port "${_p}" && EFFECTIVE_RELAY_PORT="${_p}"
  elif [ -n "${_env_rel_port}" ] && is_valid_port "${_env_rel_port}"; then
    EFFECTIVE_RELAY_PORT="${_env_rel_port}"
  fi

  if [ "${IS_UPGRADE}" -eq 1 ]; then
    if [ -n "${VELAHUB_SIGNAL_PORT_EXPLICIT}" ] && [ "${VELAHUB_SIGNAL_PORT_EXPLICIT}" != "${EFFECTIVE_SIGNAL_PORT}" ]; then
      warn "Upgrade mode preserved existing ${ENV_FILE}: VELAHUB_SIGNAL_PORT=${VELAHUB_SIGNAL_PORT_EXPLICIT} differs from configured port ${EFFECTIVE_SIGNAL_PORT}. Edit ${ENV_FILE} and restart velahub to change ports."
    fi
    if [ -n "${VELAHUB_RELAY_PORT_EXPLICIT}" ] && [ "${VELAHUB_RELAY_PORT_EXPLICIT}" != "${EFFECTIVE_RELAY_PORT}" ]; then
      warn "Upgrade mode preserved existing ${ENV_FILE}: VELAHUB_RELAY_PORT=${VELAHUB_RELAY_PORT_EXPLICIT} differs from configured port ${EFFECTIVE_RELAY_PORT}. Edit ${ENV_FILE} and restart velahub to change ports."
    fi
  fi

  _env_p2p="$(read_env_value "${ENV_FILE}" "VELAHUB_PUBLIC_P2P_ACCEL")"
  if [ -n "${_env_p2p}" ]; then
    EFFECTIVE_P2P_ACCEL="${_env_p2p}"
  fi

  _env_metrics_addr="$(read_env_value "${ENV_FILE}" "VELAHUB_METRICS_ADDR")"
  PROBE_METRICS_ADDR="$(normalize_metrics_probe_addr "${_env_metrics_addr:-127.0.0.1:9100}")"
  PROBE_LIVEZ_URL="http://${PROBE_METRICS_ADDR}/livez"

  configure_firewall "${EFFECTIVE_SIGNAL_PORT}" "${EFFECTIVE_RELAY_PORT}"

  if [ "${EFFECTIVE_SIGNAL_PORT}" -lt 1024 ] || [ "${EFFECTIVE_RELAY_PORT}" -lt 1024 ]; then
    CAP_BLOCK="CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE"
  else
    CAP_BLOCK="CapabilityBoundingSet="
  fi

  if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
    log "Installing hardened systemd service (${UNIT_PATH})..."
    cat > "${UNIT_PATH}" <<EOF
[Unit]
Description=VelaHub Unified VelaBeam Signaling, STUN, and Zero-Knowledge Blind Relay
Documentation=https://velacloud.app/velahub
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=velahub
Group=velahub
StateDirectory=velahub
StateDirectoryMode=0700
Environment=VELAHUB_MODE=self_hosted
Environment=VELAHUB_DATA_DIR=${DATA_DIR}
Environment=VELAHUB_METRICS_ADDR=127.0.0.1:9100
Environment=VELAHUB_ENV_FILE=${ENV_FILE}
EnvironmentFile=-${ENV_FILE}
ExecStart=${BIN_PATH} serve
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=3s
LimitNOFILE=65536
TasksMax=256
UMask=0077
LogRateLimitIntervalSec=30s
LogRateLimitBurst=1000

${CAP_BLOCK}
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
RestrictNamespaces=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service

[Install]
WantedBy=multi-user.target
EOF
    chmod 0644 "${UNIT_PATH}"
    systemctl daemon-reload
    systemctl enable velahub
    systemctl restart velahub

    _hc_ok=0
    _hc_attempt=1
    while [ "${_hc_attempt}" -le 5 ]; do
      if "${BIN_PATH}" healthcheck --addr "${PROBE_METRICS_ADDR}" >/dev/null 2>&1 \
         || curl --noproxy '*' -g -fsS --max-time 3 "${PROBE_LIVEZ_URL}" >/dev/null 2>&1; then
        _hc_ok=1
        break
      fi
      sleep 1
      _hc_attempt=$((_hc_attempt + 1))
    done
    if [ "${_hc_ok}" -eq 1 ]; then
      log "Health check passed: ${PROBE_LIVEZ_URL}"
    else
      warn "Service started, but ${PROBE_LIVEZ_URL} did not respond after 5 attempts. Check: journalctl -u velahub -n 40"
    fi
  else
    warn "systemd not detected. Load VELAHUB_* configuration from ${ENV_FILE} and start ${BIN_PATH} serve via your process supervisor."
  fi

  IMPORT_URI="$(run_as_velahub "${BIN_PATH}" print-uri --env-file "${ENV_FILE}" 2>/dev/null || true)"

  if [ -n "${VELAHUB_PUBLIC_HOST}" ]; then
    if [ "${PUBLIC_HOST_SOURCE}" = "auto-detected" ]; then
      PUBLIC_HOST_LINE="${VELAHUB_PUBLIC_HOST} (auto-detected; edit VELAHUB_PUBLIC_HOST in ${ENV_FILE} to override)"
    else
      PUBLIC_HOST_LINE="${VELAHUB_PUBLIC_HOST}"
    fi
  else
    PUBLIC_HOST_LINE="YOUR_PUBLIC_HOST (auto-detect failed; set VELAHUB_PUBLIC_HOST in ${ENV_FILE})"
  fi

  cat <<EOF

========================================================================
 VelaHub v${VELAHUB_VERSION} is installed and running!
========================================================================
 Config file       : ${ENV_FILE}
 Identity key      : ${DATA_DIR}/server.pk8 (0600, back this up!)
 Public host       : ${PUBLIC_HOST_LINE}
 Public P2P Accel  : ${EFFECTIVE_P2P_ACCEL} (toggle VELAHUB_PUBLIC_P2P_ACCEL in ${ENV_FILE})
 Firewall ports    : ${EFFECTIVE_SIGNAL_PORT}/udp, ${EFFECTIVE_SIGNAL_PORT}/tcp, ${EFFECTIVE_RELAY_PORT}/udp, ${EFFECTIVE_RELAY_PORT}/tcp
 Firewall status   : ${FIREWALL_STATUS}
 Local livez       : curl --noproxy '*' -g -s ${PROBE_LIVEZ_URL}
 Local healthz     : curl --noproxy '*' -g -s http://${PROBE_METRICS_ADDR}/healthz
 Check for updates : velahub update check
 Apply updates     : sudo velahub update apply --restart

 Safe onboarding URI (Access Key intentionally omitted):
   ${IMPORT_URI}

 To view your private Access Key (paste into VelaDesk / VelaTerm Access Key field):
   sudo grep '^VELAHUB_ACCESS_KEY=' ${ENV_FILE}

 Or print the full URI on a trusted terminal:
   sudo -u velahub ${BIN_PATH} print-uri --env-file ${ENV_FILE} --include-access-key
========================================================================
EOF
}

if [ "${VELAHUB_INSTALL_LIB_ONLY:-0}" != "1" ]; then
  main "$@"
fi
