#!/usr/bin/env bash
# Reproducible Debian / Ubuntu VPS bootstrap & hardening script.
# Supports interactive prompts, CLI flags, and config files (--config).

set -euo pipefail
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"

# ==============================================================================
# Default Configuration (override via config file, env vars, or CLI flags)
# ==============================================================================
ADMIN_USER="${ADMIN_USER:-}" # empty = auto-detect ("debian" on Debian, "ubuntu" on Ubuntu)
ADMIN_PASSWORD="${ADMIN_PASSWORD:-}"
ADMIN_NOPASSWD="${ADMIN_NOPASSWD:-true}"

CREATE_DEPLOY_USER="${CREATE_DEPLOY_USER:-true}"
DEPLOY_USER="${DEPLOY_USER:-deploy}"
DEPLOY_PASSWORD="${DEPLOY_PASSWORD:-}"
DEPLOY_SHARE_SSH_KEY="${DEPLOY_SHARE_SSH_KEY:-true}"

SSH_PUBLIC_KEY="${SSH_PUBLIC_KEY:-}"
SSH_PORT="${SSH_PORT:-22}"
DISABLE_PASSWORD_AUTH="${DISABLE_PASSWORD_AUTH:-true}"
PERMIT_ROOT_LOGIN="${PERMIT_ROOT_LOGIN:-no}" # no | prohibit-password | yes

FIREWALL_MODE="${FIREWALL_MODE:-ufw}" # ufw | nftables-setup | nftables-keep | none
EXTRA_PORTS="${EXTRA_PORTS:-}"       # comma-separated, e.g. "80/tcp,443/tcp"

ENABLE_FAIL2BAN="${ENABLE_FAIL2BAN:-true}"
FAIL2BAN_BANTIME="${FAIL2BAN_BANTIME:-1h}"
FAIL2BAN_FINDTIME="${FAIL2BAN_FINDTIME:-10m}"
FAIL2BAN_MAXRETRY="${FAIL2BAN_MAXRETRY:-5}"

RUN_APT_UPGRADE="${RUN_APT_UPGRADE:-true}"
APT_DIST_UPGRADE="${APT_DIST_UPGRADE:-false}"
INSTALL_COMMON_TOOLS="${INSTALL_COMMON_TOOLS:-true}"
COMMON_TOOLS="${COMMON_TOOLS:-curl wget nano vim tmux htop git unzip ca-certificates jq rsync lsof}"
INSTALL_FETCH_TOOL="${INSTALL_FETCH_TOOL:-true}" # prefers fastfetch, falls back to neofetch
ENABLE_UNATTENDED="${ENABLE_UNATTENDED:-true}"
UNATTENDED_ALL_ORIGINS="${UNATTENDED_ALL_ORIGINS:-true}"
UNATTENDED_AUTO_REBOOT="${UNATTENDED_AUTO_REBOOT:-true}"
UNATTENDED_REBOOT_WITH_USERS="${UNATTENDED_REBOOT_WITH_USERS:-true}"

UPGRADE_WINDOW_TZ="${UPGRADE_WINDOW_TZ:-Asia/Singapore}" # UTC+8 (no DST), or "local"
UPGRADE_START_HHMM="${UPGRADE_START_HHMM:-04:00}"
UPGRADE_RANDOM_MIN="${UPGRADE_RANDOM_MIN:-60}"
REBOOT_HHMM="${REBOOT_HHMM:-05:30}"

ENABLE_BBR="${ENABLE_BBR:-true}"
QDISC_ALGO="${QDISC_ALGO:-fq_codel}"           # fq_codel | fq
ENABLE_TCP_BUFFER_TUNING="${ENABLE_TCP_BUFFER_TUNING:-true}"
SWAP_SIZE="${SWAP_SIZE:-2G}"                   # target total swap (e.g. 2G, 2048M, 0 to skip)
SWAPPINESS="${SWAPPINESS:-auto}"               # auto (60 w/ zram, 10 w/o) | 0-200 | default
ENABLE_ZRAM="${ENABLE_ZRAM:-auto}"             # auto (VMs w/ zram module) | true | false
ZRAM_FRACTION="${ZRAM_FRACTION:-1.0}"          # Fedora-style RAM fraction (e.g. 1.0, 0.5)
ZRAM_MAX_SIZE="${ZRAM_MAX_SIZE:-4G}"           # Max zram size cap (e.g. 4G, 4096M, 0=uncapped)
ZRAM_ALGO="${ZRAM_ALGO:-lz4}"
ENABLE_LOG_LIMITS="${ENABLE_LOG_LIMITS:-true}" # cap journald + harden logrotate
JOURNAL_MAX_USE="${JOURNAL_MAX_USE:-50M}"
JOURNAL_MAX_FILE="${JOURNAL_MAX_FILE:-10M}"
JOURNAL_RUNTIME_MAX="${JOURNAL_RUNTIME_MAX:-20M}"

TIMEZONE="${TIMEZONE:-America/Los_Angeles}"
AUTO_TIMEZONE="${AUTO_TIMEZONE:-ask}" # ask | true | false
ENABLE_NTP="${ENABLE_NTP:-true}"

INTERACTIVE="${INTERACTIVE:-true}"
PROMPT_ADMIN_PASSWORD="${PROMPT_ADMIN_PASSWORD:-false}"
PROMPT_MISSING_SSH_KEY="${PROMPT_MISSING_SSH_KEY:-false}"
DRY_RUN="${DRY_RUN:-false}"
CONFIG_FILE="${CONFIG_FILE:-}"
SAVE_CONFIG_PATH="${SAVE_CONFIG_PATH:-}"

PRESET_NAME="${PRESET_NAME:-}"
DEFAULT_PRESET_BASE_URL="https://vps-bootstrap.pages.dev/preset/"
FALLBACK_PRESET_BASE_URL="https://raw.githubusercontent.com/SodaWithoutSparkles/vps-bootstrap/main/preset/"
PRESET_BASE_URL="${PRESET_BASE_URL:-$DEFAULT_PRESET_BASE_URL}"

UI_LANG="${UI_LANG:-}"
DEFAULT_LANG_BASE_URL="https://vps-bootstrap.pages.dev/lang/"
FALLBACK_LANG_BASE_URL="https://raw.githubusercontent.com/SodaWithoutSparkles/vps-bootstrap/main/lang/"
LANG_BASE_URL="${LANG_BASE_URL:-$DEFAULT_LANG_BASE_URL}"

RESOLVED_SSH_KEYS=""
REF_DAILY_HHMM=""
LOCAL_UPGRADE_HHMM=""
LOCAL_REBOOT_HHMM=""
LOADED_UI_LANG=""
LOADED_LANG_BASE=""
LOADED_LANG_SOURCE=""
LOADED_PRESET_SOURCE=""
declare -A L10N=()

# ==============================================================================
# Logging & Utility Helpers
# ==============================================================================
if [[ -t 1 ]]; then
  C_BLUE='\033[1;34m'
  C_GREEN='\033[1;32m'
  C_YELLOW='\033[1;33m'
  C_RED='\033[1;31m'
  C_BOLD='\033[1m'
  C_RESET='\033[0m'
else
  C_BLUE='' C_GREEN='' C_YELLOW='' C_RED='' C_BOLD='' C_RESET=''
fi

info()  { printf "${C_BLUE}[INFO]${C_RESET} %s\n" "$*"; }
ok()    { printf "${C_GREEN}[OK]${C_RESET} %s\n" "$*"; }
warn()  { printf "${C_YELLOW}[WARN]${C_RESET} %s\n" "$*" >&2; }
die()   { printf "${C_RED}[ERROR]${C_RESET} %s\n" "$*" >&2; exit 1; }
step()  { printf "\n${C_BOLD}=== %s ===${C_RESET}\n" "$*"; }

fmt_msg() {
  local _fm_out="$1" _fm_key="$2" _fm_tpl="$3"
  shift 3
  _fm_tpl="${L10N[$_fm_key]:-$_fm_tpl}"
  if (( $# == 0 )) || [[ "$_fm_tpl" != *'{'* ]]; then
    printf -v "$_fm_out" '%s' "$_fm_tpl"
    return 0
  fi
  local -a _fm_args=("$@")
  local _fm_res="" _fm_head _fm_idx
  while [[ "$_fm_tpl" == *'{'* ]]; do
    _fm_head="${_fm_tpl%%\{*}"
    _fm_res+="$_fm_head"
    _fm_tpl="${_fm_tpl:${#_fm_head}}"
    if [[ "$_fm_tpl" =~ ^\{([1-9][0-9]*)\} ]]; then
      _fm_idx="${BASH_REMATCH[1]}"
      _fm_tpl="${_fm_tpl:${#BASH_REMATCH[0]}}"
      if (( _fm_idx <= ${#_fm_args[@]} )); then
        _fm_res+="${_fm_args[$((_fm_idx - 1))]}"
      else
        _fm_res+="{${_fm_idx}}"
      fi
    else
      _fm_res+="{"
      _fm_tpl="${_fm_tpl:1}"
    fi
  done
  _fm_res+="$_fm_tpl"
  printf -v "$_fm_out" '%s' "$_fm_res"
}

info_t() { local _msg; fmt_msg _msg "$@"; info "$_msg"; }
ok_t()   { local _msg; fmt_msg _msg "$@"; ok "$_msg"; }
warn_t() { local _msg; fmt_msg _msg "$@"; warn "$_msg"; }
die_t()  { local _msg; fmt_msg _msg "$@"; die "$_msg"; }
step_t() { local _msg; fmt_msg _msg "$@"; step "$_msg"; }
echo_t() { local _msg; fmt_msg _msg "$@"; printf '%s\n' "$_msg"; }

normalize_bool() {
  local val="${1,,}"
  case "$val" in
    true|t|yes|y|1|on)  echo "true" ;;
    false|f|no|n|0|off) echo "false" ;;
    *) return 1 ;;
  esac
}

validate_username() {
  local name="$1"
  [[ "$name" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] && [[ "$name" != "root" ]]
}

validate_port() {
  local p="$1"
  [[ "$p" =~ ^[1-9][0-9]*$ ]] && (( p >= 1 && p <= 65535 ))
}

validate_port_spec() {
  local spec="$1" mode="${2:-ufw}"
  if [[ "$spec" =~ ^([0-9]+)/(tcp|udp)$ ]]; then
    validate_port "${BASH_REMATCH[1]}"
  elif [[ "$spec" =~ ^([0-9]+)$ ]]; then
    validate_port "${BASH_REMATCH[1]}"
  elif [[ "$mode" == "ufw" && "$spec" =~ ^([0-9]+):([0-9]+)/(tcp|udp)$ ]]; then
    local start="${BASH_REMATCH[1]}" end="${BASH_REMATCH[2]}"
    validate_port "$start" && validate_port "$end" && (( start < end ))
  else
    return 1
  fi
}

parse_extra_ports() {
  local _pep_str="$1" _pep_mode="${2:-ufw}"
  local -n _pep_out="$3"
  _pep_out=()
  [[ -z "$_pep_str" ]] && return 0
  [[ "$_pep_str" != *$'\n'* ]] || return 1

  local -a _pep_raw=()
  local _pep_item
  IFS=',' read -ra _pep_raw <<< "$_pep_str"
  for _pep_item in "${_pep_raw[@]}"; do
    _pep_item="${_pep_item//[[:space:]]/}"
    [[ -z "$_pep_item" ]] && continue
    validate_port_spec "$_pep_item" "$_pep_mode" || return 1
    _pep_out+=("$_pep_item")
  done
}

validate_fail2ban_duration() {
  local val="$1" allow_perm="${2:-false}"
  [[ -n "$val" && "$val" != *$'\n'* ]] || return 1
  if [[ "$allow_perm" == "true" && "$val" == "-1" ]]; then
    return 0
  fi
  [[ "$val" =~ [1-9] ]] || return 1
  if [[ "$val" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
    return 0
  fi
  local unit_re='(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|da|day|days|w|ww|week|weeks|mo|mon|month|months|y|yr|yrs|year|years)'
  local full_re="^([0-9]+([.][0-9]+)?${unit_re})([[:space:]]*[0-9]+([.][0-9]+)?${unit_re})*$"
  [[ "$val" =~ $full_re ]]
}

validate_fail2ban_maxretry() {
  [[ "$1" =~ ^[1-9][0-9]*$ ]]
}

validate_hhmm() {
  [[ "$1" =~ ^([01][0-9]|2[0-3]):[0-5][0-9]$ ]]
}

resolve_tz_alias() {
  local tz="$1"
  case "${tz^^}" in
    UTC+0|UTC-0|GMT+0|GMT-0) echo "UTC" ;;
    UTC+[1-9]|UTC+1[0-4])
      local off="${tz#*[+]}"
      echo "Etc/GMT-${off}"
      ;;
    UTC-[1-9]|UTC-1[0-2])
      local off="${tz#*-}"
      echo "Etc/GMT+${off}"
      ;;
    *) echo "$tz" ;;
  esac
}

tz_exists() {
  local tz="$1"
  [[ "$tz" == "UTC" ]] && return 0
  [[ -f "/usr/share/zoneinfo/$tz" ]]
}

convert_hhmm_tz() {
  local hhmm="$1" from_tz="$2" to_tz="$3"
  if [[ "$from_tz" == "local" || "$from_tz" == "$to_tz" ]]; then
    echo "$hhmm"
    return 0
  fi
  local from_date
  from_date="$(TZ="$from_tz" date +%F)"
  TZ="$to_tz" date -d "TZ=\"$from_tz\" $from_date $hhmm" +%H:%M
}

shift_hhmm() {
  local hhmm="$1" offset_sec="$2" tz="$3"
  local ref_date epoch
  ref_date="$(TZ="$tz" date +%F)"
  epoch="$(TZ="$tz" date -d "$ref_date $hhmm" +%s)"
  TZ="$tz" date -d "@$(( epoch + offset_sec ))" +%H:%M
}

http_get() {
  local url="$1"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --max-time 6 "$url" 2>/dev/null
  elif command -v wget >/dev/null 2>&1; then
    wget -qO- -T 6 "$url" 2>/dev/null
  elif command -v python3 >/dev/null 2>&1; then
    python3 -c 'import sys,urllib.request; print(urllib.request.urlopen(sys.argv[1], timeout=6).read().decode())' "$url" 2>/dev/null
  else
    return 1
  fi
}

parse_geoip_json() {
  local json="$1"
  if command -v python3 >/dev/null 2>&1; then
    GEOIP_JSON="$json" python3 - <<'PYEOF' 2>/dev/null
import json, os
d = json.loads(os.environ["GEOIP_JSON"])
tz = d.get("timezone") or (d.get("location") or {}).get("timezone") or ""
ip = d.get("ip") or d.get("query") or ""
city = d.get("city") or ""
region = d.get("regionName") or d.get("region") or ""
country = d.get("country") or ""
print("\t".join([str(ip), str(city), str(region), str(country), str(tz)]))
PYEOF
  elif command -v jq >/dev/null 2>&1; then
    local jq_filter='[(.ip // .query // ""), (.city // ""), (.regionName // .region // ""), (.country // ""), (.timezone // .location.timezone // "")] | @tsv'
    jq -r "$jq_filter" <<< "$json" 2>/dev/null
  else
    local tz ip city region country
    tz=$(printf '%s' "$json" | sed -nE 's/.*"timezone"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' | head -n1)
    ip=$(printf '%s' "$json" | sed -nE 's/.*"(ip|query)"[[:space:]]*:[[:space:]]*"([^"]+)".*/\2/p' | head -n1)
    city=$(printf '%s' "$json" | sed -nE 's/.*"city"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' | head -n1)
    region=$(printf '%s' "$json" | sed -nE 's/.*"region(Name)?"[[:space:]]*:[[:space:]]*"([^"]+)".*/\2/p' | head -n1)
    country=$(printf '%s' "$json" | sed -nE 's/.*"country"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' | head -n1)
    printf '%s\t%s\t%s\t%s\t%s\n' "$ip" "$city" "$region" "$country" "$tz"
  fi
}

detect_timezone_by_ip() {
  local raw1="" raw2="" parsed1="" parsed2=""
  local ip1="" city1="" region1="" country1="" tz1=""
  local ip2="" city2="" region2="" country2="" tz2=""

  info_t L10N_INFO_GEOIP_QUERY "Querying external IP geolocation services..."
  if raw1="$(http_get "https://api.ipapi.is")"; then
    parsed1="$(parse_geoip_json "$raw1" || true)"
    IFS=$'\t' read -r ip1 city1 region1 country1 tz1 <<< "$parsed1"
    tz1="$(resolve_tz_alias "${tz1:-}")"
    tz_exists "$tz1" || tz1=""
  fi

  if raw2="$(http_get "http://ip-api.com/json")"; then
    parsed2="$(parse_geoip_json "$raw2" || true)"
    IFS=$'\t' read -r ip2 city2 region2 country2 tz2 <<< "$parsed2"
    tz2="$(resolve_tz_alias "${tz2:-}")"
    tz_exists "$tz2" || tz2=""
  fi

  if [[ -z "$tz1" && -z "$tz2" ]]; then
    warn_t L10N_WARN_GEOIP_FAILED "Could not determine a valid timezone from api.ipapi.is or ip-api.com."
    return 1
  fi

  [[ -n "$tz1" ]] && echo_t L10N_GEOIP_RESULT_LINE "  [{1}] IP={2} | {3}, {4}, {5} | Timezone={6}" "api.ipapi.is" "${ip1:-?}" "${city1:-?}" "${region1:-?}" "${country1:-?}" "${tz1}"
  [[ -n "$tz2" ]] && echo_t L10N_GEOIP_RESULT_LINE "  [{1}] IP={2} | {3}, {4}, {5} | Timezone={6}" "ip-api.com" "${ip2:-?}" "${city2:-?}" "${region2:-?}" "${country2:-?}" "${tz2}"

  local candidate="${tz1:-$tz2}"
  if [[ -n "$tz1" && -n "$tz2" && "$tz1" != "$tz2" ]]; then
    warn_t L10N_WARN_GEOIP_MISMATCH "The two IP services returned different timezones ({1} vs {2})." "$tz1" "$tz2"
  fi

  if [[ "$INTERACTIVE" == "true" ]]; then
    local accept="true"
    prompt_bool_t accept "true" L10N_PROMPT_USE_GEOIP_TZ "Use detected timezone '{1}'?" "$candidate"
    if [[ "$accept" == "true" ]]; then
      TIMEZONE="$candidate"
      return 0
    fi
    return 1
  else
    TIMEZONE="$candidate"
    ok_t L10N_OK_AUTO_TIMEZONE "Auto-detected timezone: {1}" "$TIMEZONE"
    return 0
  fi
}

parse_size_to_mib() {
  local raw="${1^^}"
  raw="${raw//[[:space:]]/}"
  if [[ "$raw" == "0" || "$raw" == "0M" || "$raw" == "0G" ]]; then
    echo 0
    return 0
  fi
  if [[ "$raw" =~ ^([0-9]+)G(B|IB)?$ ]]; then
    echo $(( BASH_REMATCH[1] * 1024 ))
  elif [[ "$raw" =~ ^([0-9]+)M(B|IB)?$ ]]; then
    echo "${BASH_REMATCH[1]}"
  elif [[ "$raw" =~ ^([0-9]+)$ ]]; then
    echo "$raw"
  else
    return 1
  fi
}

detect_default_admin_user() {
  local os_id="" os_like=""
  if [[ -r /etc/os-release ]]; then
    os_id="$(. /etc/os-release && printf '%s' "${ID:-}")"
    os_like="$(. /etc/os-release && printf '%s' "${ID_LIKE:-}")"
  fi
  case "${os_id,,}" in
    ubuntu) echo "ubuntu" ;;
    debian) echo "debian" ;;
    *)
      if [[ " ${os_like,,} " == *" ubuntu "* ]]; then
        echo "ubuntu"
      else
        echo "debian"
      fi
      ;;
  esac
}

apt_pkg_available() {
  local pkg="$1"
  apt-cache policy "$pkg" 2>/dev/null | awk '/Candidate:/ {found=1; exit ($2 == "(none)" || $2 == "") ? 1 : 0} END {if (!found) exit 1}'
}

is_container() {
  systemd-detect-virt --quiet --container 2>/dev/null
}

detect_mem_total_mib() {
  awk '/^MemTotal:/ {printf "%d\n", ($2 + 1023) / 1024; exit}' /proc/meminfo
}

should_enable_zram() {
  case "${ENABLE_ZRAM,,}" in
    false) return 1 ;;
    true)
      is_container && return 1
      return 0
      ;;
    auto)
      is_container && return 1
      modprobe -n zram >/dev/null 2>&1 || return 1
      return 0
      ;;
    *) return 1 ;;
  esac
}

compute_zram_size_mib() {
  local mem_mib max_mib
  mem_mib="$(detect_mem_total_mib)"
  max_mib="$(parse_size_to_mib "$ZRAM_MAX_SIZE")"
  awk -v ram="$mem_mib" -v frac="$ZRAM_FRACTION" -v max="$max_mib" '
    BEGIN {
      v = int(ram * frac);
      if (v < 1) v = 1;
      if (max > 0 && v > max) v = max;
      print v;
    }'
}

resolve_swappiness() {
  local zram_on="$1"
  if [[ "${SWAPPINESS,,}" != "auto" ]]; then
    echo "$SWAPPINESS"
    return 0
  fi
  if [[ "$zram_on" == "true" ]]; then
    echo 60
  else
    echo 10
  fi
}

get_tcp_buffer_tier_values() {
  # Prints: tier_label \t rmem_max \t wmem_max \t buf_default \t tcp_rmem \t tcp_wmem \t conntrack_max
  local mem_mib="$1"
  if (( mem_mib <= 384 )); then
    printf '256M\t4194304\t4194304\t262144\t4096 131072 4194304\t4096 65536 4194304\t32768\n'
  elif (( mem_mib <= 768 )); then
    printf '512M\t16777216\t8388608\t262144\t4096 131072 16777216\t4096 65536 8388608\t65536\n'
  elif (( mem_mib <= 1536 )); then
    printf '1G\t33554432\t16777216\t524288\t4096 131072 33554432\t4096 65536 16777216\t65536\n'
  else
    printf '2G+\t67108864\t33554432\t1048576\t4096 131072 67108864\t4096 65536 33554432\t131072\n'
  fi
}

validate_pubkey_line() {
  local line="$1"
  [[ -n "$line" ]] || return 1
  [[ "$line" =~ ^[[:space:]]*# ]] && return 1
  if command -v ssh-keygen >/dev/null 2>&1; then
    printf '%s\n' "$line" | ssh-keygen -lf - >/dev/null 2>&1
  else
    [[ "$line" =~ (ssh-(ed25519|rsa|dss)|ecdsa-sha2-nistp(256|384|521)|sk-(ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)[[:space:]]+[A-Za-z0-9+/=]+ ]]
  fi
}

extract_valid_keys_from_file() {
  local file="$1"
  [[ -r "$file" ]] || return 0
  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line%$'\r'}"
    [[ -z "${line//[[:space:]]/}" ]] && continue
    [[ "$line" =~ ^[[:space:]]*# ]] && continue
    [[ "$line" == *"Please login as the user"* ]] && continue
    if validate_pubkey_line "$line"; then
      printf '%s\n' "$line"
    fi
  done < "$file"
}

show_key_fingerprints() {
  local keys="$1"
  while IFS= read -r line; do
    [[ -z "$line" ]] && continue
    if command -v ssh-keygen >/dev/null 2>&1; then
      printf '  - %s\n' "$(printf '%s\n' "$line" | ssh-keygen -lf - 2>/dev/null || echo "$line")"
    else
      printf '  - %.60s...\n' "$line"
    fi
  done <<< "$keys"
}

# ==============================================================================
# Interactive Prompt Helpers
# ==============================================================================
prompt_val() {
  local var_name="$1" prompt_text="$2" default_val="$3"
  local input=""
  if [[ -n "$default_val" ]]; then
    read -r -p "$prompt_text [$default_val]: " input
    input="${input:-$default_val}"
  else
    read -r -p "$prompt_text: " input
  fi
  printf -v "$var_name" '%s' "$input"
}

prompt_bool() {
  local var_name="$1" prompt_text="$2" default_bool="$3"
  local hint="y/N"
  [[ "$default_bool" == "true" ]] && hint="Y/n"
  while true; do
    local input=""
    read -r -p "$prompt_text [$hint]: " input
    input="${input:-$default_bool}"
    if parsed=$(normalize_bool "$input"); then
      printf -v "$var_name" '%s' "$parsed"
      return 0
    fi
    warn_t L10N_WARN_ENTER_YN "Please enter y or n."
  done
}

prompt_secret() {
  local var_name="$1" prompt_text="$2" required="${3:-false}"
  local confirm_text=""
  fmt_msg confirm_text L10N_PROMPT_CONFIRM_PASSWORD "Confirm password"
  while true; do
    local p1="" p2=""
    read -r -s -p "$prompt_text: " p1
    echo ""
    if [[ -z "$p1" ]]; then
      if [[ "$required" == "true" ]]; then
        warn_t L10N_WARN_PASSWORD_REQUIRED "A password is required."
        continue
      fi
      printf -v "$var_name" '%s' ""
      return 0
    fi
    read -r -s -p "${confirm_text}: " p2
    echo ""
    if [[ "$p1" != "$p2" ]]; then
      warn_t L10N_WARN_PASSWORD_MISMATCH "Passwords did not match. Try again."
      continue
    fi
    printf -v "$var_name" '%s' "$p1"
    return 0
  done
}

prompt_val_t()    { local _v="$1" _d="$2" _msg; shift 2; fmt_msg _msg "$@"; prompt_val "$_v" "$_msg" "$_d"; }
prompt_bool_t()   { local _v="$1" _d="$2" _msg; shift 2; fmt_msg _msg "$@"; prompt_bool "$_v" "$_msg" "$_d"; }
prompt_secret_t() { local _v="$1" _r="$2" _msg; shift 2; fmt_msg _msg "$@"; prompt_secret "$_v" "$_msg" "$_r"; }

read_secret_file() {
  local var_name="$1" path="$2"
  [[ -n "$path" ]] || die_t L10N_ERR_PASSWORD_FILE_NEED_PATH "--password-file requires a path or descriptor"
  if [[ "$path" == "-" ]]; then
    path="/dev/stdin"
  else
    [[ -r "$path" ]] || die_t L10N_ERR_PASSWORD_FILE_UNREADABLE "Password file is not readable: {1}" "$path"
  fi
  if [[ -f "$path" ]]; then
    local meta uid mode
    meta="$(stat -L -c '%u %a' "$path")" || die_t L10N_ERR_PASSWORD_FILE_STAT "Cannot stat password file: {1}" "$path"
    read -r uid mode <<< "$meta"
    if (( uid != 0 && uid != EUID )) || (( (8#$mode & 8#077) != 0 )); then
      die_t L10N_ERR_PASSWORD_FILE_PERMS "Password file '{1}' must be owned by you or root with mode 0600 or 0400 (got uid={2} mode={3})." "$path" "$uid" "$mode"
    fi
  fi
  local secret=""
  IFS= read -r secret < "$path" || true
  secret="${secret%$'\r'}"
  [[ -n "$secret" ]] || die_t L10N_ERR_PASSWORD_FILE_EMPTY "Password file '{1}' is empty." "$path"
  printf -v "$var_name" '%s' "$secret"
}

is_allowed_config_key() {
  case "$1" in
    ADMIN_USER|ADMIN_PASSWORD|ADMIN_NOPASSWD|\
    CREATE_DEPLOY_USER|DEPLOY_USER|DEPLOY_PASSWORD|DEPLOY_SHARE_SSH_KEY|\
    SSH_PUBLIC_KEY|SSH_PORT|DISABLE_PASSWORD_AUTH|PERMIT_ROOT_LOGIN|\
    FIREWALL_MODE|EXTRA_PORTS|\
    ENABLE_FAIL2BAN|FAIL2BAN_BANTIME|FAIL2BAN_FINDTIME|FAIL2BAN_MAXRETRY|\
    RUN_APT_UPGRADE|APT_DIST_UPGRADE|INSTALL_COMMON_TOOLS|COMMON_TOOLS|INSTALL_FETCH_TOOL|\
    ENABLE_UNATTENDED|UNATTENDED_ALL_ORIGINS|UNATTENDED_AUTO_REBOOT|UNATTENDED_REBOOT_WITH_USERS|\
    UPGRADE_WINDOW_TZ|UPGRADE_START_HHMM|UPGRADE_RANDOM_MIN|REBOOT_HHMM|\
    ENABLE_BBR|QDISC_ALGO|ENABLE_TCP_BUFFER_TUNING|\
    SWAP_SIZE|SWAPPINESS|ENABLE_ZRAM|ZRAM_FRACTION|ZRAM_MAX_SIZE|ZRAM_ALGO|\
    ENABLE_LOG_LIMITS|JOURNAL_MAX_USE|JOURNAL_MAX_FILE|JOURNAL_RUNTIME_MAX|\
    TIMEZONE|AUTO_TIMEZONE|ENABLE_NTP|\
    UI_LANG|LANG_BASE_URL|PRESET_BASE_URL|\
    INTERACTIVE|PROMPT_ADMIN_PASSWORD|PROMPT_MISSING_SSH_KEY|DRY_RUN)
      return 0 ;;
    *)
      return 1 ;;
  esac
}

parse_config_value() {
  local _pcv_out="$1" _pcv_rhs="$2" _pcv_file="$3" _pcv_lineno="$4"
  if [[ "$_pcv_rhs" =~ ^[[:space:]]*(#.*)?$ ]]; then
    printf -v "$_pcv_out" '%s' ""
    return 0
  fi
  if [[ "$_pcv_rhs" == [[:space:]]* ]]; then
    die_t L10N_ERR_CFG_WHITESPACE "Unexpected whitespace after '=' in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
  fi

  local _pcv_val="" _pcv_i=0 _pcv_len=${#_pcv_rhs} _pcv_ch
  while (( _pcv_i < _pcv_len )); do
    _pcv_ch="${_pcv_rhs:_pcv_i:1}"
    if [[ "$_pcv_ch" == " " || "$_pcv_ch" == $'\t' ]]; then
      [[ "${_pcv_rhs:_pcv_i}" =~ ^[[:space:]]*(#.*)?$ ]] || die_t L10N_ERR_CFG_TRAILING "Invalid trailing content or unquoted space in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
      break
    elif [[ "$_pcv_ch" == '"' ]]; then
      ((++_pcv_i))
      local _pcv_closed=0 _pcv_c _pcv_esc
      while (( _pcv_i < _pcv_len )); do
        _pcv_c="${_pcv_rhs:_pcv_i:1}"
        if [[ "$_pcv_c" == '"' ]]; then
          _pcv_closed=1
          ((++_pcv_i))
          break
        elif [[ "$_pcv_c" == '\' ]]; then
          ((++_pcv_i))
          (( _pcv_i < _pcv_len )) || die_t L10N_ERR_CFG_ESCAPE "Unterminated escape in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
          _pcv_esc="${_pcv_rhs:_pcv_i:1}"
          case "$_pcv_esc" in
            '"'|'\'|'$'|'`') _pcv_val+="$_pcv_esc" ;;
            *) _pcv_val+="\\$_pcv_esc" ;;
          esac
        else
          _pcv_val+="$_pcv_c"
        fi
        ((++_pcv_i))
      done
      (( _pcv_closed )) || die_t L10N_ERR_CFG_DQUOTE "Unterminated double quote in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
    elif [[ "$_pcv_ch" == "'" ]]; then
      ((++_pcv_i))
      local _pcv_closed=0 _pcv_c
      while (( _pcv_i < _pcv_len )); do
        _pcv_c="${_pcv_rhs:_pcv_i:1}"
        if [[ "$_pcv_c" == "'" ]]; then
          _pcv_closed=1
          ((++_pcv_i))
          break
        fi
        _pcv_val+="$_pcv_c"
        ((++_pcv_i))
      done
      (( _pcv_closed )) || die_t L10N_ERR_CFG_SQUOTE "Unterminated single quote in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
    elif [[ "${_pcv_rhs:_pcv_i:2}" == "\$'" ]]; then
      (( _pcv_i += 2 ))
      local _pcv_closed=0 _pcv_c _pcv_esc
      while (( _pcv_i < _pcv_len )); do
        _pcv_c="${_pcv_rhs:_pcv_i:1}"
        if [[ "$_pcv_c" == "'" ]]; then
          _pcv_closed=1
          ((++_pcv_i))
          break
        elif [[ "$_pcv_c" == '\' ]]; then
          ((++_pcv_i))
          (( _pcv_i < _pcv_len )) || die_t L10N_ERR_CFG_ESCAPE "Unterminated escape in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
          _pcv_esc="${_pcv_rhs:_pcv_i:1}"
          case "$_pcv_esc" in
            a) _pcv_val+=$'\a' ;;
            b) _pcv_val+=$'\b' ;;
            e|E) _pcv_val+=$'\e' ;;
            f) _pcv_val+=$'\f' ;;
            n) _pcv_val+=$'\n' ;;
            r) _pcv_val+=$'\r' ;;
            t) _pcv_val+=$'\t' ;;
            v) _pcv_val+=$'\v' ;;
            \\|\'|\"|\?) _pcv_val+="$_pcv_esc" ;;
            x)
              local _pcv_hex="" _pcv_h _pcv_dec=""
              while (( _pcv_i + 1 < _pcv_len && ${#_pcv_hex} < 2 )); do
                _pcv_h="${_pcv_rhs:_pcv_i+1:1}"
                [[ "$_pcv_h" =~ [0-9a-fA-F] ]] || break
                _pcv_hex+="$_pcv_h"
                ((++_pcv_i))
              done
              [[ -n "$_pcv_hex" && "$_pcv_hex" != "0" && "$_pcv_hex" != "00" ]] || die_t L10N_ERR_CFG_HEX "Invalid hex escape in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
              printf -v _pcv_dec '%b' "\\x${_pcv_hex}"
              _pcv_val+="$_pcv_dec"
              ;;
            [0-7])
              local _pcv_oct="$_pcv_esc" _pcv_o _pcv_dec=""
              while (( _pcv_i + 1 < _pcv_len && ${#_pcv_oct} < 3 )); do
                _pcv_o="${_pcv_rhs:_pcv_i+1:1}"
                [[ "$_pcv_o" =~ [0-7] ]] || break
                _pcv_oct+="$_pcv_o"
                ((++_pcv_i))
              done
              (( 8#$_pcv_oct != 0 )) || die_t L10N_ERR_CFG_NUL "NUL byte not allowed in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
              printf -v _pcv_dec '%b' "\\0${_pcv_oct}"
              _pcv_val+="$_pcv_dec"
              ;;
            *) _pcv_val+="\\$_pcv_esc" ;;
          esac
        else
          _pcv_val+="$_pcv_c"
        fi
        ((++_pcv_i))
      done
      (( _pcv_closed )) || die_t L10N_ERR_CFG_ANSIC "Unterminated ANSI-C quote in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
    elif [[ "$_pcv_ch" == '\' ]]; then
      ((++_pcv_i))
      (( _pcv_i < _pcv_len )) || die_t L10N_ERR_CFG_BSLASH "Trailing backslash in '{1}' line {2}" "$_pcv_file" "$_pcv_lineno"
      _pcv_val+="${_pcv_rhs:_pcv_i:1}"
      ((++_pcv_i))
    else
      case "$_pcv_ch" in
        '$'|'`'|';'|'&'|'|'|'('|')'|'<'|'>')
          die_t L10N_ERR_CFG_UNQUOTED_CHAR "Disallowed unquoted character '{1}' in '{2}' line {3} (quote or escape value)" "$_pcv_ch" "$_pcv_file" "$_pcv_lineno"
          ;;
      esac
      _pcv_val+="$_pcv_ch"
      ((++_pcv_i))
    fi
  done

  printf -v "$_pcv_out" '%s' "$_pcv_val"
}

parse_config_stream() {
  local _pcs_src_label="$1" _pcs_mode="${2:-apply}" _pcs_secret_var="${3:-}" _pcs_allow_passwords="${4:-true}"
  local _pcs_line _pcs_lineno=0 _pcs_key _pcs_rhs _pcs_val _pcs_has_secret=0
  while IFS= read -r _pcs_line || [[ -n "$_pcs_line" ]]; do
    (( ++_pcs_lineno ))
    _pcs_line="${_pcs_line%$'\r'}"
    [[ "$_pcs_line" =~ ^[[:space:]]*(#|$) ]] && continue
    [[ "$_pcs_line" =~ ^[[:space:]]*([A-Z_][A-Z0-9_]*)=(.*)$ ]] || die_t L10N_ERR_CFG_SYNTAX "Invalid config syntax in '{1}' line {2}" "$_pcs_src_label" "$_pcs_lineno"
    _pcs_key="${BASH_REMATCH[1]}"
    _pcs_rhs="${BASH_REMATCH[2]}"
    is_allowed_config_key "$_pcs_key" || die_t L10N_ERR_CFG_BAD_KEY "Unknown or disallowed config key '{1}' in '{2}' line {3}" "$_pcs_key" "$_pcs_src_label" "$_pcs_lineno"
    if [[ "$_pcs_allow_passwords" != "true" && ( "$_pcs_key" == "ADMIN_PASSWORD" || "$_pcs_key" == "DEPLOY_PASSWORD" ) ]]; then
      die_t L10N_ERR_PRESET_PASSWORD "Password key '{1}' is not allowed in presets ('{2}' line {3}); use --config or --password-file." "$_pcs_key" "$_pcs_src_label" "$_pcs_lineno"
    fi
    parse_config_value _pcs_val "$_pcs_rhs" "$_pcs_src_label" "$_pcs_lineno"
    if [[ "$_pcs_mode" == "apply" ]]; then
      printf -v "$_pcs_key" '%s' "$_pcs_val"
      if [[ ( "$_pcs_key" == "ADMIN_PASSWORD" || "$_pcs_key" == "DEPLOY_PASSWORD" ) && -n "$_pcs_val" ]]; then
        _pcs_has_secret=1
      fi
    fi
  done
  if [[ -n "$_pcs_secret_var" ]]; then
    printf -v "$_pcs_secret_var" '%s' "$_pcs_has_secret"
  fi
}

validate_preset_stream() {
  parse_config_stream "$1" "validate" "" "false"
}

load_config_file() {
  local file="$1"
  [[ -f "$file" && -r "$file" ]] || die_t L10N_ERR_CFG_NOT_FOUND "Config file not found or not a readable regular file: {1}" "$file"

  local has_secret=0
  parse_config_stream "$file" "apply" has_secret "true" < "$file"

  if (( has_secret )) && [[ -f "$file" ]]; then
    local mode=""
    mode="$(stat -L -c '%a' "$file" 2>/dev/null || true)"
    if [[ -n "$mode" ]] && (( (8#$mode & 8#077) != 0 )); then
      warn_t L10N_WARN_CFG_SECRET_PERMS "Config file '{1}' contains a password and has mode {2} (recommended: 0600)." "$file" "$mode"
    fi
  fi
}

normalize_lang_code() {
  local raw="${1,,}"
  raw="${raw//_/-}"
  raw="${raw%%.*}"
  [[ "$raw" =~ ^[a-z0-9][a-z0-9-]{0,15}$ ]] || return 1
  printf '%s' "$raw"
}

parse_l10n_stream() {
  local src_label="$1"
  local line lineno=0 key rhs val
  while IFS= read -r line || [[ -n "$line" ]]; do
    (( ++lineno ))
    line="${line%$'\r'}"
    [[ "$line" =~ ^[[:space:]]*(#|$) ]] && continue
    [[ "$line" =~ ^[[:space:]]*(L10N_[A-Z0-9_]+)=(.*)$ ]] || die "Invalid language syntax in '$src_label' line $lineno"
    key="${BASH_REMATCH[1]}"
    rhs="${BASH_REMATCH[2]}"
    parse_config_value val "$rhs" "$src_label" "$lineno"
    L10N["$key"]="$val"
  done
}

fetch_pack_payload() {
  local _fp_subdir="$1" _fp_filename="$2" _fp_base="$3" _fp_def="$4" _fp_fb="$5" _fp_validator="$6"
  local _fp_payload_var="$7" _fp_src_var="$8" _fp_err_var="$9"
  local _fp_payload="" _fp_src="" _fp_err="" _fp_local=""

  if [[ -n "${BASH_SOURCE[0]:-}" ]]; then
    local _fp_dir
    _fp_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || true)"
    [[ -n "$_fp_dir" ]] && _fp_local="${_fp_dir}/${_fp_subdir}/${_fp_filename}"
  fi

  if [[ -d "$_fp_base" ]]; then
    _fp_src="${_fp_base%/}/${_fp_filename}"
    if [[ -r "$_fp_src" ]]; then
      _fp_payload="$(<"$_fp_src")"
    else
      printf -v "$_fp_src_var" '%s' "$_fp_src"
      return 1
    fi
  elif [[ "${_fp_base%/}" == "${_fp_def%/}" && -n "$_fp_local" && -r "$_fp_local" ]]; then
    _fp_src="$_fp_local"
    _fp_payload="$(<"$_fp_src")"
  elif [[ "$_fp_base" =~ ^https?://[^[:space:]]+$ ]]; then
    _fp_src="${_fp_base%/}/${_fp_filename}"
    if ! _fp_payload="$(http_get "$_fp_src")" || [[ -z "$_fp_payload" ]] || ! _fp_err="$("$_fp_validator" "$_fp_src" <<< "$_fp_payload" 2>&1 >/dev/null)"; then
      if [[ "${_fp_base%/}" == "${_fp_def%/}" && -n "$_fp_fb" ]]; then
        local _fp_fb_src="${_fp_fb%/}/${_fp_filename}" _fp_fb_payload="" _fp_fb_err=""
        if _fp_fb_payload="$(http_get "$_fp_fb_src")" && [[ -n "$_fp_fb_payload" ]] && _fp_fb_err="$("$_fp_validator" "$_fp_fb_src" <<< "$_fp_fb_payload" 2>&1 >/dev/null)"; then
          warn "Could not load '${_fp_src}'; using fallback '${_fp_fb_src}'."
          _fp_src="$_fp_fb_src"
          _fp_payload="$_fp_fb_payload"
          _fp_err=""
        else
          printf -v "$_fp_src_var" '%s' "$_fp_src"
          printf -v "$_fp_err_var" '%s' "${_fp_fb_err:-$_fp_err}"
          return 1
        fi
      else
        printf -v "$_fp_src_var" '%s' "$_fp_src"
        printf -v "$_fp_err_var" '%s' "$_fp_err"
        return 1
      fi
    fi
  else
    printf -v "$_fp_src_var" '%s' "$_fp_base"
    return 2
  fi

  if ! _fp_err="$("$_fp_validator" "$_fp_src" <<< "$_fp_payload" 2>&1 >/dev/null)"; then
    printf -v "$_fp_src_var" '%s' "$_fp_src"
    printf -v "$_fp_err_var" '%s' "$_fp_err"
    return 3
  fi

  printf -v "$_fp_payload_var" '%s' "$_fp_payload"
  printf -v "$_fp_src_var" '%s' "$_fp_src"
  printf -v "$_fp_err_var" '%s' ""
  return 0
}

load_language_pack() {
  local requested="$1"
  local code=""
  if ! code="$(normalize_lang_code "$requested")"; then
    warn "Invalid language code '$requested'; using built-in English."
    UI_LANG="en"
    unset L10N
    declare -gA L10N=()
    LOADED_UI_LANG="en"
    LOADED_LANG_BASE="$LANG_BASE_URL"
    LOADED_LANG_SOURCE=""
    return 0
  fi

  UI_LANG="$code"
  unset L10N
  declare -gA L10N=()
  LOADED_UI_LANG="$code"
  LOADED_LANG_BASE="$LANG_BASE_URL"
  LOADED_LANG_SOURCE=""
  [[ "$code" == "en" ]] && return 0

  local payload="" src_label="" err_msg="" rc=0
  fetch_pack_payload "lang" "${code}.lang" "$LANG_BASE_URL" "$DEFAULT_LANG_BASE_URL" "$FALLBACK_LANG_BASE_URL" parse_l10n_stream payload src_label err_msg || rc=$?
  case "$rc" in
    0) ;;
    2)
      warn "Invalid LANG_BASE_URL '$LANG_BASE_URL'; falling back to English."
      return 0
      ;;
    3)
      warn "Failed to parse language pack '$src_label' (${err_msg:-invalid format}); falling back to English."
      return 0
      ;;
    *)
      warn "Could not load language pack '$src_label'${err_msg:+ ($err_msg)}; falling back to English."
      return 0
      ;;
  esac

  parse_l10n_stream "$src_label" <<< "$payload"
  LOADED_LANG_SOURCE="$src_label"
}

load_preset() {
  local requested="$1"
  local payload="" src_label="" err_msg="" rc=0

  if [[ "$requested" =~ ^https?://[^[:space:]]+$ ]]; then
    src_label="$requested"
    if ! payload="$(http_get "$src_label")" || [[ -z "$payload" ]]; then
      die_t L10N_ERR_PRESET_NOT_FOUND "Could not load preset '{1}' from '{2}'." "$requested" "$src_label"
    fi
    if ! err_msg="$(validate_preset_stream "$src_label" <<< "$payload" 2>&1 >/dev/null)"; then
      die_t L10N_ERR_PRESET_PARSE "Invalid preset '{1}': {2}" "$src_label" "$err_msg"
    fi
  elif [[ "$requested" == */* ]]; then
    [[ -f "$requested" && -r "$requested" ]] || die_t L10N_ERR_PRESET_NOT_FOUND "Could not load preset '{1}' from '{2}'." "$requested" "$requested"
    src_label="$requested"
    payload="$(<"$src_label")"
    if ! err_msg="$(validate_preset_stream "$src_label" <<< "$payload" 2>&1 >/dev/null)"; then
      die_t L10N_ERR_PRESET_PARSE "Invalid preset '{1}': {2}" "$src_label" "$err_msg"
    fi
  else
    local code="${requested%.conf}"
    [[ "$code" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$ ]] || die_t L10N_ERR_PRESET_NAME "Invalid preset name: {1}" "$requested"
    fetch_pack_payload "preset" "${code}.conf" "$PRESET_BASE_URL" "$DEFAULT_PRESET_BASE_URL" "$FALLBACK_PRESET_BASE_URL" validate_preset_stream payload src_label err_msg || rc=$?
    case "$rc" in
      0) ;;
      2) die_t L10N_ERR_PRESET_URL "Invalid PRESET_BASE_URL: {1}" "$PRESET_BASE_URL" ;;
      3) die_t L10N_ERR_PRESET_PARSE "Invalid preset '{1}': {2}" "$src_label" "$err_msg" ;;
      *) die_t L10N_ERR_PRESET_NOT_FOUND "Could not load preset '{1}' from '{2}'." "$requested" "$src_label" ;;
    esac
  fi

  parse_config_stream "$src_label" "apply" "" "false" <<< "$payload"
  LOADED_PRESET_SOURCE="$src_label"
}

prompt_select_language() {
  [[ -z "$UI_LANG" ]] || return 0
  echo "Select language / 选择语言:"
  echo "  1) English (default)"
  echo "  2) 简体中文 (zh-cn)"
  local choice="" code=""
  while true; do
    read -r -p "Language / 语言 [1]: " choice
    choice="${choice:-1}"
    case "${choice,,}" in
      1|en|english)
        UI_LANG="en"
        return 0
        ;;
      2|zh-cn|zh_cn|zh)
        load_language_pack "zh-cn"
        return 0
        ;;
      *)
        if code="$(normalize_lang_code "$choice")"; then
          load_language_pack "$code"
          return 0
        fi
        warn "Enter 1, 2, or a language code (e.g. zh-cn) / 请输入 1、2 或语言代码（如 zh-cn）。"
        ;;
    esac
  done
}

# ==============================================================================
# CLI Usage & Argument Parsing
# ==============================================================================
usage_opt() {
  local flags="$1" key="$2" fallback="$3" desc=""
  fmt_msg desc "$key" "$fallback"
  printf '  %-27s %s\n' "$flags" "$desc"
}

usage() {
  echo_t L10N_USAGE_HEADER "Usage: sudo bash vps-setup.sh [OPTIONS]"
  echo ""
  echo_t L10N_USAGE_INTRO "Configurable Debian/Ubuntu VPS bootstrap script."
  echo_t L10N_USAGE_DEFAULT_MODE "By default, runs interactively with defaults shown in [brackets]."
  echo ""
  echo_t L10N_USAGE_SEC_OPTIONS "Options:"
  usage_opt "-c, --config FILE"             L10N_USAGE_OPT_CONFIG          "Load defaults from a config file (see vps.conf.example)"
  usage_opt "    --preset NAME|FILE|URL"    L10N_USAGE_OPT_PRESET          "Load preset from preset/ (e.g. recommended), file, or URL"
  usage_opt "    --preset-base-url URL"     L10N_USAGE_OPT_PRESET_BASE_URL "Base URL or directory for <name>.conf presets"
  usage_opt "    --non-interactive"         L10N_USAGE_OPT_NON_INTERACTIVE "Use config/flags/defaults without prompting"
  usage_opt "    --dry-run"                 L10N_USAGE_OPT_DRY_RUN         "Print resolved configuration and exit without changes"
  usage_opt "    --lang CODE"               L10N_USAGE_OPT_LANG            "UI language pack code (e.g. en, zh-cn; default: prompt/en)"
  usage_opt "    --lang-base-url URL"       L10N_USAGE_OPT_LANG_BASE_URL   "Base URL or directory for <lang>.lang packs"
  echo ""
  echo_t L10N_USAGE_SEC_USERS "  Users & Auth:"
  usage_opt "    --user NAME"               L10N_USAGE_OPT_USER            "Admin sudo username (default: auto from OS: debian/ubuntu)"
  usage_opt "    --password-file PATH"      L10N_USAGE_OPT_PASSWORD_FILE   "Read admin password from protected file or /dev/fd/N"
  usage_opt "    --nopasswd BOOL"           L10N_USAGE_OPT_NOPASSWD        "Passwordless sudo for admin user (true|false, default: true)"
  usage_opt "    --deploy-user NAME"        L10N_USAGE_OPT_DEPLOY_USER     "Non-privileged deploy username (default: deploy)"
  usage_opt "    --no-deploy-user"          L10N_USAGE_OPT_NO_DEPLOY_USER  "Skip creating a non-privileged deploy user"
  usage_opt "    --pubkey KEY"              L10N_USAGE_OPT_PUBKEY          "SSH public key string (or path to .pub file)"
  usage_opt "    --ssh-port PORT"           L10N_USAGE_OPT_SSH_PORT        "SSH port (default: 22)"
  usage_opt "    --disable-password-auth BOOL" L10N_USAGE_OPT_DISABLE_PW_AUTH "Ban SSH password auth (default: true)"
  usage_opt "    --root-login MODE"         L10N_USAGE_OPT_ROOT_LOGIN      "PermitRootLogin: no | prohibit-password | yes (default: no)"
  echo ""
  echo_t L10N_USAGE_SEC_FIREWALL "  Firewall & Fail2ban:"
  usage_opt "    --firewall MODE"           L10N_USAGE_OPT_FIREWALL        "ufw | nftables-setup | nftables-keep | none (default: ufw)"
  usage_opt "    --ports LIST"              L10N_USAGE_OPT_PORTS           "Extra ports to allow, e.g. \"80/tcp,443/tcp\""
  usage_opt "    --no-fail2ban"             L10N_USAGE_OPT_NO_FAIL2BAN     "Do not install/configure fail2ban"
  echo ""
  echo_t L10N_USAGE_SEC_UPDATES "  Updates & Maintenance:"
  usage_opt "    --no-upgrade"              L10N_USAGE_OPT_NO_UPGRADE      "Skip initial apt-get update/upgrade"
  usage_opt "    --dist-upgrade"            L10N_USAGE_OPT_DIST_UPGRADE    "Use dist-upgrade instead of upgrade initially"
  usage_opt "    --no-common-tools"         L10N_USAGE_OPT_NO_COMMON_TOOLS "Skip installing common CLI tools"
  usage_opt "    --tools LIST"              L10N_USAGE_OPT_TOOLS           "Space-separated common tools to install"
  usage_opt "    --no-fetch-tool"           L10N_USAGE_OPT_NO_FETCH_TOOL   "Skip installing fastfetch/neofetch"
  usage_opt "    --no-unattended"           L10N_USAGE_OPT_NO_UNATTENDED   "Skip unattended-upgrades configuration"
  usage_opt "    --no-auto-reboot"          L10N_USAGE_OPT_NO_AUTO_REBOOT  "Disable automatic reboot after unattended upgrades"
  usage_opt "    --upgrade-tz TZ"           L10N_USAGE_OPT_UPGRADE_TZ      "Reference timezone for upgrade window (default: Asia/Singapore)"
  usage_opt "    --upgrade-start HH:MM"     L10N_USAGE_OPT_UPGRADE_START   "Unattended upgrade start time in upgrade-tz (default: 04:00)"
  usage_opt "    --upgrade-delay MIN"       L10N_USAGE_OPT_UPGRADE_DELAY   "Random delay in minutes (default: 60)"
  usage_opt "    --reboot-time HH:MM"       L10N_USAGE_OPT_REBOOT_TIME     "Auto-reboot time in upgrade-tz (default: 05:30)"
  echo ""
  echo_t L10N_USAGE_SEC_SYSTEM "  System:"
  usage_opt "    --no-bbr"                  L10N_USAGE_OPT_NO_BBR          "Skip enabling TCP BBR"
  usage_opt "    --qdisc ALGO"              L10N_USAGE_OPT_QDISC           "Queue discipline: fq_codel | fq (default: fq_codel)"
  usage_opt "    --no-tcp-tuning"           L10N_USAGE_OPT_NO_TCP_TUNING   "Skip RAM-adaptive TCP buffer tuning"
  usage_opt "    --swap SIZE"               L10N_USAGE_OPT_SWAP            "Target total swap size, e.g. 2G, 512M, 0 (default: 2G)"
  usage_opt "    --swappiness N"            L10N_USAGE_OPT_SWAPPINESS      "vm.swappiness: auto (60 w/ zram, 10 w/o), 0-200, or 'default'"
  usage_opt "    --zram MODE"               L10N_USAGE_OPT_ZRAM            "Compressed RAM swap: auto | true | false (default: auto)"
  usage_opt "    --zram-fraction F"         L10N_USAGE_OPT_ZRAM_FRACTION   "Fedora-style RAM fraction for zram (default: 1.0)"
  usage_opt "    --zram-max SIZE"           L10N_USAGE_OPT_ZRAM_MAX        "Maximum zram size cap (default: 4G)"
  usage_opt "    --no-log-limits"           L10N_USAGE_OPT_NO_LOG_LIMITS   "Skip journald (50M) and logrotate size caps"
  usage_opt "    --timezone TZ"             L10N_USAGE_OPT_TIMEZONE        "System timezone (default: America/Los_Angeles)"
  usage_opt "    --auto-timezone"           L10N_USAGE_OPT_AUTO_TIMEZONE   "Detect timezone via external IP lookup (api.ipapi.is / ip-api.com)"
  usage_opt "    --no-ntp"                  L10N_USAGE_OPT_NO_NTP          "Skip NTP setup"
  usage_opt "    --save-config FILE"        L10N_USAGE_OPT_SAVE_CONFIG     "Save resolved non-secret settings to FILE"
  usage_opt "-h, --help"                    L10N_USAGE_OPT_HELP            "Show this help"
}

parse_args() {
  # Pre-scan for --lang/--preset/--config so CLI flags override preset/config and messages localize early.
  local cli_lang="" cli_lang_base="" cli_preset_base=""
  local args=("$@")
  for ((i = 0; i < ${#args[@]}; i++)); do
    case "${args[$i]}" in
      -c|--config)
        (( i + 1 < ${#args[@]} )) || die_t L10N_ERR_ARG_CONFIG "--config requires a file path"
        CONFIG_FILE="${args[$((i + 1))]}"
        ((++i))
        ;;
      --config=*)
        CONFIG_FILE="${args[$i]#*=}"
        ;;
      --preset)
        (( i + 1 < ${#args[@]} )) || die_t L10N_ERR_ARG_PRESET "--preset requires a preset name, file path, or URL"
        PRESET_NAME="${args[$((i + 1))]}"
        ((++i))
        ;;
      --preset=*)
        PRESET_NAME="${args[$i]#*=}"
        ;;
      --preset-base-url)
        (( i + 1 < ${#args[@]} )) || die_t L10N_ERR_ARG_PRESET_BASE "--preset-base-url requires a URL or directory path"
        cli_preset_base="${args[$((i + 1))]}"
        ((++i))
        ;;
      --preset-base-url=*)
        cli_preset_base="${args[$i]#*=}"
        ;;
      --lang)
        (( i + 1 < ${#args[@]} )) || die_t L10N_ERR_ARG_LANG "--lang requires a language code"
        cli_lang="${args[$((i + 1))]}"
        ((++i))
        ;;
      --lang=*)
        cli_lang="${args[$i]#*=}"
        ;;
      --lang-base-url)
        (( i + 1 < ${#args[@]} )) || die_t L10N_ERR_ARG_LANG_BASE "--lang-base-url requires a URL or directory path"
        cli_lang_base="${args[$((i + 1))]}"
        ((++i))
        ;;
      --lang-base-url=*)
        cli_lang_base="${args[$i]#*=}"
        ;;
    esac
  done

  [[ -n "$cli_lang_base" ]] && LANG_BASE_URL="$cli_lang_base"
  [[ -n "$cli_preset_base" ]] && PRESET_BASE_URL="$cli_preset_base"
  [[ -n "$cli_lang" ]] && load_language_pack "$cli_lang"

  if [[ -n "$PRESET_NAME" ]]; then
    load_preset "$PRESET_NAME"
    [[ -n "$cli_preset_base" ]] && PRESET_BASE_URL="$cli_preset_base"
  fi

  if [[ -n "$CONFIG_FILE" ]]; then
    load_config_file "$CONFIG_FILE"
  fi

  [[ -n "$cli_lang_base" ]] && LANG_BASE_URL="$cli_lang_base"
  [[ -n "$cli_preset_base" ]] && PRESET_BASE_URL="$cli_preset_base"
  [[ -n "$cli_lang" ]] && UI_LANG="$cli_lang"

  if [[ -n "$UI_LANG" ]]; then
    local norm_lang=""
    norm_lang="$(normalize_lang_code "$UI_LANG" || printf '%s' "$UI_LANG")"
    if [[ "$norm_lang" != "$LOADED_UI_LANG" || "$LANG_BASE_URL" != "$LOADED_LANG_BASE" ]]; then
      load_language_pack "$UI_LANG"
    fi
  fi

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -c|--config) shift 2 ;;
      --config=*) shift ;;
      --preset) shift 2 ;;
      --preset=*) shift ;;
      --preset-base-url) shift 2 ;;
      --preset-base-url=*) shift ;;
      --lang) shift 2 ;;
      --lang=*) shift ;;
      --lang-base-url) shift 2 ;;
      --lang-base-url=*) shift ;;
      --non-interactive)
        INTERACTIVE="false"
        PROMPT_ADMIN_PASSWORD="false"
        PROMPT_MISSING_SSH_KEY="false"
        shift
        ;;
      --dry-run) DRY_RUN="true"; shift ;;
      --user) ADMIN_USER="$2"; shift 2 ;;
      --password|--password=*)
        die_t L10N_ERR_ARG_PASSWORD_DISABLED "--password is disabled because CLI arguments expose credentials in process listings and shell history; use --password-file PATH (or /dev/fd/N), or omit for TTY prompt."
        ;;
      --password-file)
        [[ $# -ge 2 ]] || die_t L10N_ERR_PASSWORD_FILE_NEED_PATH "--password-file requires a path or descriptor"
        read_secret_file ADMIN_PASSWORD "$2"
        shift 2
        ;;
      --password-file=*)
        read_secret_file ADMIN_PASSWORD "${1#*=}"
        shift
        ;;
      --nopasswd) ADMIN_NOPASSWD="$(normalize_bool "$2")" || die_t L10N_ERR_ARG_INVALID_NOPASSWD "Invalid --nopasswd: {1}" "$2"; shift 2 ;;
      --deploy-user) CREATE_DEPLOY_USER="true"; DEPLOY_USER="$2"; shift 2 ;;
      --no-deploy-user) CREATE_DEPLOY_USER="false"; shift ;;
      --pubkey) SSH_PUBLIC_KEY="$2"; shift 2 ;;
      --ssh-port) SSH_PORT="$2"; shift 2 ;;
      --disable-password-auth) DISABLE_PASSWORD_AUTH="$(normalize_bool "$2")" || die_t L10N_ERR_ARG_INVALID_BOOL "Invalid bool: {1}" "$2"; shift 2 ;;
      --root-login) PERMIT_ROOT_LOGIN="$2"; shift 2 ;;
      --firewall) FIREWALL_MODE="$2"; shift 2 ;;
      --ports) EXTRA_PORTS="$2"; shift 2 ;;
      --no-fail2ban) ENABLE_FAIL2BAN="false"; shift ;;
      --no-upgrade) RUN_APT_UPGRADE="false"; shift ;;
      --dist-upgrade) APT_DIST_UPGRADE="true"; shift ;;
      --no-common-tools) INSTALL_COMMON_TOOLS="false"; shift ;;
      --tools) COMMON_TOOLS="$2"; INSTALL_COMMON_TOOLS="true"; shift 2 ;;
      --no-fetch-tool) INSTALL_FETCH_TOOL="false"; shift ;;
      --no-unattended) ENABLE_UNATTENDED="false"; shift ;;
      --no-auto-reboot) UNATTENDED_AUTO_REBOOT="false"; shift ;;
      --upgrade-tz) UPGRADE_WINDOW_TZ="$2"; shift 2 ;;
      --upgrade-start) UPGRADE_START_HHMM="$2"; shift 2 ;;
      --upgrade-delay) UPGRADE_RANDOM_MIN="$2"; shift 2 ;;
      --reboot-time) REBOOT_HHMM="$2"; shift 2 ;;
      --no-bbr) ENABLE_BBR="false"; shift ;;
      --qdisc) QDISC_ALGO="$2"; shift 2 ;;
      --no-tcp-tuning) ENABLE_TCP_BUFFER_TUNING="false"; shift ;;
      --swap) SWAP_SIZE="$2"; shift 2 ;;
      --swappiness) SWAPPINESS="$2"; shift 2 ;;
      --zram) ENABLE_ZRAM="$2"; shift 2 ;;
      --zram-fraction) ZRAM_FRACTION="$2"; shift 2 ;;
      --zram-max) ZRAM_MAX_SIZE="$2"; shift 2 ;;
      --no-log-limits) ENABLE_LOG_LIMITS="false"; shift ;;
      --timezone) TIMEZONE="$2"; AUTO_TIMEZONE="false"; shift 2 ;;
      --auto-timezone) AUTO_TIMEZONE="true"; shift ;;
      --no-ntp) ENABLE_NTP="false"; shift ;;
      --save-config) SAVE_CONFIG_PATH="$2"; shift 2 ;;
      -h|--help) usage; exit 0 ;;
      *) die_t L10N_ERR_ARG_UNKNOWN "Unknown option: {1} (use --help for usage)" "$1" ;;
    esac
  done
}

# ==============================================================================
# SSH Key Discovery & Interactive Prompts
# ==============================================================================
discover_or_prompt_ssh_keys() {
  local found_keys=""
  local source_desc=""

  if [[ -n "$SSH_PUBLIC_KEY" ]]; then
    if [[ -r "$SSH_PUBLIC_KEY" ]]; then
      found_keys="$(extract_valid_keys_from_file "$SSH_PUBLIC_KEY")"
      fmt_msg source_desc L10N_SSH_SOURCE_FILE "file {1}" "$SSH_PUBLIC_KEY"
    elif validate_pubkey_line "$SSH_PUBLIC_KEY"; then
      found_keys="$SSH_PUBLIC_KEY"
      fmt_msg source_desc L10N_SSH_SOURCE_PARAM "provided parameter"
    else
      die_t L10N_ERR_INVALID_PUBKEY "Provided SSH_PUBLIC_KEY is not a valid SSH public key or readable file."
    fi
  fi

  if [[ -z "$found_keys" && -n "${SUDO_USER:-}" && "${SUDO_USER}" != "root" ]]; then
    local sudo_home
    sudo_home="$(getent passwd "$SUDO_USER" | cut -d: -f6 || true)"
    if [[ -n "$sudo_home" && -r "$sudo_home/.ssh/authorized_keys" ]]; then
      found_keys="$(extract_valid_keys_from_file "$sudo_home/.ssh/authorized_keys")"
      [[ -n "$found_keys" ]] && source_desc="$sudo_home/.ssh/authorized_keys"
    fi
  fi

  if [[ -z "$found_keys" && -r /root/.ssh/authorized_keys ]]; then
    found_keys="$(extract_valid_keys_from_file /root/.ssh/authorized_keys)"
    [[ -n "$found_keys" ]] && source_desc="/root/.ssh/authorized_keys"
  fi

  if [[ -n "$found_keys" ]]; then
    info_t L10N_INFO_SSH_KEYS_FOUND "Found SSH public key(s) in {1}:" "$source_desc"
    show_key_fingerprints "$found_keys"
    if [[ "$INTERACTIVE" == "true" ]]; then
      local use_found="true"
      prompt_bool_t use_found "true" L10N_PROMPT_USE_FOUND_KEYS "Use these SSH public key(s) for user login?"
      if [[ "$use_found" != "true" ]]; then
        found_keys=""
      else
        local add_more="false"
        prompt_bool_t add_more "false" L10N_PROMPT_ADD_MORE_KEYS "Paste an additional SSH public key too?"
        if [[ "$add_more" == "true" ]]; then
          found_keys="${found_keys}"$'\n'"$(prompt_paste_pubkey)"
        fi
      fi
    fi
  else
    warn_t L10N_WARN_NO_SSH_KEYS "No existing SSH public key found in /root/.ssh/authorized_keys."
    if [[ "$INTERACTIVE" == "true" ]] || [[ "$PROMPT_MISSING_SSH_KEY" == "true" && -t 0 ]]; then
      found_keys="$(prompt_paste_pubkey)"
    elif [[ "$DISABLE_PASSWORD_AUTH" == "true" ]]; then
      die_t L10N_ERR_NO_PUBKEY_NONINTERACTIVE "No SSH public key found and running non-interactively; provide --pubkey to safely disable password login."
    fi
  fi

  RESOLVED_SSH_KEYS="$found_keys"
}

prompt_paste_pubkey() {
  local keys="" prompt_msg=""
  fmt_msg prompt_msg L10N_PROMPT_PASTE_PUBKEY "Paste an SSH public key (e.g. ssh-ed25519 AAAA...): "
  while true; do
    printf '%s' "$prompt_msg" >&2
    local line=""
    IFS= read -r line || true
    line="${line%$'\r'}"
    if validate_pubkey_line "$line"; then
      keys="$line"
      ok_t L10N_OK_PUBKEY_ACCEPTED "Valid SSH key accepted." >&2
      break
    fi
    warn_t L10N_WARN_INVALID_PUBKEY_FORMAT "Invalid SSH public key format. Please paste a valid public key line."
  done
  printf '%s' "$keys"
}

prompt_admin_password_if_needed() {
  if [[ -z "$ADMIN_PASSWORD" ]]; then
    local set_pw="false"
    local pw_required="false"
    if [[ "$ADMIN_NOPASSWD" == "false" ]]; then
      if ! id "$ADMIN_USER" >/dev/null 2>&1 || [[ "$(passwd -S "$ADMIN_USER" 2>/dev/null | awk '{print $2}')" != "P" ]]; then
        info_t L10N_INFO_SUDO_NEEDS_PW "Since passwordless sudo is disabled, '{1}' needs a password for sudo." "$ADMIN_USER"
        set_pw="true"
        pw_required="true"
      fi
    fi
    prompt_bool_t set_pw "$set_pw" L10N_PROMPT_ADMIN_SET_PW "Set/update login password for '{1}'?" "$ADMIN_USER"
    if [[ "$set_pw" == "true" ]]; then
      prompt_secret_t ADMIN_PASSWORD "$pw_required" L10N_PROMPT_ENTER_PW "Enter password for '{1}'" "$ADMIN_USER"
    elif [[ "$pw_required" == "true" ]]; then
      die_t L10N_ERR_NOPASSWD_NEEDS_PW "Cannot disable NOPASSWD sudo for '{1}' without a password." "$ADMIN_USER"
    fi
  fi
}

gather_interactive_options() {
  step_t L10N_STEP_INTERACTIVE_CONFIG "Interactive Configuration"

  while true; do
    prompt_val_t ADMIN_USER "$ADMIN_USER" L10N_PROMPT_ADMIN_USER "Admin sudo username"
    validate_username "$ADMIN_USER" && break
    warn_t L10N_WARN_INVALID_USERNAME "Invalid username '{1}' (lowercase alphanumeric/underscore/hyphen, not root)." "$ADMIN_USER"
  done

  prompt_bool_t ADMIN_NOPASSWD "$ADMIN_NOPASSWD" L10N_PROMPT_ADMIN_NOPASSWD "Grant passwordless sudo (NOPASSWD) to '{1}'?" "$ADMIN_USER"

  prompt_admin_password_if_needed

  prompt_bool_t CREATE_DEPLOY_USER "$CREATE_DEPLOY_USER" L10N_PROMPT_CREATE_DEPLOY "Create a non-privileged deploy user (no sudo)?"
  if [[ "$CREATE_DEPLOY_USER" == "true" ]]; then
    while true; do
      prompt_val_t DEPLOY_USER "$DEPLOY_USER" L10N_PROMPT_DEPLOY_USER "Deploy username"
      if validate_username "$DEPLOY_USER" && [[ "$DEPLOY_USER" != "$ADMIN_USER" ]]; then
        break
      fi
      warn_t L10N_WARN_INVALID_DEPLOY_USER "Invalid deploy username (must differ from '{1}' and not be 'root')." "$ADMIN_USER"
    done
    local set_dpw="false"
    prompt_bool_t set_dpw "false" L10N_PROMPT_DEPLOY_SET_PW "Set password for '{1}'? (No = SSH key only)" "$DEPLOY_USER"
    if [[ "$set_dpw" == "true" ]]; then
      prompt_secret_t DEPLOY_PASSWORD "false" L10N_PROMPT_ENTER_PW "Enter password for '{1}'" "$DEPLOY_USER"
    fi
  fi

  discover_or_prompt_ssh_keys

  if [[ "$CREATE_DEPLOY_USER" == "true" && -n "$RESOLVED_SSH_KEYS" ]]; then
    prompt_bool_t DEPLOY_SHARE_SSH_KEY "$DEPLOY_SHARE_SSH_KEY" L10N_PROMPT_DEPLOY_SHARE_KEY "Install the same SSH key(s) for '{1}'?" "$DEPLOY_USER"
  fi

  while true; do
    prompt_val_t SSH_PORT "$SSH_PORT" L10N_PROMPT_SSH_PORT "SSH port"
    validate_port "$SSH_PORT" && break
    warn_t L10N_WARN_INVALID_PORT_RANGE "Port must be 1..65535."
  done

  prompt_bool_t DISABLE_PASSWORD_AUTH "$DISABLE_PASSWORD_AUTH" L10N_PROMPT_DISABLE_PW_AUTH "Disable SSH password authentication (key-only)?"

  while true; do
    prompt_val_t PERMIT_ROOT_LOGIN "$PERMIT_ROOT_LOGIN" L10N_PROMPT_ROOT_LOGIN "Root SSH login policy (no | prohibit-password | yes)"
    case "$PERMIT_ROOT_LOGIN" in
      no|prohibit-password|yes) break ;;
      *) warn_t L10N_WARN_CHOOSE_ROOT_LOGIN "Choose: no, prohibit-password, or yes." ;;
    esac
  done

  while true; do
    echo_t L10N_FW_MENU_TITLE "Firewall options:"
    echo_t L10N_FW_MENU_1 "  1) ufw            - Install & enable UFW (deny incoming, allow SSH + extra ports)"
    echo_t L10N_FW_MENU_2 "  2) nftables-setup - Install & configure a clean /etc/nftables.conf"
    echo_t L10N_FW_MENU_3 "  3) nftables-keep  - Do not install UFW; leave existing nftables untouched"
    echo_t L10N_FW_MENU_4 "  4) none           - Skip firewall configuration"
    prompt_val_t FIREWALL_MODE "$FIREWALL_MODE" L10N_PROMPT_FIREWALL_MODE "Firewall mode"
    case "$FIREWALL_MODE" in
      1) FIREWALL_MODE="ufw"; break ;;
      2) FIREWALL_MODE="nftables-setup"; break ;;
      3) FIREWALL_MODE="nftables-keep"; break ;;
      4) FIREWALL_MODE="none"; break ;;
      ufw|nftables-setup|nftables-keep|none) break ;;
      *) warn_t L10N_WARN_INVALID_FIREWALL "Invalid firewall choice." ;;
    esac
  done

  if [[ "$FIREWALL_MODE" == "ufw" || "$FIREWALL_MODE" == "nftables-setup" ]]; then
    local -a _checked_ports=()
    while true; do
      prompt_val_t EXTRA_PORTS "$EXTRA_PORTS" L10N_PROMPT_EXTRA_PORTS "Extra firewall ports to allow (e.g. 80/tcp,443/tcp or blank)"
      parse_extra_ports "$EXTRA_PORTS" "$FIREWALL_MODE" _checked_ports && break
      warn_t L10N_WARN_INVALID_EXTRA_PORTS "Invalid EXTRA_PORTS '{1}' for {2} (use comma-separated port/proto like 80/tcp,443/tcp)." "$EXTRA_PORTS" "$FIREWALL_MODE"
    done
  fi

  prompt_bool_t ENABLE_FAIL2BAN "$ENABLE_FAIL2BAN" L10N_PROMPT_FAIL2BAN "Install and configure Fail2ban for SSH?"
  prompt_bool_t RUN_APT_UPGRADE "$RUN_APT_UPGRADE" L10N_PROMPT_APT_UPGRADE "Run apt update & upgrade now?"
  prompt_bool_t INSTALL_COMMON_TOOLS "$INSTALL_COMMON_TOOLS" L10N_PROMPT_COMMON_TOOLS "Install common CLI tools ({1})?" "$COMMON_TOOLS"
  prompt_bool_t INSTALL_FETCH_TOOL "$INSTALL_FETCH_TOOL" L10N_PROMPT_FETCH_TOOL "Install system fetch tool (fastfetch or neofetch, auto-selected after apt update)?"
  prompt_bool_t ENABLE_UNATTENDED "$ENABLE_UNATTENDED" L10N_PROMPT_UNATTENDED "Configure unattended-upgrades?"

  if [[ "$ENABLE_UNATTENDED" == "true" ]]; then
    prompt_bool_t UNATTENDED_ALL_ORIGINS "$UNATTENDED_ALL_ORIGINS" L10N_PROMPT_UNATTENDED_ORIGINS "Include non-security updates (origin=*)?"
    prompt_bool_t UNATTENDED_AUTO_REBOOT "$UNATTENDED_AUTO_REBOOT" L10N_PROMPT_AUTO_REBOOT "Enable automatic reboot when required?"
    prompt_val_t UPGRADE_WINDOW_TZ "$UPGRADE_WINDOW_TZ" L10N_PROMPT_UPGRADE_WINDOW_TZ "Reference timezone for upgrade window (e.g. Asia/Singapore for UTC+8, or local)"
    prompt_val_t UPGRADE_START_HHMM "$UPGRADE_START_HHMM" L10N_PROMPT_UPGRADE_START "Unattended upgrade start time (HH:MM in {1})" "$UPGRADE_WINDOW_TZ"
    prompt_val_t UPGRADE_RANDOM_MIN "$UPGRADE_RANDOM_MIN" L10N_PROMPT_UPGRADE_DELAY "Randomized delay in minutes"
    if [[ "$UNATTENDED_AUTO_REBOOT" == "true" ]]; then
      prompt_val_t REBOOT_HHMM "$REBOOT_HHMM" L10N_PROMPT_REBOOT_TIME "Automatic reboot time (HH:MM in {1})" "$UPGRADE_WINDOW_TZ"
    fi
  fi

  prompt_bool_t ENABLE_BBR "$ENABLE_BBR" L10N_PROMPT_ENABLE_BBR "Enable TCP BBR congestion control?"
  if [[ "$ENABLE_BBR" == "true" ]]; then
    while true; do
      prompt_val_t QDISC_ALGO "$QDISC_ALGO" L10N_PROMPT_QDISC "Queue discipline for BBR (fq_codel | fq)"
      case "$QDISC_ALGO" in
        fq_codel|fq) break ;;
        *) warn_t L10N_WARN_CHOOSE_QDISC "Choose 'fq_codel' or 'fq'." ;;
      esac
    done
  fi
  prompt_bool_t ENABLE_TCP_BUFFER_TUNING "$ENABLE_TCP_BUFFER_TUNING" L10N_PROMPT_TCP_TUNING "Auto-tune TCP buffers based on detected RAM size?"
  prompt_val_t SWAP_SIZE "$SWAP_SIZE" L10N_PROMPT_SWAP_SIZE "Target total swap size (e.g. 2G, 512M, or 0 to skip)"
  while true; do
    prompt_val_t ENABLE_ZRAM "$ENABLE_ZRAM" L10N_PROMPT_ZRAM "Install zram compressed RAM swap (auto | true | false)"
    case "${ENABLE_ZRAM,,}" in
      auto|true|false) ENABLE_ZRAM="${ENABLE_ZRAM,,}"; break ;;
      *) warn_t L10N_WARN_CHOOSE_ZRAM "Choose 'auto', 'true', or 'false'." ;;
    esac
  done
  if [[ "$ENABLE_ZRAM" != "false" ]]; then
    prompt_val_t ZRAM_FRACTION "$ZRAM_FRACTION" L10N_PROMPT_ZRAM_FRACTION "Zram RAM fraction (Fedora-style multiplier, e.g. 1.0, 0.5)"
    prompt_val_t ZRAM_MAX_SIZE "$ZRAM_MAX_SIZE" L10N_PROMPT_ZRAM_MAX "Max zram size cap (e.g. 4G, 2048M, or 0 for uncapped)"
  fi
  prompt_val_t SWAPPINESS "$SWAPPINESS" L10N_PROMPT_SWAPPINESS "vm.swappiness (auto = 60 w/ zram or 10 w/o, 0-200, or 'default')"
  prompt_bool_t ENABLE_LOG_LIMITS "$ENABLE_LOG_LIMITS" L10N_PROMPT_LOG_LIMITS "Limit journald ({1}) and tighten logrotate to protect /var/log?" "$JOURNAL_MAX_USE"

  local use_geoip="false"
  [[ "$AUTO_TIMEZONE" == "true" ]] && use_geoip="true"
  if [[ "$AUTO_TIMEZONE" != "false" ]]; then
    prompt_bool_t use_geoip "$use_geoip" L10N_PROMPT_AUTO_GEOIP_TZ "Detect timezone automatically via external IP service (api.ipapi.is / ip-api.com)?"
  fi
  if [[ "$use_geoip" == "true" ]] && detect_timezone_by_ip; then
    ok_t L10N_OK_SELECTED_TZ "Selected timezone: {1}" "$TIMEZONE"
  else
    prompt_val_t TIMEZONE "$TIMEZONE" L10N_PROMPT_TIMEZONE "System timezone (e.g. America/Los_Angeles, UTC)"
  fi

  prompt_bool_t ENABLE_NTP "$ENABLE_NTP" L10N_PROMPT_ENABLE_NTP "Enable systemd-timesyncd NTP time sync?"
}

validate_bool_settings() {
  local _vbs_var _vbs_norm
  for _vbs_var in \
    ADMIN_NOPASSWD \
    CREATE_DEPLOY_USER \
    DEPLOY_SHARE_SSH_KEY \
    DISABLE_PASSWORD_AUTH \
    ENABLE_FAIL2BAN \
    RUN_APT_UPGRADE \
    APT_DIST_UPGRADE \
    INSTALL_COMMON_TOOLS \
    INSTALL_FETCH_TOOL \
    ENABLE_UNATTENDED \
    UNATTENDED_ALL_ORIGINS \
    UNATTENDED_AUTO_REBOOT \
    UNATTENDED_REBOOT_WITH_USERS \
    ENABLE_BBR \
    ENABLE_TCP_BUFFER_TUNING \
    ENABLE_LOG_LIMITS \
    ENABLE_NTP \
    INTERACTIVE \
    PROMPT_ADMIN_PASSWORD \
    PROMPT_MISSING_SSH_KEY \
    DRY_RUN; do
    if ! _vbs_norm="$(normalize_bool "${!_vbs_var}")"; then
      die_t L10N_ERR_VAL_BOOL "Invalid {1}: {2} (expected true or false)" "$_vbs_var" "${!_vbs_var}"
    fi
    printf -v "$_vbs_var" '%s' "$_vbs_norm"
  done

  if [[ "${AUTO_TIMEZONE,,}" == "ask" ]]; then
    AUTO_TIMEZONE="ask"
  elif _vbs_norm="$(normalize_bool "$AUTO_TIMEZONE")"; then
    AUTO_TIMEZONE="$_vbs_norm"
  else
    die_t L10N_ERR_VAL_AUTO_TIMEZONE "Invalid AUTO_TIMEZONE: {1} (expected ask, true, or false)" "$AUTO_TIMEZONE"
  fi
}

validate_all_inputs() {
  validate_bool_settings
  validate_username "$ADMIN_USER" || die_t L10N_ERR_VAL_ADMIN_USER "Invalid ADMIN_USER: {1}" "$ADMIN_USER"
  if [[ "$CREATE_DEPLOY_USER" == "true" ]]; then
    validate_username "$DEPLOY_USER" || die_t L10N_ERR_VAL_DEPLOY_USER "Invalid DEPLOY_USER: {1}" "$DEPLOY_USER"
    [[ "$DEPLOY_USER" != "$ADMIN_USER" ]] || die_t L10N_ERR_VAL_DEPLOY_EQUALS_ADMIN "DEPLOY_USER cannot equal ADMIN_USER"
  fi
  validate_port "$SSH_PORT" || die_t L10N_ERR_VAL_SSH_PORT "Invalid SSH_PORT: {1}" "$SSH_PORT"
  case "$PERMIT_ROOT_LOGIN" in
    no|prohibit-password|yes) ;;
    *) die_t L10N_ERR_VAL_ROOT_LOGIN "Invalid PERMIT_ROOT_LOGIN: {1}" "$PERMIT_ROOT_LOGIN" ;;
  esac
  case "$FIREWALL_MODE" in
    ufw|nftables-setup|nftables-keep|none) ;;
    *) die_t L10N_ERR_VAL_FIREWALL "Invalid FIREWALL_MODE: {1}" "$FIREWALL_MODE" ;;
  esac
  if [[ "$FIREWALL_MODE" == "ufw" || "$FIREWALL_MODE" == "nftables-setup" || -n "$EXTRA_PORTS" ]]; then
    local -a _validated_ports=()
    local _port_mode="$FIREWALL_MODE"
    [[ "$_port_mode" == "ufw" || "$_port_mode" == "nftables-setup" ]] || _port_mode="ufw"
    parse_extra_ports "$EXTRA_PORTS" "$_port_mode" _validated_ports || die_t L10N_ERR_VAL_EXTRA_PORTS "Invalid EXTRA_PORTS '{1}' for {2} (expected comma-separated ports like 80/tcp,443/tcp)" "$EXTRA_PORTS" "$FIREWALL_MODE"
  fi
  if [[ "$ENABLE_FAIL2BAN" == "true" ]]; then
    validate_fail2ban_duration "$FAIL2BAN_BANTIME" "true" || die_t L10N_ERR_VAL_F2B_BANTIME "Invalid FAIL2BAN_BANTIME: {1} (expected e.g. 1h, 10m, 3600, or -1)" "$FAIL2BAN_BANTIME"
    validate_fail2ban_duration "$FAIL2BAN_FINDTIME" "false" || die_t L10N_ERR_VAL_F2B_FINDTIME "Invalid FAIL2BAN_FINDTIME: {1} (expected positive duration e.g. 10m, 600)" "$FAIL2BAN_FINDTIME"
    validate_fail2ban_maxretry "$FAIL2BAN_MAXRETRY" || die_t L10N_ERR_VAL_F2B_MAXRETRY "Invalid FAIL2BAN_MAXRETRY: {1} (expected positive integer >= 1)" "$FAIL2BAN_MAXRETRY"
  fi
  if [[ "$INSTALL_COMMON_TOOLS" == "true" && -n "${COMMON_TOOLS// }" ]]; then
    [[ "$COMMON_TOOLS" != *$'\n'* ]] || die_t L10N_ERR_VAL_TOOLS_MULTILINE "Invalid COMMON_TOOLS: multiline values are not allowed"
    local -a _tools=()
    local _t
    read -ra _tools <<< "$COMMON_TOOLS"
    for _t in "${_tools[@]}"; do
      [[ "$_t" =~ ^[a-zA-Z0-9][a-zA-Z0-9.+:=/-]*$ ]] || die_t L10N_ERR_VAL_TOOLS_TOKEN "Invalid package token in COMMON_TOOLS: '{1}'" "$_t"
    done
  fi
  case "$QDISC_ALGO" in
    fq_codel|fq) ;;
    *) die_t L10N_ERR_VAL_QDISC "Invalid QDISC_ALGO: {1} (expected fq_codel or fq)" "$QDISC_ALGO" ;;
  esac
  case "${ENABLE_ZRAM,,}" in
    auto|true|false) ENABLE_ZRAM="${ENABLE_ZRAM,,}" ;;
    *) die_t L10N_ERR_VAL_ZRAM "Invalid ENABLE_ZRAM: {1} (expected auto, true, or false)" "$ENABLE_ZRAM" ;;
  esac
  if ! awk -v f="$ZRAM_FRACTION" 'BEGIN {exit (f ~ /^([0-9]+([.][0-9]+)?|[.][0-9]+)$/ && f > 0 && f <= 2.0) ? 0 : 1}'; then
    die_t L10N_ERR_VAL_ZRAM_FRACTION "Invalid ZRAM_FRACTION: {1} (expected decimal >0 and <=2.0, e.g. 1.0 or 0.5)" "$ZRAM_FRACTION"
  fi
  parse_size_to_mib "$ZRAM_MAX_SIZE" >/dev/null || die_t L10N_ERR_VAL_ZRAM_MAX "Invalid ZRAM_MAX_SIZE: {1} (use e.g. 4G, 2048M, 0)" "$ZRAM_MAX_SIZE"
  [[ "$ZRAM_ALGO" =~ ^[a-zA-Z0-9_-]+$ ]] || die_t L10N_ERR_VAL_ZRAM_ALGO "Invalid ZRAM_ALGO: {1}" "$ZRAM_ALGO"
  if [[ "${SWAPPINESS,,}" == "auto" || "${SWAPPINESS,,}" == "default" ]]; then
    SWAPPINESS="${SWAPPINESS,,}"
  elif [[ -n "$SWAPPINESS" ]]; then
    [[ "$SWAPPINESS" =~ ^[0-9]+$ ]] && (( 10#$SWAPPINESS >= 0 && 10#$SWAPPINESS <= 200 )) || die_t L10N_ERR_VAL_SWAPPINESS "Invalid SWAPPINESS: {1} (expected auto, 0-200, or default)" "$SWAPPINESS"
    SWAPPINESS="$(( 10#$SWAPPINESS ))"
  fi

  TIMEZONE="$(resolve_tz_alias "$TIMEZONE")"
  tz_exists "$TIMEZONE" || die_t L10N_ERR_VAL_TIMEZONE "Unknown TIMEZONE: {1} (check /usr/share/zoneinfo)" "$TIMEZONE"

  if [[ "$ENABLE_UNATTENDED" == "true" ]]; then
    UPGRADE_WINDOW_TZ="$(resolve_tz_alias "$UPGRADE_WINDOW_TZ")"
    if [[ "$UPGRADE_WINDOW_TZ" != "local" ]]; then
      [[ "$UPGRADE_WINDOW_TZ" =~ ^[A-Za-z0-9_+./-]+$ ]] && tz_exists "$UPGRADE_WINDOW_TZ" || die_t L10N_ERR_VAL_UPGRADE_TZ "Unknown UPGRADE_WINDOW_TZ: {1}" "$UPGRADE_WINDOW_TZ"
      if command -v systemd-analyze >/dev/null 2>&1; then
        systemd-analyze calendar "*-*-* 00:00 ${UPGRADE_WINDOW_TZ}" >/dev/null 2>&1 || die_t L10N_ERR_VAL_UPGRADE_TZ "Unknown UPGRADE_WINDOW_TZ: {1}" "$UPGRADE_WINDOW_TZ"
      fi
    fi
    validate_hhmm "$UPGRADE_START_HHMM" || die_t L10N_ERR_VAL_UPGRADE_START "Invalid UPGRADE_START_HHMM: {1}" "$UPGRADE_START_HHMM"
    validate_hhmm "$REBOOT_HHMM" || die_t L10N_ERR_VAL_REBOOT_HHMM "Invalid REBOOT_HHMM: {1}" "$REBOOT_HHMM"
    [[ "$UPGRADE_RANDOM_MIN" =~ ^[0-9]+$ ]] || die_t L10N_ERR_VAL_UPGRADE_DELAY "Invalid UPGRADE_RANDOM_MIN: {1}" "$UPGRADE_RANDOM_MIN"

    local src_tz="$UPGRADE_WINDOW_TZ"
    [[ "$src_tz" == "local" ]] && src_tz="$TIMEZONE"
    REF_DAILY_HHMM="$(shift_hhmm "$UPGRADE_START_HHMM" -3600 "$src_tz")"
    LOCAL_UPGRADE_HHMM="$(convert_hhmm_tz "$UPGRADE_START_HHMM" "$src_tz" "$TIMEZONE")"
    LOCAL_REBOOT_HHMM="$(convert_hhmm_tz "$REBOOT_HHMM" "$src_tz" "$TIMEZONE")"
  fi

  parse_size_to_mib "$SWAP_SIZE" >/dev/null || die_t L10N_ERR_VAL_SWAP_SIZE "Invalid SWAP_SIZE: {1} (use e.g. 2G, 512M, 0)" "$SWAP_SIZE"
}

# ==============================================================================
# Provisioning Steps
# ==============================================================================
setup_user_account() {
  local username="$1" password="$2" ssh_keys="$3" grant_sudo="$4" nopasswd="$5" lock_when_empty="${6:-false}"

  if ! id "$username" >/dev/null 2>&1; then
    adduser --disabled-password --gecos "" "$username"
    ok_t L10N_OK_USER_CREATED "Created user '{1}'." "$username"
  else
    info_t L10N_INFO_USER_EXISTS "User '{1}' already exists." "$username"
  fi

  if [[ -n "$password" ]]; then
    printf '%s:%s\n' "$username" "$password" | chpasswd
    ok_t L10N_OK_USER_PW_UPDATED "Updated password for '{1}'." "$username"
  elif [[ "$lock_when_empty" == "true" ]]; then
    passwd -l "$username" >/dev/null
    ok_t L10N_OK_USER_PW_LOCKED "Locked password for '{1}' (SSH key only)." "$username"
  fi

  local home_dir
  home_dir="$(getent passwd "$username" | cut -d: -f6)"

  if [[ -n "$ssh_keys" ]]; then
    mkdir -p "$home_dir/.ssh"
    touch "$home_dir/.ssh/authorized_keys"
    while IFS= read -r k; do
      [[ -z "$k" ]] && continue
      if ! grep -qxF "$k" "$home_dir/.ssh/authorized_keys"; then
        printf '%s\n' "$k" >> "$home_dir/.ssh/authorized_keys"
      fi
    done <<< "$ssh_keys"
    chown -R "$username:$username" "$home_dir/.ssh"
    chmod 700 "$home_dir/.ssh"
    chmod 600 "$home_dir/.ssh/authorized_keys"
    ok_t L10N_OK_USER_SSH_KEYS "Configured SSH authorized_keys for '{1}'." "$username"
  fi

  local sudoers_file="/etc/sudoers.d/90-${username}"
  if [[ "$grant_sudo" == "true" ]]; then
    usermod -aG sudo "$username"
    if [[ "$nopasswd" == "true" ]]; then
      printf '%s ALL=(ALL) NOPASSWD:ALL\n' "$username" > "$sudoers_file"
      chmod 440 "$sudoers_file"
      visudo -cf "$sudoers_file" >/dev/null
      ok_t L10N_OK_SUDO_NOPASSWD "Granted passwordless sudo to '{1}'." "$username"
    else
      rm -f "$sudoers_file"
      ok_t L10N_OK_SUDO_PASSWD "Added '{1}' to sudo group (password-prompted)." "$username"
    fi
  else
    if id -nG "$username" | grep -w sudo >/dev/null; then
      gpasswd -d "$username" sudo >/dev/null || true
    fi
    rm -f "$sudoers_file"
    ok_t L10N_OK_NO_SUDO "Confirmed '{1}' has no sudo privileges." "$username"
  fi
}

configure_users() {
  step_t L10N_STEP_USERS "Users & Sudoers"
  setup_user_account "$ADMIN_USER" "$ADMIN_PASSWORD" "$RESOLVED_SSH_KEYS" "true" "$ADMIN_NOPASSWD" "false"

  if [[ "$CREATE_DEPLOY_USER" == "true" ]]; then
    local d_keys=""
    [[ "$DEPLOY_SHARE_SSH_KEY" == "true" ]] && d_keys="$RESOLVED_SSH_KEYS"
    setup_user_account "$DEPLOY_USER" "$DEPLOY_PASSWORD" "$d_keys" "false" "false" "true"
  fi
}

configure_ssh_hardening() {
  step_t L10N_STEP_SSH "SSH Hardening"
  local admin_home admin_ak
  admin_home="$(getent passwd "$ADMIN_USER" | cut -d: -f6)"
  admin_ak="$admin_home/.ssh/authorized_keys"

  if [[ "$DISABLE_PASSWORD_AUTH" == "true" ]]; then
    if [[ ! -s "$admin_ak" ]] || [[ -z "$(extract_valid_keys_from_file "$admin_ak")" ]]; then
      die_t L10N_ERR_SSH_NO_KEY "Refusing to disable SSH password authentication: no valid SSH key in {1}!" "$admin_ak"
    fi
  fi

  mkdir -p /etc/ssh/sshd_config.d
  # OpenSSH uses first-match-wins: 00-vps-hardening.conf must sort before provider files (e.g. 01-*, 50-cloud-init.conf).
  rm -f /etc/ssh/sshd_config.d/99-hardening.conf
  local cfg="/etc/ssh/sshd_config.d/00-vps-hardening.conf"
  {
    echo "# Managed by vps-setup.sh (00-* ensures precedence over provider drop-ins)"
    echo "Port ${SSH_PORT}"
    echo "PermitRootLogin ${PERMIT_ROOT_LOGIN}"
    echo "PubkeyAuthentication yes"
    if [[ "$DISABLE_PASSWORD_AUTH" == "true" ]]; then
      echo "PasswordAuthentication no"
      echo "KbdInteractiveAuthentication no"
      echo "AuthenticationMethods publickey"
    else
      echo "PasswordAuthentication yes"
    fi
  } > "$cfg"

  # Ensure sshd_config includes sshd_config.d BEFORE any conflicting directives
  local inc_line first_auth_line
  inc_line="$(awk '/^[[:space:]]*Include[[:space:]]+\/etc\/ssh\/sshd_config\.d\/\*\.conf/ {print NR; exit}' /etc/ssh/sshd_config)"
  first_auth_line="$(awk '/^[[:space:]]*(Port|PermitRootLogin|PasswordAuthentication|KbdInteractiveAuthentication|PubkeyAuthentication|AuthenticationMethods)[[:space:]]/ {print NR; exit}' /etc/ssh/sshd_config)"
  if [[ -z "$inc_line" ]] || { [[ -n "$first_auth_line" ]] && (( inc_line > first_auth_line )); }; then
    warn_t L10N_WARN_PREPEND_SSH_INCLUDE "Prepending Include /etc/ssh/sshd_config.d/*.conf at top of /etc/ssh/sshd_config so hardening takes precedence."
    sed -i '1i Include /etc/ssh/sshd_config.d/*.conf' /etc/ssh/sshd_config
  fi

  # Support socket-activated ssh on newer Ubuntu releases when changing SSH_PORT
  if systemctl is-enabled --quiet ssh.socket 2>/dev/null; then
    mkdir -p /etc/systemd/system/ssh.socket.d
    cat <<EOF > /etc/systemd/system/ssh.socket.d/override.conf
[Socket]
ListenStream=
ListenStream=${SSH_PORT}
EOF
    systemctl daemon-reload
  fi

  # Debian/Ubuntu need /run/sshd for sshd -t if not yet created
  mkdir -p /run/sshd
  sshd -t

  # Verify effective sshd configuration actually honors our policy (first-match-wins sanity check)
  local eff_root eff_pw
  eff_root="$(sshd -T | awk '$1=="permitrootlogin"{print $2}')"
  eff_pw="$(sshd -T | awk '$1=="passwordauthentication"{print $2}')"
  if [[ "$eff_root" != "$PERMIT_ROOT_LOGIN" ]]; then
    die_t L10N_ERR_SSH_EFF_ROOT "Effective sshd PermitRootLogin is '{1}' (expected '{2}'). Check /etc/ssh/sshd_config and /etc/ssh/sshd_config.d/." "$eff_root" "$PERMIT_ROOT_LOGIN"
  fi
  if [[ "$DISABLE_PASSWORD_AUTH" == "true" && "$eff_pw" != "no" ]]; then
    die_t L10N_ERR_SSH_EFF_PW "Effective sshd PasswordAuthentication is '{1}' (expected 'no'). Check /etc/ssh/sshd_config and /etc/ssh/sshd_config.d/." "$eff_pw"
  fi

  local ssh_unit=""
  for candidate in ssh.service sshd.service; do
    if systemctl list-unit-files "$candidate" --no-legend 2>/dev/null | awk '{print $1}' | grep -Fx "$candidate" >/dev/null; then
      ssh_unit="$candidate"
      break
    fi
  done

  if [[ -n "$ssh_unit" ]]; then
    systemctl reload-or-restart "$ssh_unit"
    if [[ "$ssh_unit" == "ssh.service" ]] && systemctl is-active --quiet ssh.socket 2>/dev/null; then
      systemctl restart ssh.socket
    fi
  else
    die_t L10N_ERR_SSH_NO_UNIT "Could not identify ssh/sshd systemd service to reload."
  fi
  local pw_auth_state="yes"
  [[ "$DISABLE_PASSWORD_AUTH" == "true" ]] && pw_auth_state="no"
  ok_t L10N_OK_SSH_HARDENED "SSH hardened (Port={1}, PermitRootLogin={2}, PasswordAuth={3})." "$SSH_PORT" "$PERMIT_ROOT_LOGIN" "$pw_auth_state"
}

install_packages() {
  step_t L10N_STEP_PACKAGES "Packages & System Upgrade"
  export DEBIAN_FRONTEND=noninteractive
  apt-get update

  if [[ "$RUN_APT_UPGRADE" == "true" ]]; then
    if [[ "$APT_DIST_UPGRADE" == "true" ]]; then
      apt-get dist-upgrade -y
    else
      apt-get upgrade -y
    fi
    ok_t L10N_OK_PKG_UPGRADED "System packages upgraded."
  fi

  local pkgs=(sudo)
  case "$FIREWALL_MODE" in
    ufw) pkgs+=(ufw) ;;
    nftables-setup) pkgs+=(nftables) ;;
    nftables-keep)
      # Ensure nftables is available if fail2ban uses nftables banaction
      [[ "$ENABLE_FAIL2BAN" == "true" ]] && pkgs+=(nftables)
      ;;
  esac
  [[ "$ENABLE_FAIL2BAN" == "true" ]] && pkgs+=(fail2ban)
  [[ "$ENABLE_UNATTENDED" == "true" ]] && pkgs+=(unattended-upgrades apt-listchanges)
  if [[ "$ENABLE_NTP" == "true" ]] && ! is_container; then
    if ! systemctl is-active --quiet chrony 2>/dev/null && ! dpkg -s chrony >/dev/null 2>&1; then
      pkgs+=(systemd-timesyncd)
    fi
  fi
  if should_enable_zram && modprobe zram 2>/dev/null; then
    if apt_pkg_available systemd-zram-generator; then
      pkgs+=(systemd-zram-generator)
    elif apt_pkg_available zram-tools; then
      pkgs+=(zram-tools)
    fi
  fi
  if [[ "$INSTALL_COMMON_TOOLS" == "true" && -n "${COMMON_TOOLS// }" ]]; then
    local -a extra_tools=()
    read -ra extra_tools <<< "$COMMON_TOOLS"
    pkgs+=("${extra_tools[@]}")
  fi
  if [[ "$INSTALL_FETCH_TOOL" == "true" ]]; then
    if apt_pkg_available fastfetch; then
      pkgs+=(fastfetch)
    elif apt_pkg_available neofetch; then
      pkgs+=(neofetch)
    else
      warn_t L10N_WARN_NO_FETCH_PKG "Neither fastfetch nor neofetch is available in APT repositories; skipping."
    fi
  fi

  apt-get install -y "${pkgs[@]}"
  ok_t L10N_OK_PKGS_INSTALLED "Installed packages: {1}" "${pkgs[*]}"
}

configure_firewall() {
  step_t L10N_STEP_FIREWALL "Firewall ({1})" "$FIREWALL_MODE"

  local -a parsed_ports=()
  local _port_mode="$FIREWALL_MODE"
  [[ "$_port_mode" == "ufw" || "$_port_mode" == "nftables-setup" ]] || _port_mode="ufw"
  parse_extra_ports "$EXTRA_PORTS" "$_port_mode" parsed_ports || die_t L10N_ERR_INVALID_EXTRA_PORTS "Invalid EXTRA_PORTS: {1}" "$EXTRA_PORTS"

  case "$FIREWALL_MODE" in
    ufw)
      ufw default deny incoming
      ufw default allow outgoing
      ufw allow "${SSH_PORT}/tcp"
      for p in "${parsed_ports[@]}"; do
        ufw allow "$p"
      done
      ufw --force enable
      ok_t L10N_OK_UFW_ENABLED "UFW enabled (incoming denied, allowed {1}/tcp{2})." "$SSH_PORT" "${EXTRA_PORTS:+, $EXTRA_PORTS}"
      ;;
    nftables-setup)
      local tcp_ports=("$SSH_PORT")
      local udp_ports=()
      local -A seen_tcp=([$SSH_PORT]=1) seen_udp=()
      for p in "${parsed_ports[@]}"; do
        if [[ "$p" =~ ^([0-9]+)/(tcp|udp)$ ]]; then
          if [[ "${BASH_REMATCH[2]}" == "tcp" ]]; then
            [[ -n "${seen_tcp[${BASH_REMATCH[1]}]:-}" ]] || { tcp_ports+=("${BASH_REMATCH[1]}"); seen_tcp[${BASH_REMATCH[1]}]=1; }
          else
            [[ -n "${seen_udp[${BASH_REMATCH[1]}]:-}" ]] || { udp_ports+=("${BASH_REMATCH[1]}"); seen_udp[${BASH_REMATCH[1]}]=1; }
          fi
        elif [[ "$p" =~ ^([0-9]+)$ ]]; then
          [[ -n "${seen_tcp[${BASH_REMATCH[1]}]:-}" ]] || { tcp_ports+=("${BASH_REMATCH[1]}"); seen_tcp[${BASH_REMATCH[1]}]=1; }
        else
          die_t L10N_ERR_NFT_PORT_SYNTAX "Unsupported port syntax for nftables: '{1}' (expected e.g. 80/tcp or 51820/udp)" "$p"
        fi
      done

      local tcp_list udp_list
      tcp_list="$(IFS=', '; echo "${tcp_ports[*]}")"
      udp_list="$(IFS=', '; echo "${udp_ports[*]}")"

      [[ -f /etc/nftables.conf ]] && cp -a /etc/nftables.conf "/etc/nftables.conf.bak.$(date +%s)"
      {
        echo "#!/usr/sbin/nft -f"
        echo "# Managed by vps-setup.sh"
        echo "flush ruleset"
        echo ""
        echo "table inet filter {"
        echo "  chain input {"
        echo "    type filter hook input priority filter; policy drop;"
        echo "    iifname \"lo\" accept"
        echo "    ct state invalid drop"
        echo "    ct state established,related accept"
        echo "    ip protocol icmp accept"
        echo "    ip6 nexthdr icmpv6 accept"
        echo "    tcp dport { ${tcp_list} } accept"
        if [[ -n "$udp_list" ]]; then
          echo "    udp dport { ${udp_list} } accept"
        fi
        echo "  }"
        echo "  chain forward {"
        echo "    type filter hook forward priority filter; policy drop;"
        echo "  }"
        echo "  chain output {"
        echo "    type filter hook output priority filter; policy accept;"
        echo "  }"
        echo "}"
      } > /etc/nftables.conf

      nft -c -f /etc/nftables.conf
      systemctl enable --now nftables
      systemctl reload-or-restart nftables
      ok_t L10N_OK_NFT_ENABLED "Configured and enabled nftables (/etc/nftables.conf)."
      ;;
    nftables-keep)
      info_t L10N_INFO_NFT_KEEP "Leaving existing nftables configuration untouched."
      ;;
    none)
      info_t L10N_INFO_FW_SKIP "Skipping firewall setup."
      ;;
  esac
}

configure_fail2ban() {
  [[ "$ENABLE_FAIL2BAN" == "true" ]] || return 0
  step_t L10N_STEP_FAIL2BAN "Fail2ban"

  local banaction_cfg=""
  if [[ "$FIREWALL_MODE" == "nftables-setup" || "$FIREWALL_MODE" == "nftables-keep" ]]; then
    banaction_cfg=$'banaction = nftables[type=multiport]\nbanaction_allports = nftables[type=allports]'
  fi

  local jail_bak=""
  if [[ -f /etc/fail2ban/jail.local ]]; then
    jail_bak="/etc/fail2ban/jail.local.bak.$(date +%s)"
    cp -a /etc/fail2ban/jail.local "$jail_bak"
  fi

  cat <<EOF > /etc/fail2ban/jail.local
# Managed by vps-setup.sh
[DEFAULT]
bantime = ${FAIL2BAN_BANTIME}
findtime = ${FAIL2BAN_FINDTIME}
maxretry = ${FAIL2BAN_MAXRETRY}
backend = systemd
${banaction_cfg}

[sshd]
enabled = true
port = ${SSH_PORT}
EOF

  if command -v fail2ban-client >/dev/null 2>&1; then
    local f2b_test_out=""
    if ! f2b_test_out="$(fail2ban-client -t 2>&1)"; then
      if [[ -n "$jail_bak" ]]; then
        mv -f "$jail_bak" /etc/fail2ban/jail.local
      else
        rm -f /etc/fail2ban/jail.local
      fi
      printf '%s\n' "$f2b_test_out" >&2
      die_t L10N_ERR_F2B_VALIDATION "Generated /etc/fail2ban/jail.local failed fail2ban-client -t validation."
    fi
  fi
  [[ -n "$jail_bak" ]] && rm -f "$jail_bak"

  systemctl enable --now fail2ban
  systemctl restart fail2ban
  ok_t L10N_OK_F2B_ENABLED "Fail2ban enabled for SSH port {1}." "$SSH_PORT"
}

configure_unattended_upgrades() {
  [[ "$ENABLE_UNATTENDED" == "true" ]] || return 0
  step_t L10N_STEP_UNATTENDED "Unattended Upgrades"

  cat <<'EOF' > /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::MaxSize "100";
APT::Periodic::Unattended-Upgrade "1";
EOF

  {
    echo "// Managed by vps-setup.sh"
    if [[ "$UNATTENDED_ALL_ORIGINS" == "true" ]]; then
      echo 'Unattended-Upgrade::Origins-Pattern {'
      echo '        "origin=*";'
      echo '};'
    fi
    echo 'Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";'
    echo 'Unattended-Upgrade::Remove-New-Unused-Dependencies "true";'
    echo 'Unattended-Upgrade::Remove-Unused-Dependencies "true";'
    echo "Unattended-Upgrade::Automatic-Reboot \"${UNATTENDED_AUTO_REBOOT}\";"
    echo "Unattended-Upgrade::Automatic-Reboot-WithUsers \"${UNATTENDED_REBOOT_WITH_USERS}\";"
    echo "Unattended-Upgrade::Automatic-Reboot-Time \"${LOCAL_REBOOT_HHMM}\";"
  } > /etc/apt/apt.conf.d/99unattended-upgrades-custom

  local timer_tz_suffix=""
  if [[ "$UPGRADE_WINDOW_TZ" != "local" ]]; then
    timer_tz_suffix=" ${UPGRADE_WINDOW_TZ}"
  fi

  mkdir -p /etc/systemd/system/apt-daily.timer.d /etc/systemd/system/apt-daily-upgrade.timer.d /etc/systemd/system/apt-daily-upgrade.service.d
  cat <<EOF > /etc/systemd/system/apt-daily.timer.d/override.conf
[Timer]
OnCalendar=
OnCalendar=*-*-* ${REF_DAILY_HHMM}${timer_tz_suffix}
RandomizedDelaySec=30m
EOF

  cat <<EOF > /etc/systemd/system/apt-daily-upgrade.timer.d/override.conf
[Timer]
OnCalendar=
OnCalendar=*-*-* ${UPGRADE_START_HHMM}${timer_tz_suffix}
RandomizedDelaySec=${UPGRADE_RANDOM_MIN}m
EOF

  local reboot_svc_override="/etc/systemd/system/apt-daily-upgrade.service.d/override.conf"
  if [[ "$UNATTENDED_AUTO_REBOOT" == "true" && "$UPGRADE_WINDOW_TZ" != "local" && "$UPGRADE_WINDOW_TZ" != "$TIMEZONE" ]]; then
    # Shutdown accepts local wall time only, so refresh Automatic-Reboot-Time before each run to follow DST.
    cat <<EOF > "$reboot_svc_override"
[Service]
ExecStartPre=-/bin/sh -c 'tz="${UPGRADE_WINDOW_TZ}"; ref="${REBOOT_HHMM}"; now=\$(TZ="\$tz" date +%%s) && d=\$(TZ="\$tz" date +%%F) && tgt=\$(TZ="\$tz" date -d "\$d \$ref" +%%s) && { [ "\$now" -lt "\$tgt" ] || tgt=\$(TZ="\$tz" date -d "\$d \$ref +1 day" +%%s); } && hm=\$(date -d "@\$tgt" +%%H:%%M) && [ -n "\$hm" ] && sed -i "/^Unattended-Upgrade::Automatic-Reboot-Time /s/[0-9][0-9]:[0-9][0-9]/\$hm/" /etc/apt/apt.conf.d/99unattended-upgrades-custom'
EOF
  else
    rm -f "$reboot_svc_override"
  fi

  systemctl daemon-reload
  systemctl enable --now apt-daily.timer apt-daily-upgrade.timer unattended-upgrades
  if [[ "$UPGRADE_WINDOW_TZ" != "local" && "$UPGRADE_WINDOW_TZ" != "$TIMEZONE" ]]; then
    ok_t L10N_OK_UNATTENDED_SCHEDULED_TZ "Unattended upgrades scheduled at {1} (+{2}m) {3} (currently {4} {5}; reboot={6} at {7} {3} / currently {8} {5})." "$UPGRADE_START_HHMM" "$UPGRADE_RANDOM_MIN" "$UPGRADE_WINDOW_TZ" "$LOCAL_UPGRADE_HHMM" "$TIMEZONE" "$UNATTENDED_AUTO_REBOOT" "$REBOOT_HHMM" "$LOCAL_REBOOT_HHMM"
  else
    ok_t L10N_OK_UNATTENDED_SCHEDULED "Unattended upgrades scheduled at {1} (+{2}m) {3} (reboot={4} at {5})." "$UPGRADE_START_HHMM" "$UPGRADE_RANDOM_MIN" "$TIMEZONE" "$UNATTENDED_AUTO_REBOOT" "$REBOOT_HHMM"
  fi
}

apply_and_verify_sysctl() {
  local cfg="$1"
  shift
  local sysctl_out="" had_err=0

  if ! sysctl_out="$(sysctl -p "$cfg" 2>&1)"; then
    warn_t L10N_WARN_SYSCTL_P_FAILED "sysctl -p {1} failed:" "$cfg"
    [[ -n "$sysctl_out" ]] && printf '%s\n' "$sysctl_out" >&2
    had_err=1
  fi

  if ! sysctl_out="$(sysctl -e --system 2>&1)"; then
    warn_t L10N_WARN_SYSCTL_SYSTEM_FAILED "sysctl -e --system reported errors:"
    [[ -n "$sysctl_out" ]] && printf '%s\n' "$sysctl_out" >&2
    had_err=1
  fi

  local pair key expected actual
  for pair in "$@"; do
    key="${pair%%=*}"
    expected="${pair#*=}"
    if ! actual="$(sysctl -n "$key" 2>&1)"; then
      warn_t L10N_WARN_SYSCTL_READ_FAILED "Failed to read sysctl key '{1}': {2}" "$key" "$actual"
      had_err=1
      continue
    fi
    # sysctl separates multi-value fields (e.g. tcp_rmem) with tabs; normalize whitespace.
    actual="$(printf '%s' "$actual" | tr -s '[:space:]' ' ' | sed 's/^ //; s/ $//')"
    if [[ "$actual" != "$expected" ]]; then
      warn_t L10N_WARN_SYSCTL_MISMATCH "Sysctl key '{1}' rejected or overridden (expected '{2}', got '{3}')" "$key" "$expected" "$actual"
      had_err=1
    fi
  done

  return "$had_err"
}

configure_network_tuning() {
  [[ "$ENABLE_BBR" == "true" || "$ENABLE_TCP_BUFFER_TUNING" == "true" ]] || return 0
  step_t L10N_STEP_NET_TUNING "Network Tuning (BBR & RAM-Tiered TCP Buffers)"

  local cfg="/etc/sysctl.d/99-zzz-network-tuning.conf"
  rm -f /etc/sysctl.d/99-bbr.conf
  local -a expected_sysctl=()
  {
    echo "# Managed by vps-setup.sh (99-zzz-* ensures precedence over provider sysctl files)"
    if [[ "$ENABLE_BBR" == "true" ]]; then
      modprobe tcp_bbr 2>/dev/null || true
      if grep -qw bbr /proc/sys/net/ipv4/tcp_available_congestion_control 2>/dev/null; then
        echo "net.core.default_qdisc = ${QDISC_ALGO}"
        echo "net.ipv4.tcp_congestion_control = bbr"
        expected_sysctl+=("net.core.default_qdisc=${QDISC_ALGO}" "net.ipv4.tcp_congestion_control=bbr")
      else
        warn_t L10N_WARN_NO_BBR "Kernel does not report tcp_bbr support (container/custom kernel?). Skipping BBR."
      fi
    fi

    if [[ "$ENABLE_TCP_BUFFER_TUNING" == "true" ]]; then
      local mem_mib tier rmem_max wmem_max buf_def tcp_rmem tcp_wmem conntrack_max
      mem_mib="$(detect_mem_total_mib)"
      IFS=$'\t' read -r tier rmem_max wmem_max buf_def tcp_rmem tcp_wmem conntrack_max <<< "$(get_tcp_buffer_tier_values "$mem_mib")"
      info_t L10N_INFO_TCP_TIER "Detected {1} MiB RAM -> applying '{2}' TCP buffer tier (rmem_max={3}, wmem_max={4})." "$mem_mib" "$tier" "$rmem_max" "$wmem_max"
      echo "net.core.rmem_default = ${buf_def}"
      echo "net.core.wmem_default = ${buf_def}"
      echo "net.core.rmem_max = ${rmem_max}"
      echo "net.core.wmem_max = ${wmem_max}"
      echo "net.ipv4.tcp_rmem = ${tcp_rmem}"
      echo "net.ipv4.tcp_wmem = ${tcp_wmem}"
      echo "net.ipv4.tcp_mtu_probing = 1"
      # nf_conntrack may not be loaded at boot before nftables; keep '-' prefix for systemd-sysctl.
      echo "-net.netfilter.nf_conntrack_max = ${conntrack_max}"
      expected_sysctl+=(
        "net.core.rmem_default=${buf_def}"
        "net.core.wmem_default=${buf_def}"
        "net.core.rmem_max=${rmem_max}"
        "net.core.wmem_max=${wmem_max}"
        "net.ipv4.tcp_rmem=${tcp_rmem}"
        "net.ipv4.tcp_wmem=${tcp_wmem}"
        "net.ipv4.tcp_mtu_probing=1"
      )
      if [[ -e /proc/sys/net/netfilter/nf_conntrack_max ]]; then
        expected_sysctl+=("net.netfilter.nf_conntrack_max=${conntrack_max}")
      fi
    fi
  } > "$cfg"

  if (( ${#expected_sysctl[@]} == 0 )); then
    info_t L10N_INFO_NET_NONE "No applicable network tuning keys written to {1}." "$cfg"
    return 0
  fi

  if apply_and_verify_sysctl "$cfg" "${expected_sysctl[@]}"; then
    local eff_cc eff_qdisc
    eff_cc="$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo n/a)"
    eff_qdisc="$(sysctl -n net.core.default_qdisc 2>/dev/null || echo n/a)"
    ok_t L10N_OK_NET_TUNED "Network tuning applied ({1}; cc={2}, qdisc={3})." "$cfg" "$eff_cc" "$eff_qdisc"
  else
    warn_t L10N_WARN_NET_PARTIAL "Network tuning in {1} was rejected or only partially applied (see warnings above)." "$cfg"
  fi
}

configure_zram() {
  should_enable_zram || return 0
  step_t L10N_STEP_ZRAM "Zram Compressed RAM Swap"

  if ! modprobe zram 2>/dev/null; then
    warn_t L10N_WARN_NO_ZRAM_MOD "Kernel does not support zram module; skipping zram."
    return 0
  fi

  local zram_mib max_mib
  zram_mib="$(compute_zram_size_mib)"
  max_mib="$(parse_size_to_mib "$ZRAM_MAX_SIZE")"

  if dpkg -s systemd-zram-generator >/dev/null 2>&1; then
    local size_expr
    if (( max_mib > 0 )); then
      size_expr="min(ram * ${ZRAM_FRACTION}, ${max_mib})"
    else
      size_expr="ram * ${ZRAM_FRACTION}"
    fi
    cat <<EOF > /etc/systemd/zram-generator.conf
# Managed by vps-setup.sh (Fedora-style zram-generator config)
[zram0]
zram-size = ${size_expr}
compression-algorithm = ${ZRAM_ALGO}
swap-priority = 100
EOF
    # Stop existing zram swap first in case package postinst or an earlier run activated default ram/2
    systemctl stop dev-zram0.swap systemd-zram-setup@zram0.service 2>/dev/null || true
    swapoff /dev/zram0 2>/dev/null || true
    systemctl daemon-reload
    systemctl start dev-zram0.swap
    ok_t L10N_OK_ZRAM_GENERATOR "Enabled zram via systemd-zram-generator ({1} -> ~{2} MiB, algo={3}, priority=100)." "$size_expr" "$zram_mib" "$ZRAM_ALGO"
  elif dpkg -s zram-tools >/dev/null 2>&1; then
    rm -f /etc/systemd/zram-generator.conf
    cat <<EOF > /etc/default/zramswap
# Managed by vps-setup.sh
ALGO=${ZRAM_ALGO}
SIZE=${zram_mib}
PRIORITY=100
EOF
    systemctl enable --now zramswap.service
    systemctl restart zramswap.service
    ok_t L10N_OK_ZRAM_TOOLS "Enabled zram via zram-tools ({1} MiB, algo={2}, priority=100)." "$zram_mib" "$ZRAM_ALGO"
  else
    warn_t L10N_WARN_NO_ZRAM_PKG "Neither systemd-zram-generator nor zram-tools is installed; skipping zram."
  fi
}

configure_swap() {
  local target_mib
  target_mib="$(parse_size_to_mib "$SWAP_SIZE")"

  if (( target_mib > 0 )); then
    step_t L10N_STEP_SWAP "Swap ({1})" "$SWAP_SIZE"
    if is_container; then
      warn_t L10N_WARN_SWAP_CONTAINER "Running inside a container; skipping swapfile creation (host manages swap)."
    else
      local current_bytes current_mib
      current_bytes="$(swapon --show=SIZE --bytes --noheadings 2>/dev/null | awk '!/\/dev\/zram/ {s+=$1} END{print s+0}')"
      current_mib=$(( current_bytes / 1024 / 1024 ))

      if (( current_mib >= target_mib - 32 )); then
        info_t L10N_INFO_SWAP_MEETS_TARGET "Existing active disk swap ({1} MiB) already meets target ({2} MiB)." "$current_mib" "$target_mib"
      elif [[ -f /swapfile ]] && swapon --show=NAME --noheadings | grep -x '/swapfile' >/dev/null; then
        warn_t L10N_WARN_SWAPFILE_ACTIVE "/swapfile is already active ({1} MiB total). Leaving existing swapfile untouched." "$current_mib"
      else
        local add_mib=$(( target_mib - current_mib ))
        local swap_path="/swapfile"
        if [[ -e "$swap_path" ]]; then
          swap_path="/swapfile-extra"
        fi
        info_t L10N_INFO_SWAP_CREATING "Creating {1} MiB swapfile at {2}..." "$add_mib" "$swap_path"
        fallocate -l "${add_mib}M" "$swap_path" 2>/dev/null || dd if=/dev/zero of="$swap_path" bs=1M count="$add_mib" status=progress
        chmod 600 "$swap_path"
        mkswap "$swap_path" >/dev/null
        swapon "$swap_path"
        if ! grep -qE "^${swap_path}[[:space:]]" /etc/fstab; then
          printf '%s none swap sw 0 0\n' "$swap_path" >> /etc/fstab
        fi
        local total_swap_mib
        total_swap_mib="$(free -m | awk '/^Swap:/{print $2}')"
        ok_t L10N_OK_SWAP_ENABLED "Swap enabled at {1} (total active swap now {2} MiB)." "$swap_path" "$total_swap_mib"
      fi
    fi
  fi

  local zram_active="false"
  if swapon --show=NAME --noheadings 2>/dev/null | grep '/dev/zram' >/dev/null; then
    zram_active="true"
  fi
  local eff_swappiness
  eff_swappiness="$(resolve_swappiness "$zram_active")"

  if [[ -n "$eff_swappiness" && "$eff_swappiness" != "default" ]] || [[ "$zram_active" == "true" ]]; then
    rm -f /etc/sysctl.d/99-swappiness.conf
    local mem_cfg="/etc/sysctl.d/99-zzz-memory-tuning.conf"
    local -a mem_expected=()
    {
      echo "# Managed by vps-setup.sh"
      if [[ -n "$eff_swappiness" && "$eff_swappiness" != "default" ]]; then
        echo "vm.swappiness = ${eff_swappiness}"
        mem_expected+=("vm.swappiness=${eff_swappiness}")
      fi
      if [[ "$zram_active" == "true" ]]; then
        echo "vm.page-cluster = 0"
        mem_expected+=("vm.page-cluster=0")
      fi
    } > "$mem_cfg"
    if apply_and_verify_sysctl "$mem_cfg" "${mem_expected[@]}"; then
      local cur_swappiness cur_page_cluster
      cur_swappiness="$(sysctl -n vm.swappiness 2>/dev/null || echo "$eff_swappiness")"
      cur_page_cluster="$(sysctl -n vm.page-cluster 2>/dev/null || echo n/a)"
      ok_t L10N_OK_MEM_TUNED "Memory tuning applied (swappiness={1}, page-cluster={2})." "$cur_swappiness" "$cur_page_cluster"
    else
      warn_t L10N_WARN_MEM_PARTIAL "Memory tuning in {1} was rejected or only partially applied (see warnings above)." "$mem_cfg"
    fi
  fi
}

configure_log_limits() {
  [[ "$ENABLE_LOG_LIMITS" == "true" ]] || return 0
  step_t L10N_STEP_LOGS "Journald & /var/log Protection"

  mkdir -p /etc/systemd/journald.conf.d
  cat <<EOF > /etc/systemd/journald.conf.d/99-vps-limit.conf
# Managed by vps-setup.sh
[Journal]
SystemMaxUse=${JOURNAL_MAX_USE}
SystemMaxFileSize=${JOURNAL_MAX_FILE}
RuntimeMaxUse=${JOURNAL_RUNTIME_MAX}
RuntimeMaxFileSize=5M
MaxRetentionSec=14day
Compress=yes
EOF
  systemctl restart systemd-journald
  journalctl --vacuum-size="${JOURNAL_MAX_USE}" >/dev/null 2>&1 || true

  if [[ -f /etc/logrotate.conf ]]; then
    sed -i 's/^#compress$/compress/' /etc/logrotate.conf
  fi
  for lr in /etc/logrotate.d/btmp /etc/logrotate.d/wtmp; do
    if [[ -f "$lr" ]] && ! grep -qE '^\s*maxsize\s' "$lr"; then
      cp -a "$lr" "${lr}.bak"
      sed -i '/^[[:space:]]*rotate[[:space:]]/i \    maxsize 10M' "$lr"
      if command -v logrotate >/dev/null 2>&1 && ! logrotate -d /etc/logrotate.conf >/dev/null 2>&1; then
        warn_t L10N_WARN_LOGROTATE_RESTORE "logrotate validation failed after editing {1}; restoring backup." "$lr"
        mv -f "${lr}.bak" "$lr"
      else
        rm -f "${lr}.bak"
      fi
    fi
  done

  apt-get clean
  ok_t L10N_OK_LOGS_CAPPED "Capped systemd-journald ({1}, file={2}, runtime={3}) and tightened log rotation." "$JOURNAL_MAX_USE" "$JOURNAL_MAX_FILE" "$JOURNAL_RUNTIME_MAX"
}

configure_time_ntp() {
  step_t L10N_STEP_TIME "Timezone & NTP"
  timedatectl set-timezone "$TIMEZONE"
  if [[ "$ENABLE_NTP" == "true" ]]; then
    if is_container; then
      info_t L10N_INFO_NTP_CONTAINER "Running inside a container; clock sync is managed by the host."
    elif systemctl is-active --quiet chrony 2>/dev/null || dpkg -s chrony >/dev/null 2>&1; then
      systemctl enable --now chrony
      info_t L10N_INFO_NTP_CHRONY "Preserving active chrony NTP service."
    else
      timedatectl set-ntp true
      systemctl enable --now systemd-timesyncd
    fi
  fi
  ok_t L10N_OK_TIME_SET "Timezone set to {1}; NTP={2}." "$TIMEZONE" "$ENABLE_NTP"
}

save_non_secret_config() {
  local dest="$1"
  local -a keys=(
    ADMIN_USER ADMIN_NOPASSWD CREATE_DEPLOY_USER DEPLOY_USER DEPLOY_SHARE_SSH_KEY
    SSH_PORT DISABLE_PASSWORD_AUTH PERMIT_ROOT_LOGIN FIREWALL_MODE EXTRA_PORTS
    ENABLE_FAIL2BAN FAIL2BAN_BANTIME FAIL2BAN_FINDTIME FAIL2BAN_MAXRETRY
    RUN_APT_UPGRADE APT_DIST_UPGRADE INSTALL_COMMON_TOOLS COMMON_TOOLS
    INSTALL_FETCH_TOOL ENABLE_UNATTENDED UNATTENDED_ALL_ORIGINS
    UNATTENDED_AUTO_REBOOT UNATTENDED_REBOOT_WITH_USERS UPGRADE_WINDOW_TZ
    UPGRADE_START_HHMM UPGRADE_RANDOM_MIN REBOOT_HHMM ENABLE_BBR QDISC_ALGO
    ENABLE_TCP_BUFFER_TUNING SWAP_SIZE SWAPPINESS ENABLE_ZRAM ZRAM_FRACTION
    ZRAM_MAX_SIZE ZRAM_ALGO ENABLE_LOG_LIMITS JOURNAL_MAX_USE JOURNAL_MAX_FILE
    JOURNAL_RUNTIME_MAX TIMEZONE AUTO_TIMEZONE ENABLE_NTP UI_LANG LANG_BASE_URL PRESET_BASE_URL
  )
  (
    umask 077
    {
      echo "# Generated by vps-setup.sh (passwords intentionally omitted)"
      local k
      for k in "${keys[@]}"; do
        printf '%s=%q\n' "$k" "${!k}"
      done
    } > "$dest"
  )
  chmod 600 "$dest"
  ok_t L10N_OK_SAVED_CONFIG "Saved reusable config to {1}" "$dest"
}

print_plan_summary() {
  local mem_mib tier zram_will_enable="false" zram_mib zram_desc eff_swap
  mem_mib="$(detect_mem_total_mib)"
  IFS=$'\t' read -r tier _ <<< "$(get_tcp_buffer_tier_values "$mem_mib")"

  local w_set="" w_unchanged="" w_locked="" w_disabled="" w_enabled="" w_auto="" w_default=""
  fmt_msg w_set       L10N_STATE_SET       "set"
  fmt_msg w_unchanged L10N_STATE_UNCHANGED "unchanged/disabled"
  fmt_msg w_locked    L10N_STATE_LOCKED    "locked"
  fmt_msg w_disabled  L10N_STATE_DISABLED  "disabled"
  fmt_msg w_enabled   L10N_STATE_ENABLED   "enabled"
  fmt_msg w_auto      L10N_STATE_AUTO      "auto"
  fmt_msg w_default   L10N_STATE_DEFAULT   "default"

  if should_enable_zram; then
    zram_will_enable="true"
    zram_mib="$(compute_zram_size_mib)"
    fmt_msg zram_desc L10N_SUM_ZRAM_ON "{1} ({2}: {3} MiB = min({4} MiB * {5}, {6}), {7})" "$w_enabled" "$ENABLE_ZRAM" "$zram_mib" "$mem_mib" "$ZRAM_FRACTION" "$ZRAM_MAX_SIZE" "$ZRAM_ALGO"
  else
    fmt_msg zram_desc L10N_SUM_ZRAM_OFF "{1} ({2})" "$w_disabled" "$ENABLE_ZRAM"
  fi
  eff_swap="$(resolve_swappiness "$zram_will_enable")"

  local admin_pw_state="$w_unchanged"
  [[ -n "$ADMIN_PASSWORD" ]] && admin_pw_state="$w_set"

  local deploy_desc="$w_disabled" deploy_pw_state="$w_locked"
  [[ -n "$DEPLOY_PASSWORD" ]] && deploy_pw_state="$w_set"
  if [[ "$CREATE_DEPLOY_USER" == "true" ]]; then
    fmt_msg deploy_desc L10N_SUM_DEPLOY_DETAIL "{1} (share_key={2}, password={3})" "$DEPLOY_USER" "$DEPLOY_SHARE_SSH_KEY" "$deploy_pw_state"
  fi

  local ssh_pw_state="$w_enabled"
  [[ "$DISABLE_PASSWORD_AUTH" == "true" ]] && ssh_pw_state="$w_disabled"

  local fw_extra=""
  [[ -n "$EXTRA_PORTS" ]] && fmt_msg fw_extra L10N_SUM_FW_EXTRA " (extra ports: {1})" "$EXTRA_PORTS"

  local tools_desc="$w_disabled"
  [[ "$INSTALL_COMMON_TOOLS" == "true" ]] && tools_desc="${COMMON_TOOLS}"

  local fetch_desc="$w_disabled"
  [[ "$INSTALL_FETCH_TOOL" == "true" ]] && fmt_msg fetch_desc L10N_SUM_FETCH_AUTO "auto (fastfetch -> neofetch after apt update)"

  local ua_extra=""
  [[ "$ENABLE_UNATTENDED" == "true" ]] && fmt_msg ua_extra L10N_SUM_UA_EXTRA " (all_origins={1}, auto_reboot={2})" "$UNATTENDED_ALL_ORIGINS" "$UNATTENDED_AUTO_REBOOT"

  local tcp_extra=""
  [[ "$ENABLE_TCP_BUFFER_TUNING" == "true" ]] && fmt_msg tcp_extra L10N_SUM_TCP_TIER " ({1} MiB -> {2} tier)" "$mem_mib" "$tier"

  local swap_auto_tag="" zram_pc_tag=""
  [[ "$SWAPPINESS" == "auto" ]] && swap_auto_tag=" ($w_auto)"
  [[ "$zram_will_enable" == "true" ]] && zram_pc_tag=", page-cluster=0"

  local log_extra=""
  [[ "$ENABLE_LOG_LIMITS" == "true" ]] && fmt_msg log_extra L10N_SUM_LOG_DETAIL " (journald max={1}, file={2}, runtime={3})" "$JOURNAL_MAX_USE" "$JOURNAL_MAX_FILE" "$JOURNAL_RUNTIME_MAX"

  step_t L10N_STEP_SUMMARY "Resolved Configuration"
  echo_t L10N_SUM_ADMIN       "  Admin user         : {1} (nopasswd={2}, password={3})" "$ADMIN_USER" "$ADMIN_NOPASSWD" "$admin_pw_state"
  echo_t L10N_SUM_DEPLOY      "  Deploy user        : {1}" "$deploy_desc"
  echo_t L10N_SUM_SSH         "  SSH                : port={1}, password_auth={2}, root_login={3}" "$SSH_PORT" "$ssh_pw_state" "$PERMIT_ROOT_LOGIN"
  echo_t L10N_SUM_FIREWALL    "  Firewall           : {1}{2}" "$FIREWALL_MODE" "$fw_extra"
  echo_t L10N_SUM_FAIL2BAN    "  Fail2ban           : {1} (bantime={2}, findtime={3}, maxretry={4})" "$ENABLE_FAIL2BAN" "$FAIL2BAN_BANTIME" "$FAIL2BAN_FINDTIME" "$FAIL2BAN_MAXRETRY"
  echo_t L10N_SUM_APT         "  APT Upgrade now    : {1} (dist_upgrade={2})" "$RUN_APT_UPGRADE" "$APT_DIST_UPGRADE"
  echo_t L10N_SUM_TOOLS       "  Common tools       : {1}" "$tools_desc"
  echo_t L10N_SUM_FETCH       "  System fetch tool  : {1}" "$fetch_desc"
  echo_t L10N_SUM_UNATTENDED  "  Unattended upgrades: {1}{2}" "$ENABLE_UNATTENDED" "$ua_extra"
  if [[ "$ENABLE_UNATTENDED" == "true" ]]; then
    echo_t L10N_SUM_UPGRADE_WIN "  Upgrade window     : {1} (+{2}m) {3} -> currently {4} {5} (reboot at {6} {3} / currently {7} {5})" "$UPGRADE_START_HHMM" "$UPGRADE_RANDOM_MIN" "$UPGRADE_WINDOW_TZ" "$LOCAL_UPGRADE_HHMM" "$TIMEZONE" "$REBOOT_HHMM" "$LOCAL_REBOOT_HHMM"
  fi
  echo_t L10N_SUM_NETWORK     "  Network tuning     : BBR={1} (qdisc={2}), TCP_buffers={3}{4}" "$ENABLE_BBR" "$QDISC_ALGO" "$ENABLE_TCP_BUFFER_TUNING" "$tcp_extra"
  echo_t L10N_SUM_SWAP        "  Swap & Memory      : swap={1}, swappiness={2}{3}, zram={4}{5}" "$SWAP_SIZE" "${eff_swap:-$w_default}" "$swap_auto_tag" "$zram_desc" "$zram_pc_tag"
  echo_t L10N_SUM_LOGS        "  Log protection     : {1}{2}" "$ENABLE_LOG_LIMITS" "$log_extra"
  echo_t L10N_SUM_TIME        "  Timezone / NTP     : {1} / {2}" "$TIMEZONE" "$ENABLE_NTP"
}

print_verification_report() {
  step_t L10N_STEP_VERIFY "Post-Setup Verification"
  echo_t L10N_VER_USERS "--- Users ---"
  id "$ADMIN_USER"
  [[ "$CREATE_DEPLOY_USER" == "true" ]] && id "$DEPLOY_USER"
  echo_t L10N_VER_SSH "--- SSH Effective ---"
  sshd -T | grep -E '^(port|permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|authenticationmethods)' || true
  echo_t L10N_VER_FIREWALL "--- Firewall ---"
  case "$FIREWALL_MODE" in
    ufw) ufw status ;;
    nftables-setup|nftables-keep) nft list ruleset 2>/dev/null | head -n 30 || true ;;
    none) echo_t L10N_VER_FW_NONE "Firewall not managed." ;;
  esac
  if [[ "$ENABLE_FAIL2BAN" == "true" ]]; then
    echo_t L10N_VER_FAIL2BAN "--- Fail2ban ---"
    fail2ban-client status sshd || true
  fi
  echo_t L10N_VER_SWAP "--- Swap, Zram & Kernel Tuning ---"
  free -h
  swapon --show || true
  sysctl net.ipv4.tcp_congestion_control net.core.default_qdisc net.core.rmem_max net.core.wmem_max vm.swappiness vm.page-cluster 2>/dev/null || true
  if [[ "$ENABLE_LOG_LIMITS" == "true" ]]; then
    echo_t L10N_VER_JOURNAL "--- Journal Disk Usage ---"
    journalctl --disk-usage || true
  fi
  echo_t L10N_VER_TIME "--- Time ---"
  timedatectl
  if [[ "$ENABLE_UNATTENDED" == "true" ]]; then
    echo_t L10N_VER_TIMERS "--- Upgrade Timers ---"
    systemctl list-timers apt-daily.timer apt-daily-upgrade.timer --no-pager || true
  fi
}

# ==============================================================================
# Main
# ==============================================================================
main() {
  parse_args "$@"
  validate_bool_settings
  [[ -z "$ADMIN_USER" ]] && ADMIN_USER="$(detect_default_admin_user)"

  if [[ "$DRY_RUN" != "true" && "$EUID" -ne 0 ]]; then
    die_t L10N_ERR_NEED_ROOT "Please run as root (e.g. sudo bash {1})." "$0"
  fi

  if [[ -n "$LOADED_PRESET_SOURCE" ]]; then
    info_t L10N_INFO_PRESET_LOADED "Loaded preset '{1}' ({2})." "$PRESET_NAME" "$LOADED_PRESET_SOURCE"
  fi

  if [[ "$INTERACTIVE" == "true" ]]; then
    [[ -t 0 ]] || die_t L10N_ERR_NEED_TTY "Interactive mode requires a TTY (pass --non-interactive for automated runs)."
    prompt_select_language
    gather_interactive_options
  else
    [[ -z "$UI_LANG" ]] && UI_LANG="en"
    if [[ "$PROMPT_ADMIN_PASSWORD" == "true" && -z "$ADMIN_PASSWORD" ]]; then
      if [[ -t 0 ]]; then
        prompt_admin_password_if_needed
      elif [[ "$DRY_RUN" != "true" ]]; then
        die_t L10N_ERR_NEED_TTY "Interactive mode requires a TTY (pass --non-interactive for automated runs)."
      fi
    fi
    discover_or_prompt_ssh_keys
    if [[ "$AUTO_TIMEZONE" == "true" ]]; then
      detect_timezone_by_ip || warn_t L10N_WARN_GEOIP_FALLBACK "Falling back to configured TIMEZONE={1}." "$TIMEZONE"
    fi
  fi

  validate_all_inputs
  print_plan_summary

  if [[ "$DRY_RUN" == "true" ]]; then
    info_t L10N_INFO_DRY_RUN "Dry-run enabled; no changes made."
    exit 0
  fi

  if [[ "$INTERACTIVE" == "true" ]]; then
    local proceed="true"
    prompt_bool_t proceed "true" L10N_PROMPT_PROCEED "Proceed with applying this configuration?"
    [[ "$proceed" == "true" ]] || { info_t L10N_INFO_ABORTED "Aborted."; exit 0; }
  fi

  install_packages
  configure_time_ntp
  configure_users
  configure_ssh_hardening
  configure_firewall
  configure_fail2ban
  configure_unattended_upgrades
  configure_network_tuning
  configure_zram
  configure_swap
  configure_log_limits

  if [[ -n "$SAVE_CONFIG_PATH" ]]; then
    save_non_secret_config "$SAVE_CONFIG_PATH"
  elif [[ "$INTERACTIVE" == "true" ]]; then
    local save_cfg="false"
    prompt_bool_t save_cfg "false" L10N_PROMPT_SAVE_CONFIG "Save these settings (without passwords) to /root/vps.conf for reuse?"
    [[ "$save_cfg" == "true" ]] && save_non_secret_config "/root/vps.conf"
  fi

  print_verification_report
  ok_t L10N_OK_COMPLETE "Server setup complete! Test logging in as '{1}' in a new terminal before closing this session." "$ADMIN_USER"
}

main "$@"
