#!/usr/bin/env bash
# wattun-manager: set up and run WatTunnel tunnels.
#   Kharej = the outside server (runs the real service, the tunnel SERVER)  -> set it up FIRST, it makes the token
#   Iran   = the inside server users connect to (the tunnel CLIENT)          -> paste the token there
# Each tunnel is /etc/wattun/NAME.yml + NAME.key (+ NAME.token on Kharej), run by systemd as wattun@NAME.
# Run it without arguments for the dashboard. Commands:
#   wattun-manager [new [kharej|iran]|kharej|iran|status|list|monitor|ports NAME|test NAME|
#                   speedtest NAME [MB]|logs NAME|token NAME|heal|update|rollback|help]
#   Censor starts blocking the tunnel (whitelist regime): blackout NAME [SNI] turns the resilience kit
#                   (fake-SNI desync + defaults) on with one command; profiles save/apply combinations.
#   Auto carrier (one token, Iran tests every connection type): auto-test NAME | auto-ip NAME IP |
#                   auto-watch NAME | auto-retest NAME   (the last two are run by systemd, not by hand)
#   CDN carriers (ws, wss, h2, h2c, grpc via Cloudflare; wattun >= 2.2.0): cdn-tune NAME [full]
#   Unattended (no tty, for scripts and test rigs): kharej --carrier C --name N --yes | iran --token T --map L:T --yes |
#                   cdn-tune NAME --yes | auto-test NAME --yes | delete NAME --yes | uninstall --yes   (see: help)
# Environment: WAT_NO_ANIM=1 (no animations), NO_COLOR=1 (no colours), WAT_REPO, WAT_PROXY, WAT_PREFIX (sandbox, see below),
#   WAT_SIG_PUB (another release-signing key), WAT_ALLOW_UNSIGNED_UPDATE=1 (run install.sh from main unverified; not recommended).
set -uo pipefail
shopt -s extglob

# Sandbox: WAT_PREFIX=NAME (default wattun) moves every path and unit name this manager creates or controls:
#   $CONF=/etc/NAME  $RUN=/run/NAME  $AUTO_RUN=/run/NAME-auto  $BIN=/opt/NAME/wattun  units NAME@X, NAME-heal, NAME-autowatch-X.
# WAT_CONF / WAT_BIN / WAT_RUN / WAT_AUTO_RUN still override single paths. The manager itself is then THIS script file.
WAT_PREFIX=${WAT_PREFIX:-wattun}
case "$WAT_PREFIX" in ''|-*|*[!A-Za-z0-9_.]*|*-) printf 'WAT_PREFIX must be letters, digits, "_" or "." and may contain "-" inside (got "%s").\n' "$WAT_PREFIX" >&2; exit 1 ;; esac
SANDBOX=0; [ "$WAT_PREFIX" = wattun ] || SANDBOX=1
CONF=${WAT_CONF:-/etc/$WAT_PREFIX}
RUN=${WAT_RUN:-/run/$WAT_PREFIX}
if [ "$SANDBOX" = 1 ]; then
  BIN=${WAT_BIN:-/opt/$WAT_PREFIX/wattun}
  MGR=$(readlink -f "$0" 2>/dev/null || echo "$0")
  # a sandbox must never share a path with the production install
  if [ "$CONF" = /etc/wattun ] || [ "$BIN" = /usr/local/bin/wattun ] || [ "$RUN" = /run/wattun ]; then
    printf 'Sandbox %s refuses to use a production path (CONF=%s BIN=%s RUN=%s MGR=%s).\n' "$WAT_PREFIX" "$CONF" "$BIN" "$RUN" "$MGR" >&2; exit 1
  fi
  export WAT_PREFIX
else
  BIN=${WAT_BIN:-/usr/local/bin/wattun}
  MGR=/usr/local/bin/wattun-manager
fi
REPO=${WAT_REPO:-JohnWatsoon/WatTunnel}
# Release-signing public key. update() checks the installer it runs as root against the release's signed SHA256SUMS.
# This PEM must stay byte-identical to SIG_PUB in install.sh; regenerate the key in both scripts together.
SIG_PUB=$(cat <<'PEM'
-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA0j+yK26CzKRD+am5rQZJ
v8zChkZ5HuwQ4uBtj2mKfFRG8mrj7XN3iW60QEj7Le/fAYtk4hHvqsxb6Xhxw303
+rFCBxKr+mwc3GOB/zVh/fzNqN2pXzKCT+mSKiaDfwUmCizKFNUUCCnhNVpEx9hl
A4B4n5iBgxW0G/ks4hOujx6teaKUN44+cZNgPshPSQ5KdiqQBi0rFCiSAKBCh1vL
j07u5S/mvU8L8u9M6sUzST0mXcGw9WKQmAiIOCqAwLiyV1RtDodgaCIxLPJ93Qo/
uK4DzYX3Ker8lW6MRKXgX3fAVXoyj/ZaE3oh1ZibVefAy6w7qB74JvQPv4nFvS/Y
VJXpxiHiqE/YMdHbS9eCQnqjHVKmGWvBVPo/IlUiJFbl8nIEFZVij32Cp8A4awO2
IORyD7iC8bA7AZHruzVfiUtrYA5XhBTRJplqws8kM0Ig4sLrws0HPOY4xOBRtSVh
vgY6Qw/EWglth/K24PEC8AiuJYIRRkn/Kq+SBIRu8qVrAgMBAAE=
-----END PUBLIC KEY-----
PEM
)
if [ -n "${WAT_SIG_PUB:-}" ]; then SIG_PUB=$(cat "$WAT_SIG_PUB"); fi
# Download helpers for update(): verify SHA256SUMS with the pinned key, then match one "<sha>  <name>" line.
sig_pub_file() { # write the pinned key to a private temp file and print its path
  local f
  f=$(mktemp /tmp/wattun-sigpub.XXXXXX) || return 1
  chmod 600 "$f" 2>/dev/null || { rm -f "$f"; return 1; }
  printf '%s\n' "$SIG_PUB" >"$f" || { rm -f "$f"; return 1; }
  printf '%s\n' "$f"
}
sums_verify() { # sums sig [pubfile]: the optional third argument lets the self-test use a throwaway key
  local pub rc
  command -v openssl >/dev/null 2>&1 || return 1
  if [ -n "${3:-}" ]; then pub=$3; else pub=$(sig_pub_file) || return 1; fi
  openssl dgst -sha256 -verify "$pub" -signature "$2" "$1" >/dev/null 2>&1; rc=$?
  [ -n "${3:-}" ] || rm -f "$pub"
  return "$rc"
}
sums_has() { grep -qx -- "$3  $2" "$1"; } # sums name sha
MGR_VERSION=2026112701   # YYYYMMDDNN; install.sh refuses to replace a newer manager with an older one
HEAL_UNIT=$WAT_PREFIX-heal
MCONF=$CONF/.manager.conf
self_cmd() { # the command to type to start this manager (user-facing hints)
  if [ "$SANDBOX" = 1 ]; then printf 'WAT_PREFIX=%s %s' "$WAT_PREFIX" "$MGR"; else printf wattun; fi
}
SELF=$(self_cmd)
# Environment for units that call this manager again (heal timer, watcher, retest): same sandbox, same paths.
unit_env_lines() { # Environment= lines for a service file
  [ "$SANDBOX" = 1 ] && printf 'Environment="WAT_PREFIX=%s"\n' "$WAT_PREFIX"
  [ -n "${WAT_CONF:-}" ] && printf 'Environment="WAT_CONF=%s"\n' "$WAT_CONF"
  [ -n "${WAT_BIN:-}" ] && printf 'Environment="WAT_BIN=%s"\n' "$WAT_BIN"
  [ -n "${WAT_RUN:-}" ] && printf 'Environment="WAT_RUN=%s"\n' "$WAT_RUN"
  [ -n "${WAT_AUTO_RUN:-}" ] && printf 'Environment="WAT_AUTO_RUN=%s"\n' "$WAT_AUTO_RUN"
  return 0
}
run_env_args() { # --setenv arguments for systemd-run, one per line (read with mapfile)
  printf '%s\n' "--setenv=WAT_CONF=$CONF" "--setenv=WAT_RUN=$RUN" "--setenv=WAT_PREFIX=$WAT_PREFIX"
  [ -n "${WAT_BIN:-}" ] || [ "$SANDBOX" = 1 ] && printf '%s\n' "--setenv=WAT_BIN=$BIN"
  [ -n "${WAT_AUTO_RUN:-}" ] && printf '%s\n' "--setenv=WAT_AUTO_RUN=$WAT_AUTO_RUN"
  return 0
}
# The systemd template unit NAME@.service. install.sh writes wattun@.service; in a sandbox the manager writes its own.
ensure_template() {
  [ "$SANDBOX" = 1 ] || return 0
  local f="/etc/systemd/system/$WAT_PREFIX@.service"
  [ -f "$f" ] && return 0
  cat >"$f" <<EOF
[Unit]
Description=WatTunnel %i (sandbox $WAT_PREFIX)
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=0

[Service]
Type=simple
ExecStart=$BIN -config $CONF/%i.yml
Restart=always
RestartSec=2
LimitNOFILE=1048576
LimitMEMLOCK=infinity
AmbientCapabilities=CAP_NET_RAW CAP_NET_ADMIN CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
EOF
  chmod 644 "$f" && systemctl daemon-reload && ok "Sandbox: created $f (ExecStart $BIN, configs in $CONF)"
}
LIB=${WAT_MANAGER_LIB:-0}

# Non-interactive mode: no tty, no stdin reads, no animation, no screen clearing, plain lines. Every prompt helper
# (ask, ask_ok, confirm, key_read, pick_carrier, port_editor, at_choose...) answers with its preset or default.
# On with --yes, or NONINTERACTIVE=1 in the environment, or when stdin is not a tty and a --flag is given.
NONINTERACTIVE=${NONINTERACTIVE:-0}
case "${1:-}" in kharej|iran|cdn-tune|auto-test|delete|uninstall|matrix|auto-retest|bond-retest|bond-add-rev|bond-del-rev|auto-prune|scepter)
  for _a in "$@"; do
    case "$_a" in --yes) NONINTERACTIVE=1 ;; --*) [ -t 0 ] || NONINTERACTIVE=1 ;; esac
  done ;;
esac
[ "$NONINTERACTIVE" = 1 ] || NONINTERACTIVE=0
# Answers set by flags (see ni_parse); empty = the wizard's own default
NI_CARRIER=''; NI_NAME=''; NI_LISTEN=''; NI_PATH=''; NI_ADDR=''; NI_SNI=''; NI_CDN=''; NI_PORTS=''; NI_MBPS=''; NI_FAKESNI=''; NI_FAKEMODE=''; NI_FAKETTL=''; NI_POOLROT=''; NI_POOLBYTES=''; NI_PRESET=''; NI_TEST=''; NI_ECH=''; NI_GOVERNOR=''; NI_DNSLISTEN=''; NI_SRCIP=''; NI_UDPDNS=''
NI_TOKEN=''; NI_MAP=''; NI_PICK=best; NI_SESSIONS=''; NI_YES=0; NI_POS=(); NI_EXTENDED=0
ERRN=0

case "$(locale charmap 2>/dev/null)" in UTF-8) ;; *) export LC_ALL=C.UTF-8 ;; esac

# ======================================================================================
#  Terminal UI core: colours, cursor, animations, prompts
# ======================================================================================
IS_TTY=0; [ -t 1 ] && IS_TTY=1
[ "$NONINTERACTIVE" = 1 ] && IS_TTY=0
USE_COLOR=0
if [ "${WAT_FORCE_COLOR:-0}" = 1 ] || { [ "$IS_TTY" = 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; }; then USE_COLOR=1; fi
[ "$NONINTERACTIVE" = 1 ] && USE_COLOR=0
NCOL=8
if [ "$USE_COLOR" = 1 ]; then
  NCOL=$(tput colors 2>/dev/null || echo 8)
  case "${TERM:-}" in *256color*) NCOL=256 ;; esac
  case "$NCOL" in ''|*[!0-9]*) NCOL=8 ;; esac
fi
if [ "$USE_COLOR" = 1 ]; then
  RST=$'\e[0m'; BOLD=$'\e[1m'; RED=$'\e[31m'; GRN=$'\e[32m'; YEL=$'\e[33m'
  if [ "$NCOL" -ge 256 ]; then CYN=$'\e[38;5;45m'; else CYN=$'\e[36m'; fi
  BLU=$'\e[34m'; GRY=$'\e[90m'
else
  RST=''; BOLD=''; RED=''; GRN=''; YEL=''; CYN=''; BLU=''; GRY=''
fi

conf_get() { local v; v=$(sed -n "s/^$1=//p" "$MCONF" 2>/dev/null | tail -1); echo "${v:-$2}"; }
conf_set() {
  mkdir -p "$CONF"; touch "$MCONF"; chmod 600 "$MCONF"
  sed -i "/^$1=/d" "$MCONF"; echo "$1=$2" >>"$MCONF"
}
ANIM=0
if [ "$IS_TTY" = 1 ] && [ "${WAT_NO_ANIM:-0}" != 1 ] && [ "$(conf_get anim 1)" = 1 ]; then ANIM=1; fi

SPIN_PID=''
LOGF=''
LINK_RTT=''
IN_FLOW=0
INTRO_DONE=0
KEY=''
KEY_NAV=0 # 1: key_read reports arrows as up|down|left|right instead of swallowing them (tunnel page deck)
REPLY_V=''

cur_hide() { [ "$IS_TTY" = 1 ] && printf '\e[?25l'; return 0; }
cur_show() { [ "$IS_TTY" = 1 ] && printf '\e[?25h'; return 0; }
kill_spin() {
  if [ -n "$SPIN_PID" ]; then kill "$SPIN_PID" 2>/dev/null; wait "$SPIN_PID" 2>/dev/null; SPIN_PID=''; fi
  return 0
}
UDIR_TMP=''
BDIR_TMP=''
cleanup() { kill_spin; cur_show; [ -n "$LOGF" ] && rm -f "$LOGF"; [ -n "$UDIR_TMP" ] && rm -rf "$UDIR_TMP"; [ -n "$BDIR_TMP" ] && rm -rf "$BDIR_TMP"; at_cleanup; return 0; }
on_int() { [ "$IN_FLOW" = 1 ] && return 0; cleanup; printf '\n'; exit 130; }
eof_exit() { cleanup; echo; exit 0; }

rep() { local s; printf -v s '%*s' "$2" ''; printf '%s' "${s// /$1}"; }
VLEN=0
vlen() { local s=${1//$'\e'\[*([0-9;?])[a-zA-Z]/}; VLEN=${#s}; }
strip_ansi() { printf '%s' "${1//$'\e'\[*([0-9;?])[a-zA-Z]/}"; }

# ---- responsive layout width ----
UI_W=74
BOXW=74
TM_CW=36
term_cols() {
  local c=${COLUMNS:-}
  if [[ ! "$c" =~ ^[0-9]+$ ]] || [ "$c" -lt 20 ]; then
    c=$(tput cols 2>/dev/null || echo 80)
  fi
  case "$c" in ''|*[!0-9]*) c=80 ;; esac
  echo "$c"
}
ui_init_width() {
  local cols; cols=$(term_cols)
  if [ "$cols" -lt 50 ]; then UI_W=44
  elif [ "$cols" -lt 78 ]; then UI_W=$((cols - 4))
  elif [ "$cols" -ge 84 ]; then UI_W=76
  else UI_W=74; fi
  BOXW=$UI_W
  TM_CW=$(( (UI_W - 2) / 2 ))
}

# ---- plain messages ----
say()  { printf '%b\n' "$*"; }
ok()   { printf '  %s✔%s %s\n' "$GRN" "$RST" "$*"; }
warn() { printf '  %s!%s %s\n' "$YEL" "$RST" "$*"; }
err()  { ERRN=$((ERRN+1)); if [ "$NONINTERACTIVE" = 1 ]; then printf 'error: %s\n' "$*" >&2; else printf '  %s✘%s %s\n' "$RED" "$RST" "$*"; fi; }
hint() { printf '  %s%s%s\n' "$GRY" "$*" "$RST"; }
hr()   { [ "${UI_W:-0}" -gt 0 ] || ui_init_width; printf '  %s%s%s\n' "$GRY" "$(rep ─ "$UI_W")" "$RST"; }
key_label() { printf '%s[%s]%s' "$CYN" "$1" "$RST"; }
set_row() { # key label value [unit] [default] : one "[k] label  value" line of a settings page
  local v=$3
  if [ -n "$v" ]; then v="$v${4:+ $4}"
  else case "${5:-}" in off|'default route'|'') v="$GRY${5:-}$RST" ;; *) v="$5 ${GRY}(default)${RST}" ;; esac; fi
  printf '  %s %-16s %s\n' "$(key_label "$1")" "$2" "$v"
}
adv_group() { # title : a named section of the Advanced settings page (A1)
  printf '\n  %s%s%s\n' "$BOLD" "$1" "$RST"
}
menu_line() { # key label [key label...] : rows of "[k] label" items, wrapped at UI_W
  local out='' w=0 iw maxw=${UI_W:-74}
  while [ $# -ge 2 ]; do
    iw=$(( ${#1} + 3 + ${#2} ))
    if [ "$w" -gt 0 ] && [ $((w + 2 + iw)) -gt "$maxw" ]; then printf '  %s
' "$out"; out=''; w=0; fi
    [ "$w" -gt 0 ] && { out+='  '; w=$((w+2)); }
    out+="$(key_label "$1") $2"; w=$((w+iw)); shift 2
  done
  printf '  %s
' "$out"
}

# ---- signature kite + WATTUN mark & 0.45s packet-pulse reveal ----
WATTUN_KITE=(
  '   ╱╲  '
  '  ╱──╲ '
  ' ╱ ╲╱  '
)
WATTUN_BANNER=(
  '██   ██  ▄██▄  ██████ ██████ ██  ██ ██▄  ██'
  '██ █ ██ ██▄▄██   ██     ██   ██  ██ ██▀█▄██'
  ' ▀█▀█▀  ██  ██   ██     ██   ▀████▀ ██  ▀██'
)
META_TELEGRAM='@WatxDev'

_banner_draw_frame() { # kite0 kite1 kite2 word_col meta_col show_meta gap cols
  local k0=$1 k1=$2 k2=$3 wc=$4 mc=$5 show_meta=$6 gap=$7 cols=$8
  local -a side=("WatTunnel${VER:+ · v${VER}}" "github.com/JohnWatsoon" "t.me/${META_TELEGRAM#@}")
  local -a ks=("$k0" "$k1" "$k2")
  local i sp=''; [ "$gap" -eq 2 ] && sp=' '
  for i in 0 1 2; do
    if [ "$cols" -ge 78 ] && [ "$show_meta" = 1 ]; then
      printf '  %s%s%s  %s%s%s %s%s%s%s%s\n' \
        "$CYN" "${ks[$i]}" "$RST" "$wc" "${WATTUN_BANNER[$i]}" "$RST" "$sp" "$mc" "${side[$i]}" "$RST" "$EL"
    else
      printf '  %s%s%s  %s%s%s%s\n' "$CYN" "${ks[$i]}" "$RST" "$wc" "${WATTUN_BANNER[$i]}" "$RST" "$EL"
    fi
  done
}
banner() { # [1 = animated reveal] : geometric kite + WATTUN mark, responsive at <78 and <56 cols
  local anim=${1:-0} cols gap=2
  cols=$(term_cols)
  [ "$cols" -lt 80 ] && gap=1
  if [ "$cols" -lt 56 ]; then
    printf '  %s◈%s %sWatTunnel%s%s\n' "$CYN" "$RST" "$BOLD" "$RST" "${VER:+ ${GRY}v${VER}${RST}}"
    return 0
  fi
  if [ "$anim" = 1 ] && [ "$ANIM" = 1 ]; then
    cur_hide
    _banner_draw_frame "       ${GRY}┃" " ╺▸    ${GRY}┃" "╱      ${GRY}┃" "$GRY" "" 0 "$gap" "$cols"
    sleep 0.075
    printf '\r\e[3A'
    _banner_draw_frame "       ${GRY}┃" " ╺━▸   ${GRY}┃" "╱      ${GRY}┃" "$GRY" "" 0 "$gap" "$cols"
    sleep 0.075
    printf '\r\e[3A'
    _banner_draw_frame "       ${GRY}┃" "   ╺━━╋▸" "╱      ${GRY}┃" "$GRY" "" 0 "$gap" "$cols"
    sleep 0.075
    printf '\r\e[3A'
    _banner_draw_frame "${WATTUN_KITE[0]}" "${WATTUN_KITE[1]}" "${WATTUN_KITE[2]}" "$BOLD" "" 0 "$gap" "$cols"
    sleep 0.075
    printf '\r\e[3A'
    _banner_draw_frame "${WATTUN_KITE[0]}" "${WATTUN_KITE[1]}" "${WATTUN_KITE[2]}" "$BOLD" "$GRY" 1 "$gap" "$cols"
    cur_show
  else
    _banner_draw_frame "${WATTUN_KITE[0]}" "${WATTUN_KITE[1]}" "${WATTUN_KITE[2]}" "$BOLD" "$GRY" 1 "$gap" "$cols"
  fi
  if [ "$cols" -lt 78 ]; then
    printf '  %s%sgithub.com/JohnWatsoon · t.me/%s%s\n' "$GRY" "${VER:+v${VER} · }" "${META_TELEGRAM#@}" "$RST"
  fi
  return 0
}

VER=''

EL=''; [ "$IS_TTY" = 1 ] && EL=$'\e[K'
clear_screen() { [ "$IS_TTY" = 1 ] && printf '\e[H\e[2J'; return 0; }

render_header() { # title [subtitle] [animated=0]
  if [ "$NONINTERACTIVE" = 1 ]; then printf '== %s%s ==\n' "$1" "${2:+ ($2)}"; return 0; fi
  ui_init_width; clear_screen; echo
  banner "${3:-0}"
  hr
  local left="${BOLD}$1${RST}" right="${2:+${GRY}$2${RST}}"
  if [ -n "$right" ]; then
    local lw rw pad
    vlen "$left"; lw=$VLEN; vlen "$right"; rw=$VLEN
    pad=$((UI_W - lw - rw)); [ "$pad" -lt 2 ] && pad=2
    printf '  %s%*s%s\n' "$left" "$pad" '' "$right"
  else
    printf '  %s\n' "$left"
  fi
  echo
}

render_subpage_header() { # title [subtitle] : one line, "WatTunnel · title  subtitle"
  if [ "$NONINTERACTIVE" = 1 ]; then printf '== %s%s ==\n' "$1" "${2:+ ($2)}"; return 0; fi
  ui_init_width; clear_screen; echo
  printf '  %sWatTunnel%s ·%s %s%s%s%s\n' "$GRY" "${VER:+ v$VER}" "$RST" "$BOLD" "$1" "$RST" "${2:+  ${GRY}$2${RST}}"
  hr; echo
}

page_full() { # title [subtitle]
  local anim=0
  if [ "$ANIM" = 1 ] && [ "$INTRO_DONE" = 0 ]; then anim=1; fi
  INTRO_DONE=1
  render_header "$1" "${2:-}" "$anim"
}

page() { # title [subtitle]
  render_subpage_header "$1" "${2:-}"
}

# ---- boxes ----
box_top() { # [title]
  if [ -z "${1:-}" ]; then printf '  %s╭%s╮%s\n' "$GRY" "$(rep ─ "$BOXW")" "$RST"; return 0; fi
  vlen "$1"
  local rem=$((BOXW - VLEN - 3)); [ "$rem" -lt 1 ] && rem=1
  printf '  %s╭─ %s%s%s %s╮%s\n' "$GRY" "$RST" "$1" "$GRY" "$(rep ─ "$rem")" "$RST"
}
box_mid() { printf '  %s├%s┤%s\n' "$GRY" "$(rep ─ "$BOXW")" "$RST"; }
box_row() { # a row never pushes the right border out: a longer one is cut to the box
  local t=$1 pad; vlen "$t"
  if [ "$VLEN" -gt $((BOXW-2)) ]; then t=$(strip_ansi "$t"); t="${t:0:$((BOXW-3))}…"; VLEN=$((BOXW-2)); fi
  pad=$((BOXW-2-VLEN)); printf '  %s│%s %s%*s %s│%s\n' "$GRY" "$RST" "$t" "$pad" '' "$GRY" "$RST"
}
row_2col() {
  local left=$1 right=$2 w_left pad
  if [ "$BOXW" -lt 58 ]; then
    box_row "$left"
    [ -n "$(strip_ansi "$right")" ] && box_row "$right"
    return 0
  fi
  w_left=$(( (BOXW - 4) / 2 ))
  vlen "$left"
  pad=$((w_left - VLEN))
  [ "$pad" -lt 0 ] && pad=0
  box_row "${left}$(rep ' ' "$pad")  ${right}"
}
kv() { printf '%s%-11s%s %s' "$GRY" "$1" "$RST" "$2"; } # label value, for the tunnel card
box_bot() { printf '  %s╰%s╯%s\n' "$GRY" "$(rep ─ "$BOXW")" "$RST"; }

# ---- spinner / progress ----
SPIN_FR=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
spin_start() { # label : animate a spinner on the current line until spin_stop (foreground work continues)
  [ "$ANIM" = 1 ] || return 0
  cur_hide
  (
    local i=0 t0=$SECONDS el ts
    while :; do
      el=$((SECONDS-t0))
      if [ "$el" -ge 1 ]; then ts=" ${GRY}· ${el}s${RST}"; else ts=''; fi
      printf '\r\e[K  %s%s%s %s%s' "$CYN" "${SPIN_FR[$i]}" "$RST" "$1" "$ts"
      i=$(( (i+1) % 10 )); sleep 0.1
    done
  ) &
  SPIN_PID=$!
}
spin_stop() { kill_spin; [ "$ANIM" = 1 ] && { printf '\r\e[K'; cur_show; }; return 0; }
step() { # label cmd... : run silently under a spinner, print a done/failed line
  local label=$1 rc; shift
  [ -n "$LOGF" ] || LOGF=$(mktemp /tmp/wattun-manager.XXXXXX)
  : >"$LOGF"
  spin_start "$label"
  "$@" >>"$LOGF" 2>&1; rc=$?
  spin_stop
  if [ "$rc" -eq 0 ]; then ok "$label"; else err "$label"; tail -n 3 "$LOGF" 2>/dev/null | sed "s/^/      $GRY/; s/\$/$RST/"; fi
  return "$rc"
}
bar() { # cur max width -> ━━━━━━────
  local c=$1 m=$2 w=${3:-16} f ch_f='━' ch_e='─'
  [ "$m" -gt 0 ] || m=1; [ "$c" -gt "$m" ] && c=$m
  f=$(( c * w / m ))
  if [ "$USE_COLOR" = 1 ]; then
    printf '%s%s%s%s%s' "$CYN" "$(rep "$ch_f" "$f")" "$GRY" "$(rep "$ch_e" $((w-f)))" "$RST"
  else
    printf '%s%s' "$(rep '#' "$f")" "$(rep '-' $((w-f)))"
  fi
}

celebrate() { printf '  %s◆%s %s%s%s\n' "$GRN" "$RST" "$BOLD" "$1" "$RST"; }
sec_hdr() { # title [meta] : calm section divider clamped to UI_W
  [ "${UI_W:-0}" -gt 0 ] || ui_init_width
  if [ "$NONINTERACTIVE" = 1 ]; then printf '\n  -- %s%s --\n' "$1" "${2:+ ($2)}"; return 0; fi
  local m=${2:+ · $2} len rem
  len=$(( 3 + ${#1} + ${#m} + 1 ))
  rem=$(( UI_W - len )); [ "$rem" -lt 2 ] && rem=2
  printf '\n  %s── %s%s%s%s %s%s\n' "$GRY" "$RST$BOLD" "$1" "$RST" "${2:+ ${GRY}· ${2}}" "$GRY" "$(rep ─ "$rem")$RST"
}
tbar() { # val max [width=10] : proportional throughput bar (▰▰▱▱ / ##--)
  local v=${1:-0} m=${2:-10} w=${3:-10} f
  f=$(awk -v v="$v" -v m="$m" -v w="$w" 'BEGIN{if(m<=0)m=1; r=int((v*w/m)+0.5); if(r<0)r=0; if(r>w)r=w; print r}')
  if [ "$USE_COLOR" = 1 ]; then
    printf '%s%s%s%s%s' "$CYN" "$(rep ▰ "$f")" "$GRY" "$(rep ▱ $((w-f)))" "$RST"
  else
    printf '%s%s' "$(rep '#' "$f")" "$(rep '-' $((w-f)))"
  fi
}
conn_card() { # name carrier rtt maps... : connected summary card + diagram
  local name=$1 cr=$2 rtt=$3; shift 3
  [ "${UI_W:-0}" -gt 0 ] || ui_init_width
  if [ "$NONINTERACTIVE" = 1 ]; then
    celebrate "CONNECTED (RTT ${rtt} ms)"
    echo
    say "  Users connect here:"
    conn_diagram "$cr" "$@"
    return 0
  fi
  celebrate "CONNECTED${rtt:+ · ${rtt} ms}"
  echo
  conn_diagram "$cr" "$@"
  echo
  box_top "$name"
  if systemctl is-enabled -q "$HEAL_UNIT.timer" 2>/dev/null; then
    box_row "$(kv 'Auto-heal' "${GRN}on${RST} · background monitor")"
  fi
  if is_pool_list "$cr" && [ "$(uname -s)" = Linux ] && [ -z "${T_FAKESNI:-}${T_POOLROT:-}${T_POOLBYTES:-}" ] \
     && ! grep -q '^fake-sni:' <<<"${AT_EXTRA:-}"; then
    if [ "${T_REV:-0}" = 1 ]; then
      box_row "$(kv 'Blocked?' "Set anti-censor on Kharej: tunnel page -> z")"
    else
      box_row "$(kv 'Blocked?' "Press [z] on tunnel page for anti-censor presets")"
    fi
  fi
  box_bot
}

# ---- input ----
# shellcheck disable=SC2120
key_read() { # [timeout] -> KEY ; rc 0 key, 2 timeout ; EOF exits
  local rc k2 c i; KEY=''
  [ "$NONINTERACTIVE" = 1 ] && { KEY=enter; return 0; }
  while :; do
    if [ -n "${1:-}" ]; then IFS= read -rsn1 -t "$1" KEY; rc=$?; else IFS= read -rsn1 KEY; rc=$?; fi
    if [ "$rc" -ne 0 ]; then
      [ "$rc" -gt 128 ] && { KEY=''; return 2; }
      eof_exit
    fi
    if [ "$KEY" = $'\e' ]; then
      # ESC followed by more bytes is an escape sequence (arrows, Home, F-keys): swallowed and read again,
      # except arrows on a page that navigates a deck (KEY_NAV=1). A lone ESC stays "esc".
      if IFS= read -rsn1 -t 0.05 k2; then
        c=''
        if [ "$k2" = '[' ] || [ "$k2" = O ]; then
          for ((i=0; i<8; i++)); do
            IFS= read -rsn1 -t 0.05 c || break
            case "$c" in [A-Za-z~@]) break ;; esac
          done
          if [ "$KEY_NAV" = 1 ]; then
            case "$c" in
              A) KEY=up; return 0 ;;
              B) KEY=down; return 0 ;;
              C) KEY=right; return 0 ;;
              D) KEY=left; return 0 ;;
            esac
          fi
        fi
        KEY=''; continue
      fi
      KEY=esc
    fi
    break
  done
  [ -z "$KEY" ] && KEY=enter
  return 0
}
ask() { # prompt [default] -> REPLY_V (free text). Enter keeps the default.
  local d=${2:-} v
  if [ "$NONINTERACTIVE" = 1 ]; then REPLY_V=$d; return 0; fi
  printf '  %s?%s %s%s %s›%s ' "$CYN" "$RST" "$1" "${d:+ ${GRY}[$d]${RST}}" "$GRY" "$RST"
  IFS= read -r v || eof_exit
  v=${v#"${v%%[![:space:]]*}"}; v=${v%"${v##*[![:space:]]}"}
  REPLY_V=${v:-$d}
}
ask_ok() { # prompt default validator : up to 3 tries, validator prints its own error
  local t
  if [ "$NONINTERACTIVE" = 1 ]; then # the preset/default is the only answer: validate once and say what is wrong
    ask "$1" "$2"; "$3" "$REPLY_V" && return 0
    err "'$1': '$REPLY_V' is not accepted (set it with the matching command-line flag)"; return 1
  fi
  for t in 1 2 3; do
    ask "$1" "$2"
    if "$3" "$REPLY_V"; then return 0; fi
  done
  err "Too many invalid answers, going back."; return 1
}
confirm() { # prompt [y|n default]
  local def=${2:-y} t lab='Y/n'
  [ "$def" = y ] || def=n # anything but y is "no"
  [ "$def" = n ] && lab='y/N'
  if [ "$NONINTERACTIVE" = 1 ]; then
    echo "  ? $1 -> $([ "$def" = y ] && echo yes || echo no)" # the answer actually used
    [ "$def" = y ]; return
  fi
  for t in 1 2 3; do
    printf '  %s?%s %s %s[%s]%s ' "$CYN" "$RST" "$1" "$GRY" "$lab" "$RST"
    key_read
    case "$KEY" in
      y|Y) echo yes; return 0 ;;
      n|N) echo no; return 1 ;;
      enter) echo; [ "$def" = y ]; return ;;
      esc) echo; return 1 ;;
    esac
    echo
  done
  return 1
}
pause() { printf '\n  %sPress any key to go back...%s' "$GRY" "$RST"; key_read; echo; }
PMSG=''
flash() { PMSG=$*; } # shown after the next prompt caret

run_flow() { # fn args... : run in a subshell; Ctrl+C cancels just this flow
  local rc
  IN_FLOW=1
  ( trap 'kill_spin; cur_show; exit 130' INT; trap 'kill_spin; cur_show; at_cleanup' EXIT; "$@" )
  rc=$?
  IN_FLOW=0
  [ "$rc" -eq 130 ] && { echo; warn "Cancelled."; [ "$IS_TTY" = 1 ] && sleep 0.8; }
  return "$rc"
}

# ======================================================================================
#  Pure helpers: config, tokens, port specs
# ======================================================================================
is_auto_helper() { # hidden internal helpers: per-shape auto listeners (-e-*) and auto reverse companions (-r)
  is_auto_ext "$1" || [ -n "$(companion_of "$1")" ]
}
is_probe_unit() { # hidden scepter machinery (3.5.0, plan D2/E4): the engine's test.open probe listeners live
  # as probe-<unix-ts>.yml in Kharej's conf dir for their ttl (probe-<unix-ts>-N.yml on a same-second
  # collision, the shape openProbe really produces). Discriminator = the name shape AND the provenance line
  # the engine stamps every probe yml with (cmd/wattun/scepter_ops.go probeProvenance, the same string its
  # orphan sweep matches) AND mode: server — so a user tunnel merely named probe-12345 predating Scepter,
  # which carries none of those, keeps listing (the .autoext sidecar's M1 rule, applied to probes).
  [[ "$1" =~ ^probe-[0-9]+(-[0-9]+)?$ ]] || return 1
  grep -qs 'probe tunnel created by scepter test.open' "$CONF/$1.yml" || return 1
  [ "$(cfg "$1" mode)" = server ] || return 1
  return 0
}
tunnels() { # every *visible* tunnel: hidden per-shape listeners (-e-*), reverse companions (-r) and the
  # transient scepter test.open probes stay invisible (cleanup paths use tunnels_all, which sees them all)
  local f b; for f in "$CONF"/*.yml; do [ -e "$f" ] || continue; b=${f##*/}; b=${b%.yml}; is_auto_helper "$b" && continue; is_probe_unit "$b" && continue; echo "$b"; done
}
listed_tunnels() { # what a status list shows: hidden auto helpers (-r and -e-*) never appear as separate tunnels
  local n; for n in $(tunnels); do
    is_auto_helper "$n" && continue
    echo "$n"
  done
}
tunnels_all() { # every config, hidden helpers included (uninstall/low-level cleanup)
  local f b; for f in "$CONF"/*.yml; do [ -e "$f" ] || continue; b=${f##*/}; echo "${b%.yml}"; done
}
auto_helpers() { # parent -> its hidden internal helper units ($parent-r and $parent-e-*), one per line
  local p=$1
  [ -f "$CONF/$p-r.yml" ] && [ "$(companion_of "$p-r")" = "$p" ] && echo "$p-r"
  auto_ext_names "$p"
}
auto_all_units() { # parent -> parent followed by its hidden internal helpers
  echo "$1"
  auto_helpers "$1"
}
cfg() { # name key -> first "key: value" of NAME.yml, quotes dropped. Pure bash: a sed|head|tr per read was most of
  # the auto-heal's forks (hundreds a pass); rc 2 when the file is unreadable, like the old pipeline under pipefail.
  local l f="$CONF/$1.yml"
  [ -r "$f" ] || return 2
  while IFS= read -r l || [ -n "$l" ]; do
    case $l in "$2:"*)
      l=${l#"$2:"}; l=${l#"${l%%[![:space:]]*}"}; printf '%s\n' "${l//[\"\']/}"; return 0 ;;
    esac
  done <"$f"
  return 0
}
role()    { [ "$(cfg "$1" mode)" = server ] && echo Kharej || echo Iran; }
role_label() { case $1 in Iran) echo Entry ;; Kharej) echo Exit ;; *) echo "$1" ;; esac; } # 4.1.2: what a role is called on screen
stats()   { local m; m=$(cfg "$1" metrics); [ -n "$m" ] && curl -fs --noproxy '*' --max-time 2 "http://$m/stats"; }
stats_flat() { # name : /stats?flat=1 (3.3.6), one key=value line per top-level value, for readers of aggregates only;
  # an older binary answers it with the JSON, and an empty answer falls back to one plain /stats: jget reads both forms
  local m v; m=$(cfg "$1" metrics); [ -n "$m" ] || return 1
  v=$(curl -fs --noproxy '*' --max-time 2 "http://$m/stats?flat=1") && [ -n "$v" ] || v=$(stats "$1") || return 1
  printf '%s' "$v"
}
ms()      { printf "%.1f" "${1:-0}"; }
jget()    { # text key : a top-level value of a JSON object, or of stats_flat's key=value lines (text not starting with '{')
  case $1 in
    '{'*) grep -o "\"$2\": *[^,}]*" <<<"$1" | head -1 | sed 's/.*: *//; s/"//g' ;;
    *) sed -n "s/^$2=//p" <<<"$1" | head -1 ;;
  esac
}
jget_flat() { # json flat-key legacy-key: the flat aggregate first, fall back for older binaries
  local v; v=$(jget "$1" "$2"); [ -n "$v" ] || v=$(jget "$1" "$3"); printf '%s' "$v"
}
human()   { awk -v b="${1:-0}" 'BEGIN{s="B KB MB GB TB";split(s,u," ");i=1;while(b>=1024&&i<5){b/=1024;i++}printf "%.1f %s",b,u[i]}'; }
ipv4_ok() { # is $1 a dotted IPv4 with every octet 0-255 ?
  local a b c d
  [[ "$1" =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$ ]] || return 1
  a=${BASH_REMATCH[1]}; b=${BASH_REMATCH[2]}; c=${BASH_REMATCH[3]}; d=${BASH_REMATCH[4]}
  [ "$((10#$a))" -le 255 ] && [ "$((10#$b))" -le 255 ] && [ "$((10#$c))" -le 255 ] && [ "$((10#$d))" -le 255 ]
}
ip_is_private() { # RFC1918, CGNAT 100.64/10, loopback, link-local
  local a b
  ipv4_ok "$1" || return 1
  a=${1%%.*}; b=${1#*.}; b=${b%%.*}; a=$((10#$a)); b=$((10#$b))
  case "$a" in 10|127) return 0 ;; esac
  [ "$a" = 172 ] && [ "$b" -ge 16 ] && [ "$b" -le 31 ] && return 0
  [ "$a" = 192 ] && [ "$b" = 168 ] && return 0
  [ "$a" = 169 ] && [ "$b" = 254 ] && return 0
  [ "$a" = 100 ] && [ "$b" -ge 64 ] && [ "$b" -le 127 ] && return 0
  return 1
}
public_ip() { # prints a valid IPv4 (or IPv6 when no IPv4 exists). A public address on an interface comes first (no
  # third-party lookup); NAT'd servers fall back to ipify/ifconfig.me, then hostname -I.
  local ip u
  ip=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\) .*/\1/p')
  if ipv4_ok "$ip" && ! ip_is_private "$ip"; then echo "$ip"; return 0; fi
  for u in https://api.ipify.org https://ifconfig.me; do
    ip=$(curl -fs4 --max-time 5 "$u" 2>/dev/null | tr -d '[:space:]')
    ipv4_ok "$ip" && { echo "$ip"; return 0; }
  done
  ip=$(hostname -I 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i ~ /^[0-9.]+$/){print $i; exit}}')
  ipv4_ok "$ip" && { echo "$ip"; return 0; }
  ip=$(ip -6 route get 2606:4700::1 2>/dev/null | sed -n 's/.* src \([0-9a-fA-F:]*\) .*/\1/p' | head -1)
  if ipv6_ok "$ip"; then
    case "${ip,,}" in ::1|fe80:*|fc*|fd*) ;; *) echo "$ip"; return 0 ;; esac
  fi
  for u in https://api64.ipify.org https://ifconfig.me; do
    ip=$(curl -fs6 --max-time 5 "$u" 2>/dev/null | tr -d '[:space:]')
    ipv6_ok "$ip" && { echo "$ip"; return 0; }
  done
  ip=$(hostname -I 2>/dev/null | awk '{for(i=1;i<=NF;i++) if($i ~ /:/ && $i !~ /^fe80:/){print $i; exit}}')
  ipv6_ok "$ip" && echo "$ip"
  return 0
}
new_key() { head -c 32 /dev/urandom | base64 | tr -d '/+=\n' | head -c 40; }
rand_path() { echo "/api/$(head -c 6 /dev/urandom | od -An -tx1 | tr -d ' \n')"; } # a fresh URL path per tunnel: every install used /wat, a fixed string a filter can match (3.0.1)
uptime_of() { # name -> "3d 4h" / "2h 14m" / "5m", empty when unknown
  local t s; t=$(systemctl show "${WAT_PREFIX}@$1" -p ActiveEnterTimestamp --value 2>/dev/null)
  s=$(date -d "$t" +%s 2>/dev/null) || return 0; s=$(( $(date +%s) - s )); [ "$s" -ge 0 ] || return 0
  if [ "$s" -ge 86400 ]; then echo "$((s/86400))d $((s%86400/3600))h"
  elif [ "$s" -ge 3600 ]; then echo "$((s/3600))h $((s%3600/60))m"
  else echo "$((s/60))m"; fi
}
has_dgram() { local c; for c in ${1//+/ }; do is_pool "$c" || return 0; done; return 1; } # icmp/udp/gre/ipip in the list: the only carriers whose loss_pct is wire loss

# ---- engine state files (F8, 3.3.0): -state-dir moves the quota/totals pair, the names keep the config basename ----
# Mirrors cmd/wattun/state.go statePaths: <state-dir>/<config basename>.quota.json / .totals.json when the tunnel sets
# state-dir:, else next to the config (the 2.5.0-3.2.x location, so existing tunnels keep working). The manager only
# ever deletes these files (reset-traffic, delete, uninstall): live byte totals come from /stats, never from disk.
state_base_path() { # name state-dir -> the "<config basename>" the engine prefixes (pure; empty dir = next to the config)
  local n=$1 d=${2:-}
  if [ -n "$d" ]; then
    # the engine resolves a relative -state-dir from its working directory, which systemd sets to /; mirror that so a
    # hand-edited relative value does not make the manager delete files somewhere else
    case "$d" in /*) ;; *) d="/$d" ;; esac
    d=${d%/}
    printf '%s/%s.yml' "$d" "$n"
  else printf '%s/%s.yml' "$CONF" "$n"; fi
}
state_dir_of() { # name -> the tunnel's state-dir value (empty = engine default: next to the config)
  local d; d=$(cfg "$1" state-dir)
  printf '%s' "${d%/}"
}
state_dir_is_relative() { # name -> 0 when a hand-edited state-dir: is relative (engine CWD = / under the unit)
  local d; d=$(state_dir_of "$1")
  [ -n "$d" ] && [ "${d#/}" = "$d" ]
}
state_dir_relative_warn() { # name : M8 — say it out loud instead of silently assuming the unit's CWD (/)
  state_dir_is_relative "$1" || return 0
  warn "state-dir of '$1' is relative ($(cfg "$1" state-dir)); the service resolves it from / (the manager does the same)."
  hint "Use an absolute path (the shipped unit supports /run/wattun) so the manager and the service agree."
  return 0
}
state_base() { state_base_path "$1" "$(state_dir_of "$1")"; }
state_file() { # name totals|quota -> resolved path, exactly where the engine reads/writes it
  case "${2:-}" in totals|quota) ;; *) return 1 ;; esac
  printf '%s.%s.json' "$(state_base "$1")" "$2"
}
state_files() { # name -> every state file the engine can leave for it (delete/reset cleanup), one per line
  local b; b=$(state_base "$1")
  printf '%s\n' "$b.totals.json" "$b.totals.json.host" "$b.totals.json.tmp" "$b.quota.json" "$b.quota.json.tmp" "$b.pn" "$b.pn.tmp"
}

free_metrics_port() { # first free port from WAT_METRICS_BASE (default 19750, sandbox 19850); never 18990-18999 or 19700-19709 or 20400-20999
  local p=${WAT_METRICS_BASE:-} lim
  [[ "$p" =~ ^[0-9]{4,5}$ ]] || { p=19750; [ "$SANDBOX" = 1 ] && p=19850; }
  lim=$((p + 650))
  if [ "$p" -lt 20400 ] && [ "$lim" -gt 20400 ]; then lim=20400; fi
  [ "$lim" -le 65535 ] || lim=65535 # F25: the range follows the base; capped below the 20500-20999 test range
  while [ "$p" -lt "$lim" ]; do
    if { [ "$p" -ge 18990 ] && [ "$p" -le 18999 ]; } || { [ "$p" -ge 19700 ] && [ "$p" -le 19709 ]; } || { [ "$p" -ge 20400 ] && [ "$p" -le 20999 ]; }; then p=$((p+1)); continue; fi
    if ! port_busy "$p" tcp bind \
       && ! grep -qhE "^(metrics|dns-listen):.*:$p([\"'[:space:]]|#|\$)" "$CONF"/*.yml 2>/dev/null \
       && ! tunnel_using_listen "$p" >/dev/null \
       && ! tunnel_using_public "$p" tcp >/dev/null; then
      break
    fi
    p=$((p+1))
  done
  # F25: fail closed instead of returning a busy/out-of-range port. Callers then write no metrics: line.
  if [ "$p" -ge "$lim" ]; then
    printf '  ! No free metrics port below %s; this tunnel gets no /stats listener (auto-heal cannot read it).\n' "$lim" >&2
    return 1
  fi
  echo "$p"
}
valid_name() { [[ "$1" =~ ^[a-zA-Z0-9_-]{1,32}$ ]] && [ ! -e "$CONF/$1.yml" ]; }
suggest_name() { # kharej|iran -> kharej, kharej-2, kharej-3 ...
  local base=$1 n=1 c=$1
  while [ -e "$CONF/$c.yml" ] && [ "$n" -lt 99 ]; do n=$((n+1)); c="$base-$n"; done
  echo "$c"
}

# ---- port busy / ownership ----
port_busy() { # port [tcp|udp|any] [listen|bind] : is something listening (or bound when $3=bind) on IPv4/IPv6?
  local port=${1:-} pr=${2:-any} mode=${3:-listen} f fl hex ss_out ss_rc files=()
  [[ "$port" =~ ^[0-9]+$ ]] && [ "$((10#$port))" -ge 1 ] && [ "$((10#$port))" -le 65535 ] || return 0
  port=$((10#$port))
  if command -v ss >/dev/null 2>&1; then
    if [ "$mode" = bind ]; then
      case "$pr" in tcp) fl=-Htan ;; udp) fl=-Haun ;; *) fl=-Htaun ;; esac
    else
      case "$pr" in tcp) fl=-Hltn ;; udp) fl=-Hlun ;; *) fl=-Hltnu ;; esac
    fi
    ss_out=$(ss "$fl" "( sport = :$port )" 2>/dev/null); ss_rc=$?
    if [ "$ss_rc" -eq 0 ]; then
      [ -n "$ss_out" ] && return 0
      return 1
    fi
  fi
  printf -v hex '%04X' "$port"   # ss missing or failed (e.g. restricted container): read /proc/net IPv4 + IPv6 directly
  case "$pr" in tcp) files=(tcp tcp6) ;; udp) files=(udp udp6) ;; *) files=(tcp tcp6 udp udp6) ;; esac
  for f in "${files[@]}"; do
    awk -v h=":$hex" -v u="${f:0:3}" -v m="$mode" \
      'NR>1 && toupper(substr($2, length($2)-4)) == h && (m=="bind" || u=="udp" || $4=="0A") {found=1} END{exit !found}' \
      "/proc/net/$f" 2>/dev/null && return 0
  done
  return 1
}
port_user() { # port proto -> process name and PID or empty
  local f=-Hltnp; [ "${2:-tcp}" = udp ] && f=-Hlunp
  local line u pid
  line=$(ss "$f" "( sport = :$1 )" 2>/dev/null | grep -o 'users:(("[^"]*",pid=[0-9]*' | head -1)
  if [ -n "$line" ]; then
    u=$(echo "$line" | cut -d'"' -f2)
    pid=$(echo "$line" | grep -o 'pid=[0-9]*' | cut -d= -f2)
    if [ -n "$pid" ] && [ -n "$u" ]; then echo "$u (PID $pid)"; return; fi
    [ -n "$u" ] && { echo "$u"; return; }
  fi
  ss "$f" "( sport = :$1 )" 2>/dev/null | grep -o 'users:(("[^"]*"' | head -1 | cut -d'"' -f2
}

# ---- port specs. Canonical form: LISTEN:TARGET/proto (proto = tcp|udp) ----
NS_OUT=(); NS_ERR=''
norm_spec() { # "8443->443/udp" "443" "53/both" -> NS_OUT=(canonical...) ; rc 1 + NS_ERR on bad input
  NS_OUT=(); NS_ERR=''
  local s=$1 body proto=tcp L T
  s=${s//->/:}; s=${s//→/:}; s=${s//=>/:}; s=${s//=/:}; s=${s//[[:space:]]/}
  [ -n "$s" ] || { NS_ERR='empty entry'; return 1; }
  body=$s
  if [[ $s == */* ]]; then body=${s%%/*}; proto=${s#*/}; fi
  proto=${proto,,}
  case $proto in
    tcp|udp|both) ;;
    tcp+udp|udp+tcp|tcpudp|udptcp) proto=both ;;
    *) NS_ERR="unknown protocol '$proto' (use tcp, udp or both)"; return 1 ;;
  esac
  if [[ $body == *:*:* ]]; then NS_ERR="'$1' has too many ':'"; return 1; fi
  if [[ $body == *:* ]]; then L=${body%%:*}; T=${body##*:}; else L=$body; T=$body; fi
  if ! [[ $L =~ ^[0-9]{1,5}$ && $T =~ ^[0-9]{1,5}$ ]]; then NS_ERR="'$1' is not a port"; return 1; fi
  L=$((10#$L)); T=$((10#$T))
  if [ "$L" -lt 1 ] || [ "$L" -gt 65535 ] || [ "$T" -lt 1 ] || [ "$T" -gt 65535 ]; then NS_ERR="'$1': ports must be 1-65535"; return 1; fi
  case $proto in both) NS_OUT=("$L:$T/tcp" "$L:$T/udp") ;; *) NS_OUT=("$L:$T/$proto") ;; esac
}
spec_L() { local x=${1%%/*}; echo "${x%%:*}"; }
spec_T() { local x=${1%%/*}; echo "${x##*:}"; }
spec_P() { echo "${1##*/}"; }
spec_yaml() { # canonical -> YAML list item text (L:T only when they differ)
  local L T P out
  L=$(spec_L "$1"); T=$(spec_T "$1"); P=$(spec_P "$1")
  if [ "$L" = "$T" ]; then out=$L; else out="$L:$T"; fi
  [ "$P" = udp ] && out="$out/udp"
  echo "$out"
}
spec_human() { # canonical -> "443" / "8443→443" / "53/udp"
  local L T P out
  L=$(spec_L "$1"); T=$(spec_T "$1"); P=$(spec_P "$1")
  if [ "$L" = "$T" ]; then out=$L; else out="$L→$T"; fi
  [ "$P" = udp ] && out="$out/udp"
  echo "$out"
}
maps_yaml_block() { # prints the ports: block for the array MAPS (nothing when empty)
  local i
  [ "${#MAPS[@]}" -gt 0 ] || return 0
  echo "ports:"
  for ((i=0; i<${#MAPS[@]}; i++)); do echo "  - $(spec_yaml "${MAPS[$i]}")"; done
}
maps_allow_str() { # MAPS -> "443,53/udp" (target ports only, as embedded in the token)
  local i out='' t p
  for ((i=0; i<${#MAPS[@]}; i++)); do
    t=$(spec_T "${MAPS[$i]}"); p=$(spec_P "${MAPS[$i]}")
    [ "$p" = udp ] && t="$t/udp"
    case ",$out," in *",$t,"*) continue ;; esac
    out="${out:+$out,}$t"
  done
  echo "$out"
}
allow_to_array() { # "443,53/udp" -> PE_ALLOW=(443:443/tcp 53:53/udp)
  local it; PE_ALLOW=()
  for it in ${1//,/ }; do norm_spec "$it" && PE_ALLOW+=("${NS_OUT[@]}"); done
  return 0
}
allowed_has() { # target proto : 0 if allowed or the allow list is unknown/empty
  local i
  [ "${#PE_ALLOW[@]}" -gt 0 ] || return 0
  for ((i=0; i<${#PE_ALLOW[@]}; i++)); do
    [ "$(spec_T "${PE_ALLOW[$i]}")" = "$1" ] && [ "$(spec_P "${PE_ALLOW[$i]}")" = "$2" ] && return 0
  done
  return 1
}
yml_ports_raw() { # name -> one raw ports: item per line
  sed -n '/^ports:/,/^[^ #\t-]/{/^[[:space:]]*-[[:space:]]/{s/^[[:space:]]*-[[:space:]]*//;s/[[:space:]]*#.*//;s/["'"'"']//g;p}}' "$CONF/$1.yml" 2>/dev/null
}
yml_maps() { # name -> canonical items, one per line
  local it
  while IFS= read -r it; do [ -n "$it" ] && norm_spec "$it" && printf '%s\n' "${NS_OUT[@]}"; done < <(yml_ports_raw "$1")
}
load_maps() { # name -> MAPS
  MAPS=()
  local it
  while IFS= read -r it; do [ -n "$it" ] && MAPS+=("$it"); done < <(yml_maps "$1")
}
cfg_ports() { # legacy one-line list: "443 8443→443 53/udp"
  local it out=''
  while IFS= read -r it; do [ -n "$it" ] && out="$out $(spec_human "$it")"; done < <(yml_maps "$1")
  echo "${out# }"
}
write_ports() { # name : replace the ports: block of NAME.yml with the array MAPS
  local f="$CONF/$1.yml" tmp
  tmp=$(mktemp "$CONF/.tmp.XXXXXX") || return 1
  awk '
    /^ports:/ {skip=1; next}
    skip && /^[[:space:]]+(-|#)/ {next}
    skip && /^[[:space:]]*$/ {next}
    {skip=0; print}' "$f" >"$tmp"
  maps_yaml_block >>"$tmp"
  chmod 600 "$tmp"; wmv "$tmp" "$f"
}
wmv() { # src dst : the one-writer lock (panel plan D3) around a config rename; shared with the Go manager and the panel
  if command -v flock >/dev/null 2>&1 && mkdir -p "$RUN" 2>/dev/null && : >>"$RUN/write.lock" 2>/dev/null; then
    flock -w 10 "$RUN/write.lock" mv -f "$1" "$2" || { rm -f "$1"; err "another change is being saved, try again"; return 1; }
  else
    mv -f "$1" "$2"
  fi
}
set_value() { # name key value : set or add a top-level key
  local f="$CONF/$1.yml" tmp
  tmp=$(mktemp "$CONF/.tmp.XXXXXX") || return 1
  # key and value through the environment: awk -v would expand backslash escapes in the value
  grep -v "^$2:" "$f" | K="$2" V="$3" awk '/^(metrics|ports):/ && !d {print ENVIRON["K"] ": " ENVIRON["V"]; d=1} {print} END{if(!d) print ENVIRON["K"] ": " ENVIRON["V"]}' >"$tmp"
  chmod 600 "$tmp"; wmv "$tmp" "$f"
}
unset_value() { # same tmp+mv pattern as set_value: the 3 s hot-reloader must never see an interleaved rewrite
  local f="$CONF/$1.yml" tmp
  tmp=$(mktemp "$CONF/.tmp.XXXXXX") || return 1
  grep -v "^$2:" "$f" >"$tmp"
  chmod 600 "$tmp"; wmv "$tmp" "$f"
}
set_port_limit() { # name port rate quota [period: day|week|month, 3.3.6; written only with a quota]
  local f="$CONF/$1.yml" lp=$2 lr=$3 lq=$4 lpd=${5:-} tmp
  [ -f "$f" ] || return 1
  tmp=$(mktemp "$CONF/.tmp.XXXXXX") || return 1
  awk -v lp="$lp" -v lr="$lr" -v lq="$lq" -v lpd="$lpd" '
    BEGIN { in_lim=0; wrote=0 }
    /^limits:/ { in_lim=1; print; next }
    in_lim && /^[a-zA-Z0-9_-]+:/ {
      if (!wrote && ((lr != "" && lr != "0") || (lq != "" && lq != "0"))) {
        s = "  - " lp
        if (lr != "" && lr != "0") s = s " rate=" lr
        if (lq != "" && lq != "0") s = s " quota=" lq
        if (lpd != "" && lq != "" && lq != "0") s = s " period=" lpd
        print s
        wrote = 1
      }
      in_lim = 0
      print
      next
    }
    in_lim && $1 == "-" && $2 ~ ("^" lp "([[:space:]]|$)") {
      if (!wrote && ((lr != "" && lr != "0") || (lq != "" && lq != "0"))) {
        s = "  - " lp
        if (lr != "" && lr != "0") s = s " rate=" lr
        if (lq != "" && lq != "0") s = s " quota=" lq
        if (lpd != "" && lq != "" && lq != "0") s = s " period=" lpd
        print s
        wrote = 1
      }
      next
    }
    { print }
    END {
      if (!wrote && ((lr != "" && lr != "0") || (lq != "" && lq != "0"))) {
        if (!in_lim) print "limits:"
        s = "  - " lp
        if (lr != "" && lr != "0") s = s " rate=" lr
        if (lq != "" && lq != "0") s = s " quota=" lq
        if (lpd != "" && lq != "" && lq != "0") s = s " period=" lpd
        print s
      }
    }
  ' "$f" >"$tmp"
  chmod 600 "$tmp"; wmv "$tmp" "$f"
}

# Connection token: wat1:BASE64("carrier|peer|key|path|sni|icmp-type|allowed-ports[|reverse]")
# Field 7 (allowed ports on Kharej, comma list, empty = any) was added in 1.9.0; 6-field tokens still parse.
# Field 8 ("1" = reverse ICMP, wattun >= 2.0.0) is written only when set, so every other token stays 7 fields.
# Field 9 (auto plan) is written only for carrier "auto" tokens; field 8 stays empty there. Format:
#   d=udp:4443,tcp:4443,...;r=tcp:24431,...   d = Kharej listen ports (direct), r = ports Iran listens on during the
#   reverse test. Only ; , : = are used, never '|'. 7/8-field tokens still parse.
# Field 10 (3.5.0, Scepter plan D5) is the pairing capability tier (tunnel|create|manage|full) of a token-bootstrap
# pairing: written only when set, exactly like fields 8/9, so an older parser stops at field 9 and ignores it.
# Owner directive (2026-11-22): the wizards' first mints write pair=full automatically — the engine derives the
# pairing from the token on both ends, Iran's wizard asks nothing extra; a pasted watp1: line stays for explicit/rotate.
make_token() {
  local f; f=$(printf '%s|%s|%s|%s|%s|%s|%s' "${1:-}" "${2:-}" "${3:-}" "${4:-}" "${5:-}" "${6:-}" "${7:-}")
  if [ -n "${10:-}" ]; then f="$f|${8:-}|${9:-}|${10}"; elif [ -n "${9:-}" ]; then f="$f|${8:-}|$9"; elif [ "${8:-}" = 1 ]; then f="$f|1"; fi
  printf 'wat1:%s' "$(printf '%s' "$f" | base64 -w0)"
}
T_CARRIER=''; T_PEER=''; T_KEY=''; T_PATH=''; T_SNI=''; T_ICMP=''; T_PORTS=''; T_REV=''; T_AUTO=''; T_PAIR=''
T_LEG_C=(); T_LEG_P=() # a bond token's per-leg endpoints (parallel to the carrier list; see token_bond_legs)
read_token() { # token -> T_CARRIER T_PEER T_KEY T_PATH T_SNI T_ICMP T_PORTS T_REV T_AUTO T_PAIR
  local raw
  T_CARRIER=''; T_PEER=''; T_KEY=''; T_PATH=''; T_SNI=''; T_ICMP=''; T_PORTS=''; T_REV=''; T_AUTO=''; T_PAIR=''
  [[ "$1" == wat1:* ]] || return 1
  raw=$(printf '%s' "${1#wat1:}" | base64 -d 2>/dev/null) || return 1
  IFS='|' read -r T_CARRIER T_PEER T_KEY T_PATH T_SNI T_ICMP T_PORTS T_REV T_AUTO T_PAIR <<<"$raw"
  [ -n "$T_CARRIER" ] && [ -n "$T_PEER" ] && [ -n "$T_KEY" ]
}
is_reverse() { [ "$(cfg "$1" reverse)" = true ]; }

# The server that RECEIVES the tunnel's ICMP requests (Iran in reverse, Kharej in normal mode, echo/timestamp types):
# Linux answers every one with its own full-size copy, which doubles that server's ICMP upload (and, on Kharej, the
# ICMP volume the route sees, which has a ~30 MB/s reroute trigger). Rate-limiting the kernel's echo and timestamp
# replies (icmp_ratemask bits 0 and 14, 10 per second per sender) drops those copies and keeps ordinary pings
# answered. The tunnel's replies are raw-socket sends and are not limited. Measured on the real path: without it
# OutEchoReps = 2 x InEchos. The old values are kept and restored when the last such tunnel is gone (Kharej: 3.0.0).
KREPLY_CONF=/etc/sysctl.d/90-$WAT_PREFIX-reverse.conf
kreply_on() { [ -f "$KREPLY_CONF" ]; }
kreply_apply() {
  local mask lim
  mask=$(sysctl -n net.ipv4.icmp_ratemask 2>/dev/null) && lim=$(sysctl -n net.ipv4.icmp_ratelimit 2>/dev/null) || return 1
  [ -f "$CONF/.kreply.orig" ] || printf 'net.ipv4.icmp_ratemask = %s\nnet.ipv4.icmp_ratelimit = %s\n' "$mask" "$lim" >"$CONF/.kreply.orig"
  {
    echo "# wattun-manager: this server receives ICMP tunnel requests. The kernel's ping replies are rate-limited so it"
    echo "# stops sending a copy of every tunnel packet. Removed when no such tunnel is left."
    echo "net.ipv4.icmp_ratemask = $((mask | 1 | 16384))"
    echo "net.ipv4.icmp_ratelimit = 100"
  } >"$KREPLY_CONF"
  sysctl -q -p "$KREPLY_CONF" >/dev/null
}
kreply_restore() {
  [ -f "$KREPLY_CONF" ] || return 0
  rm -f "$KREPLY_CONF"
  [ -f "$CONF/.kreply.orig" ] && sysctl -q -p "$CONF/.kreply.orig" >/dev/null && rm -f "$CONF/.kreply.orig"
  ok "Restored the kernel's normal ping replies (no ICMP tunnel that needs it is left)."
}
kreply_wanted() { # name : this tunnel receives ICMP requests that the kernel would answer too
  case "+$(cfg "$1" carrier)+" in *+icmp+*) ;; *) return 1 ;; esac
  case "$(cfg "$1" icmp-type)" in ''|echo|timestamp) ;; *) return 1 ;; esac # info/mask: Linux does not answer
  if [ "$(role "$1")" = Iran ]; then is_reverse "$1"; else ! is_reverse "$1"; fi
}
kreply_users_left() {
  local n
  for n in $(tunnels); do kreply_wanted "$n" && return 0; done
  return 1
}
kreply_needed() { ! kreply_on && [ "$(sysctl -n net.ipv4.icmp_echo_ignore_all 2>/dev/null)" != 1 ]; }
kreply_offer() {
  kreply_needed || return 0
  hint "Linux here also answers every tunnel packet with a full-size copy, doubling this server's ICMP upload."
  [ "$SANDBOX" = 1 ] && warn "Sandbox: this changes GLOBAL kernel settings (net.ipv4.icmp_ratemask |= 16385, icmp_ratelimit = 100) via $KREPLY_CONF; original values saved in $CONF/.kreply.orig."
  step "Limiting the kernel's ping replies (normal pings keep working)" kreply_apply \
    && hint "Undo: remove $KREPLY_CONF and run: sysctl --system (it is also undone when the last reverse the entry tunnel is deleted)."
  return 0
}
refresh_token() { # name [fortress] : keep NAME.token in step with NAME.yml — the allowed ports always, and for a bonded
  # Kharej config (arm-blackout Fortress mode, M1 2026-11-18) also the finalized carrier list, one endpoint per
  # leg and the path, so the emergency token never carries the single-carrier tunnel that was armed over.
  local f="$CONF/$1.token" allow cr bp changed=0 tmp
  [ -f "$f" ] && read_token "$(cat "$f")" || return 0
  load_maps "$1"; allow=$(maps_allow_str)
  [ -f "$CONF/$1-r.yml" ] && is_auto_kharej "$1" && write_ports "$1-r" # the auto reverse companion allows the same ports
  cr=$T_CARRIER; bp=$T_PEER
  [ "$allow" = "$T_PORTS" ] || changed=1
  # an auto Kharej also lists every carrier (icmp+udp+...), but its token is the auto plan Iran tests: only
  # arm-blackout (second arg "fortress") turns it into a bond token (3.4.3; before, opening the token page did)
  if [ "$(role "$1")" = Kharej ] && [ "$T_REV" != 1 ] && { [ "$T_CARRIER" != auto ] || [ "${2:-}" = fortress ]; }; then
    local cc; cc=$(cfg "$1" carrier)
    if [[ "$cc" == *+* ]]; then
      cr=$cc
      split_hp "${T_PEER%%,*}" # the dial host is the old token's first endpoint, without its stale port
      bp=$(bond_peer_field "$1" "$HP_HOST")
      { [ "$cr" = "$T_CARRIER" ] && [ "$bp" = "$T_PEER" ]; } || changed=1
      # the bond finalized path/sni/icmp-type too (arm-blackout writes a fresh path); carry them, not pre-arming values
      [ "$(cfg "$1" path)" = "$T_PATH" ] || { T_PATH=$(cfg "$1" path); changed=1; }
      [ "$(cfg "$1" sni)" = "$T_SNI" ] || { T_SNI=$(cfg "$1" sni); changed=1; }
      [ "$(cfg "$1" icmp-type)" = "$T_ICMP" ] || { T_ICMP=$(cfg "$1" icmp-type); changed=1; }
      [ -z "$T_AUTO" ] || { T_AUTO=''; changed=1; } # a fortress token is not an auto plan
    fi
  fi
  [ "$changed" = 0 ] && return 0
  tmp=$(mktemp "$CONF/.tmp.XXXXXX") || return 1
  ( umask 077; make_token "$cr" "$bp" "$T_KEY" "$T_PATH" "$T_SNI" "$T_ICMP" "$allow" "$T_REV" "$T_AUTO" "$T_PAIR" >"$tmp" )
  wmv "$tmp" "$f"
}
# M1 (2026-11-18): a bonded Kharej config listens on one port per leg (listen-<carrier>:), so its token carries
# one endpoint per leg in field 2, comma separated in the carrier list's order; bare-carrier legs (icmp, gre,
# ipip, raw shapes) dial a bare address and stay port-less. read_token needs no change (no '|' is introduced);
# the Iran side splits the list back into per-leg peer-<carrier>: keys (token_bond_legs). A single-carrier
# token keeps the plain host:port form, so old tokens and old managers still interoperate.
bond_peer_field() { # name host -> comma-separated per-leg endpoints for a bonded config, in carrier order
  local c port entry out='' base
  base=$(cfg "$1" listen); base=${base##*:}; [[ "$base" =~ ^[0-9]+$ ]] || base='' # legs without their own key
  for c in $(cfg "$1" carrier | tr '+' ' '); do
    port=''; carrier_has_listen "$c" || { out="${out:+$out,}$(join_hp "$2" '')"; continue; }
    port=$(cfg "$1" "listen-$c"); port=${port##*:}; [[ "$port" =~ ^[0-9]+$ ]] || port=$base
    [[ "$port" =~ ^[0-9]+$ ]] || port=''
    out="${out:+$out,}$(join_hp "$2" "$port")"
  done
  printf '%s' "$out"
}
token_bond_legs() { # T_CARRIER (a bond) + T_PEER -> T_LEG_C/T_LEG_P arrays; T_PEER becomes the first leg's entry
  T_LEG_C=(); T_LEG_P=()
  { [[ "$T_CARRIER" == *+* ]] && [[ "$T_PEER" == *,* ]]; } || return 0 # an older manager's bond token has one endpoint for every leg
  local -a cs ps
  IFS='+' read -ra cs <<<"$T_CARRIER"
  IFS=',' read -ra ps <<<"$T_PEER"
  if [ "${#ps[@]}" -ne "${#cs[@]}" ]; then
    err "This token lists ${#ps[@]} endpoints for ${#cs[@]} carriers; it is damaged or hand-made."
    return 1
  fi
  local i
  for ((i=0; i<${#cs[@]}; i++)); do
    [ -n "${ps[$i]}" ] || { err "This token has an empty endpoint for carrier '${cs[$i]}'."; return 1; }
    T_LEG_C+=("${cs[$i]}"); T_LEG_P+=("${ps[$i]}")
  done
  T_PEER=${T_LEG_P[0]}
  return 0
}

# ======================================================================================
#  Scepter pairing (3.5.0, Phase A; plan D3/D4/D5/D6): the pairing credential is
#  {pairing UUID, 32-byte key, capability tier, version}. Iran consumes a watp1:
#  line (UNWRAPPED, plan D5 literal text, matching the engine parser and the Go
#  manager):
#     watp1:1|<36-char pairing UUID>|<base64 of exactly 32 bytes>|<capability>
#  The classic token's optional field 10 carries the same capability for a
#  token-bootstrap pairing (see make_token). Capability tiers (D4):
#     tunnel < create < manage < full
#  Store format (F1-B, 2026-11-22) — $CONF/.pairing, written 0600:
#     line 1 is the credential in the ENGINE's format above, because `wattun -pair`
#     (Kharej) and `wattun -pair-to` (Iran) read exactly that one line from the file;
#     the pre-2026112211 manager wrote a key=value file there that the engine cannot
#     parse, so a manager-paired Kharej never armed the channel. `# ` comment lines
#     after line 1 are this manager's bookkeeping (created=, oldkey=,
#     oldkey_expires=) and are ignored by the engine (the engine takes the first watp1:
#     line and skips blank/# lines; the pre-fix engine, which parses the whole file as
#     one line, was updated together with this manager). The old key=value store still
#     parses for READING; nothing writes that shape any more.
#     for READING; nothing writes that shape any more.
#  Hidden infrastructure: the store and the audit log are dotfiles, never *.yml
#  tunnels, so tunnels()/listed_tunnels()/dashboards can never list them (the
#  scepter latch follows the same rule on the engine side). Both ends need 3.5.0
#  for every Scepter feature; the manager here is Kharej's LOCAL console only
#  (Phase B.3 parity decision: cockpit features live in the Go manager/panel).
# ======================================================================================
PAIR_CAPS='tunnel create manage full'
# Token-bootstrap pairing is the default shape now (owner directive 2026-11-22:
# zero extra manual steps — the wizard's first mint embeds field 10 pair=full and
# the engine derives the pairing from it; a pasted watp1: line stays available for
# explicit/rotate flows on Kharej's console). The default tier rides T_PAIR:
# a first mint writes "full" unless an expert row/flag preset a tier.
SCEPTER_DEFAULT_TIER=full
# The scepter latch listener's default port (owner directive 2026-11-22: a
# manager-made Kharej tunnel carries latch-port without asking). 20443 sits in
# the manager's reserved 20400-20999 band — free_metrics_port and the probe
# ports never land there — so the latch cannot collide with either.
SCEPTER_LATCH_DEFAULT=20443
pick_latch_port() { # [exclude...] : latch-port for a new Kharej tunnel; 20443 unless this
  # tunnel's picked ports or another listener on this server holds it (scan up to 20499, then give up: the
  # engine's key-derived default applies when the yml carries no latch-port)
  local p=$SCEPTER_LATCH_DEFAULT e
  while [ "$p" -le 20499 ]; do
    for e in "$@"; do [ "$e" = "$p" ] && { p=$((p+1)); continue 2; }; done
    if ! listen_blocked tcp "$p"; then echo "$p"; return 0; fi
    p=$((p+1))
  done
  return 1
}
PAIR_STORE=$CONF/.pairing
PAIR_AUDIT=$CONF/.pairing.audit
pair_caps_ok() { case " $PAIR_CAPS " in *" ${1:-} "*) return 0 ;; esac; return 1; }
v_pair_caps() { pair_caps_ok "$1" && return 0; err "Use a capability tier: $PAIR_CAPS."; return 1; }
v_pair_uuid() {
  [[ "$1" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]] && return 0
  err "Enter the pairing UUID exactly as printed (36 characters, dashes included)."; return 1
}
new_pair_uuid() {
  local u
  u=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen 2>/dev/null) || u=''
  if [ -z "$u" ]; then # no kernel uuidgen on this host: fold 16 random bytes into the same shape
    u=$(head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \n' | sed 's/\(.\{8\}\)\(.\{4\}\)\(.\{4\}\)\(.\{4\}\)\(.\{12\}\)/\1-\2-\3-\4-\5/')
  fi
  printf '%s\n' "${u,,}"
}
new_pair_key() { head -c 32 /dev/urandom | base64 -w0; } # the D5 credential: base64 of exactly 32 bytes
P_VERSION=''; P_UUID=''; P_KEY=''; P_CAPS=''; P_CREATED=''; P_OLDKEY=''; P_OLDKEY_EXP=''
# The watp1: line is UNWRAPPED (plan D5 literal text; matches the engine parser committed in d354660 and the Go
# manager): watp1:<version>|<pairing UUID>|<base64 32-byte key>|<capability> — no outer base64 of the payload.
make_pairing() { # version uuid key caps -> watp1: line (pure; field order is the wire format, D5)
  printf 'watp1:%s|%s|%s|%s' "${1:-}" "${2:-}" "${3:-}" "${4:-}"
}
read_pairing() { # line -> P_VERSION P_UUID P_KEY P_CAPS ; rc 1 + its own error on a bad line
  P_VERSION=''; P_UUID=''; P_KEY=''; P_CAPS=''
  local klen
  [[ "$1" == watp1:* ]] || { err "A pairing line starts with watp1: (a tunnel token starts with wat1:)."; return 1; }
  IFS='|' read -r P_VERSION P_UUID P_KEY P_CAPS <<<"${1#watp1:}"
  [ "$P_VERSION" = 1 ] || { err "Pairing format version '${P_VERSION:-?}' is not known here (this manager speaks version 1)."; return 1; }
  v_pair_uuid "$P_UUID" || return 1
  if ! [[ "$P_KEY" =~ ^[A-Za-z0-9+/=]+$ ]] \
     || { klen=$(printf '%s' "$P_KEY" | base64 -d 2>/dev/null | wc -c | tr -d ' '); [ "$klen" != 32 ]; }; then
    err "The pairing key must be base64 decoding to exactly 32 bytes."; return 1
  fi
  v_pair_caps "$P_CAPS" || return 1
}
v_pairing() { read_pairing "$1"; }
pairing_load() { # $PAIR_STORE -> P_VERSION P_UUID P_KEY P_CAPS P_CREATED P_OLDKEY P_OLDKEY_EXP
  # rc 0 = parsed, 1 = the file exists but holds nothing parsable, 2 = no store. Lenient on purpose:
  # the engine owns the credential's shape, and refusing a store the engine accepts would lock this
  # console out of a future format; only a store with no uuid/key/caps at all counts as unreadable.
  P_VERSION=''; P_UUID=''; P_KEY=''; P_CAPS=''; P_CREATED=''; P_OLDKEY=''; P_OLDKEY_EXP=''
  [ -f "$PAIR_STORE" ] || return 2
  local line k v
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      watp1:*) # the engine's credential line (line 1; a stray further one is ignored)
        [ -n "$P_UUID" ] && continue
        line=${line%$'\r'} # a CRLF-edited store must not bake \r into the caps field (round-2)
        IFS='|' read -r P_VERSION P_UUID P_KEY P_CAPS <<<"${line#watp1:}" ;;
      \#*) # bookkeeping comments written by pairing_store_write: created=, oldkey=, oldkey_expires=
        k=${line#'#'}; k=${k# }; k=${k%%=*}; v=${line#*=}
        case "$k" in
          created) [ -n "$P_CREATED" ] || P_CREATED=$v ;;
          oldkey) [ -n "$P_OLDKEY" ] || P_OLDKEY=$v ;;
          oldkey_expires) [ -n "$P_OLDKEY_EXP" ] || P_OLDKEY_EXP=$v ;;
        esac ;;
      *) # the pre-2026112211 manager's key=value store: read-only compat, never written again
        k=${line%%=*}; v=${line#*=}
        case "$k" in
          version) P_VERSION=$v ;;
          uuid) [ -n "$P_UUID" ] || P_UUID=$v ;;
          key) [ -n "$P_KEY" ] || P_KEY=$v ;;
          caps) [ -n "$P_CAPS" ] || P_CAPS=$v ;;
          created) [ -n "$P_CREATED" ] || P_CREATED=$v ;;
          oldkey) [ -n "$P_OLDKEY" ] || P_OLDKEY=$v ;;
          oldkey_expires) [ -n "$P_OLDKEY_EXP" ] || P_OLDKEY_EXP=$v ;;
        esac ;;
    esac
  done <"$PAIR_STORE"
  { [ -n "$P_UUID" ] && [ -n "$P_KEY" ] && [ -n "$P_CAPS" ]; } || return 1
  return 0
}
pairing_get() { # field -> value ('' when absent, or there is no store, or it cannot be parsed)
  pairing_load
  case "$1" in
    version) printf '%s' "${P_VERSION:-}" ;;
    uuid) printf '%s' "$P_UUID" ;;
    key) printf '%s' "$P_KEY" ;;
    caps) printf '%s' "$P_CAPS" ;;
    created) printf '%s' "$P_CREATED" ;;
    oldkey) printf '%s' "$P_OLDKEY" ;;
    oldkey_expires) printf '%s' "$P_OLDKEY_EXP" ;;
  esac
  return 0
}
pairing_revoked() { # Handoff 4 R3: the store is a revoke tombstone (first non-comment line "revoked ...")
  [ -f "$PAIR_STORE" ] && grep -v '^#' "$PAIR_STORE" | grep -m1 . | grep -q '^revoked'
}
pairing_active() { [ -f "$PAIR_STORE" ] && ! pairing_revoked; }
pairing_check_readable() { # refuse to touch a store this manager cannot parse: it may be a newer engine's
  # format holding the only copy of the credential, and pair/rotate/revoke would destroy it (F1-B, 2026-11-22)
  [ -f "$PAIR_STORE" ] || return 0
  pairing_revoked && return 0
  pairing_load && return 0
  err "$PAIR_STORE exists but this manager cannot read it; nothing was changed."
  hint "Pair or rotate with the engine (wattun -pair) or delete the file by hand, then try again."
  return 1
}
pairing_store_write() { # uuid key caps [oldkey oldkey-expires-epoch] : the whole store, atomically (tmp+rename, 0600)
  # Line 1 is the credential in the ENGINE's format — `wattun -pair` reads exactly that line and cannot
  # parse anything else (F1-B); the `# ` lines carry this manager's bookkeeping and the engine skips them.
  local tmp old created
  mkdir -p "$CONF"
  created=$(pairing_get created); [ -n "$created" ] || created=$(date +%s) # a rotation keeps the original creation time
  old=$(umask); umask 077
  tmp=$(mktemp "$CONF/.tmp.XXXXXX") || { umask "$old"; return 1; }
  {
    make_pairing 1 "$1" "$2" "$3"; echo
    echo "# created=$created"
    if [ -n "${4:-}" ]; then echo "# oldkey=$4"; echo "# oldkey_expires=$5"; fi # the 24 h rotation window (plan D-rotation)
  } >"$tmp" || { rm -f "$tmp"; umask "$old"; return 1; }
  chmod 600 "$tmp"; mv -f "$tmp" "$PAIR_STORE"; umask "$old"
}
pairing_audit() { # event detail : append one line, never rewrite the file
  # Append-only for real (F5, 2026-11-22): the ENGINE appends audit records with open-append-close per
  # entry, so the old cat->tmp->mv rewrite dropped anything appended in the read->rename window (the
  # engine kept writing the renamed-away inode). One small O_APPEND write is atomic enough on a regular
  # file; a missing file is created 0600 via umask (>> never truncates an existing one). A failed append
  # returns 1 with its own error — an unaudited pairing change must not look like success (round-2).
  local f="$PAIR_AUDIT" old
  mkdir -p "$CONF"
  old=$(umask); umask 077
  if ! printf '%s %s %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$1" "$2" >>"$f"; then
    umask "$old"
    err "Could not append to $PAIR_AUDIT — the audit line was NOT recorded."
    return 1
  fi
  umask "$old"
  return 0
}
pairing_audit_tail() { # [n=20]
  [ -f "$PAIR_AUDIT" ] || { hint "No pairing audit entries yet."; return 0; }
  tail -n "${1:-20}" "$PAIR_AUDIT"
}
pairing_status() {
  local caps created exp left
  if pairing_revoked; then
    say "  $(kv pairing "${RED}revoked${RST} ${GRY}(no Iran can manage this server; o = allow a new Iran)${RST}")"
    return 0
  fi
  if ! pairing_active; then
    say "  $(kv pairing "${GRY}waiting${RST} ${GRY}(the first updated Iran tunnel that connects pairs itself, old tokens too)${RST}")"
    return 0
  fi
  if ! pairing_load; then
    say "  $(kv pairing "${YEL}unreadable${RST} ${GRY}($PAIR_STORE is not a format this manager reads)${RST}")"
    return 0
  fi
  caps=$P_CAPS
  if grep -q '^# claimed' "$PAIR_STORE"; then say "  $(kv pairing "${GRN}paired with an Iran${RST}")"
  else say "  $(kv pairing "${GRN}on${RST}")"; fi
  say "  $(kv uuid "$P_UUID")"
  say "  $(kv caps "$caps")"
  created=$P_CREATED
  [ -n "$created" ] && say "  $(kv created "$(date -u -d "@$created" '+%Y-%m-%d %H:%M UTC' 2>/dev/null || echo "$created")")"
  exp=$P_OLDKEY_EXP
  if [ -n "$P_OLDKEY" ] && [ -n "$exp" ]; then
    left=$(( exp - $(date +%s) ))
    # "the old key is accepted" was a lie: the engine takes only the current credential — the old
    # line sits in the store as reference for the rotation window (round-2, 2026-11-22).
    if [ "$left" -gt 0 ]; then say "  $(kv rotation "${YEL}the old line is kept for reference; attach the new line on Iran now — window ${left}s${RST}")"
    else say "  $(kv rotation "${GRY}old key expired${RST}")"; fi
  fi
  return 0
}
scepter_kharej_only() { # F1-C (2026-11-22): pair/rotate/revoke write Kharej's SERVER-side credential.
  # On Iran the same path ($CONF/.pairing) holds the CLIENT credential written by `wattun -pair-to`;
  # rewriting it here would desync the pair, so Iran only reads (status/audit) and pairs from the Go
  # cockpit. Refusing on an explicit Iran side only: side is saved at install/first tunnel, and an
  # undetermined side must not lock Kharej's first pairing out.
  [ "$(server_side)" = iran ] || return 0
  err "This is the exit-side action; the entry server's pairing is managed by the Go cockpit (wattun -pair-to)."
  return 1
}
scepter_pair() { # generate (or adopt a pasted watp1: line) and store the pairing; prints the line for Iran
  local line uuid key caps
  scepter_kharej_only || return 1
  pairing_check_readable || return 1
  if pairing_active; then
    confirm "A pairing already exists ($(pairing_get uuid)). Replace it? The entry server must be given the new line." n || return 0
  fi
  ask "Paste a watp1: line (Enter = generate a fresh pairing here)" ""
  line=$REPLY_V
  if [ -n "$line" ]; then
    read_pairing "$line" || return 1
    uuid=$P_UUID; key=$P_KEY; caps=$P_CAPS
  else
    uuid=$(new_pair_uuid); key=$(new_pair_key); caps=full
    ask_ok "Capability tier ($PAIR_CAPS)" "$caps" v_pair_caps || return 1; caps=$REPLY_V
  fi
  pairing_store_write "$uuid" "$key" "$caps" || { err "Could not write $PAIR_STORE."; return 1; }
  pairing_audit pair_created "$uuid caps=$caps"
  ok "Pairing stored ($uuid, caps $caps)."
  echo
  printf '  %s%s%s\n\n' "$BOLD$YEL" "$(make_pairing 1 "$uuid" "$key" "$caps")" "$RST"
  hint "Give this watp1: line to the entry server (pairs the cockpit; wattun 3.5.0 on both ends)."
  return 0
}
scepter_rotate() { # [window_secs=86400] : new key; the window (default 24 h) is bookkeeping that reminds
  # you to re-attach the new watp1: line on Iran BEFORE rotating - the engine accepts only the current
  # credential and reloads within the poll interval once the store changes (TECHNICAL.md accepted limits)
  local win=${1:-86400} uuid caps key nk
  case "$win" in ''|*[!0-9]*) err "The rotation window is a number of seconds."; return 1 ;; esac
  scepter_kharej_only || return 1
  pairing_active || { err "No pairing to rotate (pair first)."; return 1; }
  pairing_check_readable || return 1
  pairing_load || return 1 # check_readable just proved the store parses; belt and braces
  uuid=$P_UUID; caps=$P_CAPS; key=$P_KEY
  nk=$(new_pair_key)
  pairing_store_write "$uuid" "$nk" "$caps" "$key" "$(( $(date +%s) + win ))" || { err "Could not write $PAIR_STORE."; return 1; }
  pairing_audit pair_rotated "$uuid window=${win}s"
  ok "Pairing key rotated; the engine switches to the new key within its poll interval."
  echo
  printf '  %s%s%s\n\n' "$BOLD$YEL" "$(make_pairing 1 "$uuid" "$nk" "$caps")" "$RST"
  hint "Attach this new watp1: line on the entry server NOW (rotation takes effect at the next store poll)."
  return 0
}
scepter_revoke() { # revoke = a tombstone (Handoff 4 R3): a deleted store would let a token-paired unit
  # re-derive the pairing at its next start; the tombstone keeps every unit unpaired, token or not.
  # Tunnels keep running (plan D3).
  local id tmp old
  scepter_kharej_only || return 1
  pairing_revoked && { err "The pairing is already revoked (o = allow a new entry server)."; return 1; }
  pairing_check_readable || return 1
  id=$(pairing_get uuid); [ -n "$id" ] || id=token
  if [ "$NONINTERACTIVE" = 1 ]; then
    [ "${NI_YES:-0}" = 1 ] || { err "scepter revoke without a terminal needs --yes"; return 1; }
  else
    confirm "Revoke the pairing? No entry server can manage this server until you allow a new one; tunnels keep running." n || return 0
  fi
  pairing_audit pair_revoked "$id" || return 1
  mkdir -p "$CONF"
  old=$(umask); umask 077
  tmp=$(mktemp "$CONF/.tmp.XXXXXX") || { umask "$old"; return 1; }
  printf 'revoked %s %s\n' "$id" "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" >"$tmp" && chmod 600 "$tmp" && mv -f "$tmp" "$PAIR_STORE"
  umask "$old"
  ok "Pairing revoked. The audit log is kept in $PAIR_AUDIT."
  return 0
}
scepter_reopen() { # Handoff 4 R2: delete the store - the next Iran that connects with a pairing token pairs itself
  scepter_kharej_only || return 1
  [ -f "$PAIR_STORE" ] || { hint "Nothing to do: no entry server is paired yet, the next one to connect pairs itself."; return 0; }
  pairing_check_readable || return 1
  if [ "$NONINTERACTIVE" = 1 ]; then
    [ "${NI_YES:-0}" = 1 ] || { err "scepter reopen without a terminal needs --yes"; return 1; }
  else
    confirm "Allow a new entry server to pair? The current pairing ends; the next entry server that connects takes over." n || return 0
  fi
  pairing_audit pair_reopened "$(pairing_get uuid)" || return 1
  rm -f "$PAIR_STORE"
  ok "Pairing open: the next entry server that connects to this server pairs itself."
  return 0
}
scepter_menu() { # Kharej's local Scepter console: status, pair, rotate, revoke, audit tail.
  # F1-C: on Iran the console is read-only (status/audit) — Iran's credential is the client side,
  # written by `wattun -pair-to`, and pair/rotate/revoke here would overwrite it.
  local sd; sd=$(server_side)
  if [ "$sd" = iran ]; then
    while :; do
      page "Pairing" "Entry server · read-only"
      pairing_status
      echo
      hint "Pairing is managed on the exit server; this server pairs by itself when its tunnel connects."
      menu_line a 'audit tail' 0 back
      key_read
      case "$KEY" in
        a|A) echo; pairing_audit_tail 20; pause ;;
        b|0|q|enter|esc) return 0 ;;
      esac
    done
  fi
  while :; do
    page "Pairing" "which entry server manages this server"
    pairing_status
    echo
    menu_line o 'allow a new entry server' x 'revoke' r rotate p 'pair by hand' a 'audit tail' 0 back
    key_read
    case "$KEY" in
      p|P) echo; scepter_pair; pause ;;
      r|R) echo; scepter_rotate; pause ;;
      x|X) echo; scepter_revoke; pause ;;
      o|O) echo; scepter_reopen; pause ;;
      a|A) echo; pairing_audit_tail 20; pause ;;
      b|0|q|enter|esc) return 0 ;;
    esac
  done
}
scepter_cmd() { # status|pair|rotate [secs]|revoke|audit [n]
  case "${1:-status}" in
    status) pairing_status ;;
    pair) scepter_pair ;;
    rotate) scepter_rotate "${2:-86400}" ;;
    revoke|unpair) scepter_revoke ;;
    reopen|allow) scepter_reopen ;;
    audit) pairing_audit_tail "${2:-20}" ;;
    *) err "scepter: use status, pair, rotate, revoke, reopen or audit."; return 1 ;;
  esac
}

# ---- cross-tunnel conflict checks ----
tunnel_using_public() { # port proto [exclude] -> name of another Iran tunnel publishing it
  local n it
  for n in $(tunnels); do
    [ "$n" = "${3:-}" ] && continue
    [ "$(role "$n")" = Iran ] || continue
    while IFS= read -r it; do
      [ -n "$it" ] && [ "$(spec_L "$it")" = "$1" ] && [ "$(spec_P "$it")" = "$2" ] && { echo "$n"; return 0; }
    done < <(yml_maps "$n")
  done
  return 1
}
tunnel_using_listen() { # port [exclude] -> name of a tunnel (Kharej, or Iran in reverse) listening on it
  # every config counts, hidden auto children too, and every listen key: an auto tunnel keeps its ports as
  # listen-<carrier>: lines, and a stopped one still owns them (it starts again on reboot)
  local f n
  for f in "$CONF"/*.yml; do
    [ -e "$f" ] || continue
    n=${f##*/}; n=${n%.yml}
    [ "$n" = "${2:-}" ] && continue
    grep -qE "^listen(-[a-z0-9-]+)?:[[:space:]]*[\"']?[^\"'#]*:$1[\"']?([[:space:]]*(#.*)?)?\$" "$f" && { echo "$n"; return 0; }
  done
  return 1
}
tunnel_using_misc() { # port [exclude] -> name of a tunnel using port for metrics: or dns-listen:
  local f n
  for f in "$CONF"/*.yml; do
    [ -e "$f" ] || continue
    n=${f##*/}; n=${n%.yml}
    [ "$n" = "${2:-}" ] && continue
    grep -qE "^(metrics|dns-listen):[[:space:]]*[\"']?[^\"'#]*:$1[\"']?([[:space:]]*(#.*)?)?\$" "$f" && { echo "$n"; return 0; }
  done
  return 1
}
listen_blocked() { # proto port
  port_busy "$2" "$1" bind || tunnel_using_listen "$2" >/dev/null || tunnel_using_public "$2" "$1" >/dev/null || tunnel_using_misc "$2" >/dev/null
}
listen_conflict_desc() { # proto port -> explanation string
  # A probe unit is hidden machinery (its name is throw-away), so the message
  # names the machine, never the tunnel (round-2, 2026-11-22).
  local proto=${1:-tcp} port=$2
  local tun u
  tun=$(tunnel_using_listen "$port")
  if [ -n "$tun" ]; then
    if is_probe_unit "$tun"; then echo "a scepter probe test unit"; else echo "tunnel '$tun'"; fi
    return
  fi
  tun=$(tunnel_using_public "$port" "$proto")
  if [ -n "$tun" ]; then echo "tunnel '$tun' (public port)"; return; fi
  tun=$(tunnel_using_misc "$port")
  if [ -n "$tun" ]; then
    if is_probe_unit "$tun"; then echo "a scepter probe test unit"; else echo "tunnel '$tun' (local service)"; fi
    return
  fi
  u=$(port_user "$port" "$proto")
  if [ -n "$u" ]; then echo "$u"; return; fi
  echo "another process or tunnel"
}
_rand_u16() { # -> 0..65535
  local v=''
  if [ -r /dev/urandom ] && command -v od >/dev/null 2>&1; then
    v=$(od -An -tu2 -N2 /dev/urandom 2>/dev/null | tr -d '[:space:]')
  fi
  case "$v" in ''|*[!0-9]*) v=$(( (RANDOM << 1) ^ (RANDOM & 1) ^ ($$ & 65535) )) ;; esac
  echo "$v"
}
_port_reserved() { # port [space_sep_exclude] -> 0 when reserved or already chosen in the same plan
  local p=$1 ex=${2:-}
  if [ "$p" -ge 18990 ] && [ "$p" -le 18999 ]; then return 0; fi
  if [ "$p" -ge 19700 ] && [ "$p" -le 20999 ]; then return 0; fi
  case " $ex " in *" $p "*) return 0 ;; esac
  return 1
}
rand_open_port() { # [proto=tcp] [exclude_space_sep] -> prints one free random open port (10000..32767, fallback 40000..60000)
  local proto=${1:-tcp} excl=${2:-} i p start
  # Primary range 10000..32767 avoids well-known/panel ports and stays below Linux's default ephemeral range (32768..60999).
  for ((i=0; i<200; i++)); do
    p=$(( 10000 + ($(_rand_u16) % 22768) ))
    _port_reserved "$p" "$excl" && continue
    listen_blocked "$proto" "$p" && continue
    echo "$p"; return 0
  done
  for ((i=0; i<100; i++)); do
    p=$(( 40000 + ($(_rand_u16) % 20001) ))
    _port_reserved "$p" "$excl" && continue
    listen_blocked "$proto" "$p" && continue
    echo "$p"; return 0
  done
  start=$(( $(_rand_u16) % 22768 ))
  for ((i=0; i<256; i++)); do
    p=$(( 10000 + ((start + i * 103) % 22768) ))
    _port_reserved "$p" "$excl" && continue
    listen_blocked "$proto" "$p" && continue
    echo "$p"; return 0
  done
  return 1
}
CF_HTTPS_PORTS='2053 2083 2087 2096 8443' # Cloudflare-proxied HTTPS ports (never auto-grab 443)
CF_HTTP_PORTS='2052 2082 2086 2095 8880 8080' # Cloudflare-proxied HTTP ports (never auto-grab 80)
CF_ORIGIN_FALLBACK=0
cf_port_ok() { # carrier port -> 0 when port is Cloudflare-proxyable for this carrier
  local c=$1 p=${2:-}
  [ -n "$p" ] || return 1
  case "$c" in
    wss|grpc|h2|tls) case " 443 2053 2083 2087 2096 8443 " in *" $p "*) return 0 ;; esac ;;
    ws|h2c) case " 80 8080 8880 2052 2082 2086 2095 " in *" $p "*) return 0 ;; esac ;;
  esac
  return 1
}
pick_cf_cdn_port() { # carrier [exclude_space_sep] -> free CF port (never 443/80), else rand_open_port + CF_ORIGIN_FALLBACK=1
  local c=$1 excl=${2:-} list p off n i
  local -a pool=()
  CF_ORIGIN_FALLBACK=0
  case "$c" in
    wss|grpc|h2) list=$CF_HTTPS_PORTS ;;
    ws|h2c) list=$CF_HTTP_PORTS ;;
    *) rand_open_port "$(rproto "$c")" "$excl"; return $? ;;
  esac
  for p in $list; do pool+=("$p"); done
  n=${#pool[@]}
  off=$(( $(_rand_u16) % n ))
  for ((i=0; i<n; i++)); do
    p=${pool[$(((off + i) % n))]}
    _port_reserved "$p" "$excl" && continue
    listen_blocked tcp "$p" && continue
    echo "$p"; return 0
  done
  CF_ORIGIN_FALLBACK=1
  rand_open_port tcp "$excl"
}
default_listen() { # carrier [cdn_mode=0] [exclude_space_sep] -> free random open port (or non-443/80 CF port when cdn_mode=1)
  local cr=$1 cdn=${2:-0} excl=${3:-}
  if [ "$cdn" = 1 ] && is_cdn_carrier "$cr"; then
    pick_cf_cdn_port "$cr" "$excl"
    return $?
  fi
  rand_open_port "$(rproto "$cr")" "$excl"
}

# ---- validators (print their own error, rc 1 when bad) ----
# Engine limits, kept next to the validators: a bigger value is refused or silently clamped by the engine
# (maxSessions in cmd/wattun/tunnel.go, poolMaxConns in wat/carrier_tcp.go, MinPayload/MaxPayloadHi and
# poolMaxMTU in wat/session.go + wat/carrier_tcp.go), so the manager refuses it with the real limit instead.
ENG_MAX_SESSIONS=16   # maxSessions: -sessions 1..16 (a client of one pool carrier only)
ENG_MAX_CONNS=64      # poolMaxConns: -conns is clamped to 64 per pool
ENG_MTU_MIN=256       # MinPayload: the smallest datagram the engine accepts
ENG_MTU_MAX=1400      # MaxPayloadHi: icmp/udp/gre/ipip (and any bond with one) cap -mtu here
ENG_MTU_MAX_POOL=16384 # poolMaxMTU: a tcp/tls/ws/wss/h2/h2c/grpc carrier frames up to this
# A5 (2026-11-04): stable-but-rare engine keys that stay file-only on purpose (no UI: they are set once by an expert,
# or matter only to one debugging scenario). Listed in one place, shown in the Advanced page's help line, and checked by
# test-manager's coverage test, so a new engine flag cannot silently lack a manager path.
#   debug/ping-every/udp-idle/tcp-cc/slack-ms/hedge/lanes/mem-budget/plain: diagnostics and hand-tuned internals
#   port-offset: the "second slot" of a one-server handover, set by the installer docs
#   tls-cert/tls-key: a custom certificate pair for the tls carrier (self-signed is the default)
#   header: extra request headers for the ws/wss/h2/h2c/grpc carriers (repeatable; flag.Func, no UI row)
#   keep-slow/tls-small-ch/hdr-mask/tcp-mimic/tls-pin/fake-ip/fake-split: anti-censor/diagnostic file-only keys
#   legacy-mask-flip: joins a pre-3.0 plain-header peer (3.3.8; default off, the automatic flip was a downgrade)
#   udp-dns-edns: structurally complete udp-dns frames (3.3.8; both ends, opt-in)
#   probe-guard: demand a key-derived token on HTTP-family tunnel requests (3.3.8; both ends, opt-in)
#   mtu-adapt: sender-side payload clamp for size-selective loss (3.3.8; single-ended, no wire signal, opt-in)
#   max-sessions/max-conns: denial-of-service caps (server sessions, public connections); the defaults fit (3.3.5)
#   pairing: Scepter pairing attach, Iran side (3.5.0, both ends; the watp1: line or token field 10 carries the credential)
#   pair/pair-to: the one-shot bootstrap forms of the same (engine flags; the manager writes .pairing itself)
#   latch-port/latch-dial: the scepter latch listener and its one-shot contact/drill form (3.5.0, Kharej side; opt-in with a stored pairing)
#   scepter-call/scepter-args: the one-shot write-intent/RPC call form (3.5.0, Iran side; the Go manager shells out to it)
#   panel: runs the web panel from panel.conf (3.6.0), not a tunnel; `wattun panel on` writes its unit
CFG_FILE_ONLY='debug ping-every udp-idle tcp-cc slack-ms hedge lanes mem-budget plain port-offset tls-cert tls-key header keep-slow tls-small-ch hdr-mask legacy-mask-flip udp-dns-edns probe-guard mtu-adapt tcp-mimic tls-pin fake-ip fake-split max-sessions max-conns decoy repair fast-rtx burst-cap rate-tune ptcp-hop spray-hop pair pair-to pairing latch-port latch-dial scepter-call scepter-args update-job scepter-deny-ports panel bond-switch-after bond-cooldown'
# The server's target-port allowlist (-allow-min/-allow-max/-allow-ports/-allow-file) is reachable through the wizard's
# ports:/allowed-ports editor instead of separate rows: same data, one code path. The coverage test excludes these four.
CFG_PORTS_UI='allow-min allow-max allow-ports allow-file'
mtu_max_for() { # carrier list -> largest mtu the engine will not clamp for it (a bond merges to its smallest leg)
  local c hi leg
  [ -n "$1" ] || { echo "$ENG_MTU_MAX"; return 0; }
  hi=$ENG_MTU_MAX_POOL
  for c in ${1//+/ }; do
    case "$c" in tcp|tls|ws|wss|h2|h2c|grpc) leg=$ENG_MTU_MAX_POOL ;; *) leg=$ENG_MTU_MAX ;; esac
    leg=$(shaped_raw_mtu "$c" "$leg") # F19 raw shapes: 1400 minus their IP protocol header (M1/M15)
    leg=$(shaped_udp_mtu "$c" "$leg") # F19 UDP shapes carry a fixed header: their ceiling is below 1400
    [ "$leg" -lt "$hi" ] && hi=$leg
  done
  echo "$hi"
}
sessions_carrier_ok() { # carrier list -> 0 when the engine accepts -sessions > 1 (one udp/pool carrier, not a bond)
  case "${1:-}" in *+*) return 1 ;; esac
  case "${1:-}" in udp|tcp|tls|ws|wss|h2|h2c|grpc) return 0 ;; esac
  return 1
}
v_port() { [[ "$1" =~ ^[0-9]{1,5}$ ]] && [ "$((10#$1))" -ge 1 ] && [ "$((10#$1))" -le 65535 ] && return 0; err "Enter a port between 1 and 65535."; return 1; }
v_name() {
  [[ "$1" =~ ^[a-zA-Z0-9_-]{1,32}$ ]] || { err "Use 1-32 letters, digits, - or _."; return 1; }
  [ ! -e "$CONF/$1.yml" ] || { err "A tunnel named '$1' already exists."; return 1; }
}
HP_HOST=''; HP_PORT=''
split_hp() { # addr -> HP_HOST (unbracketed) and HP_PORT (empty when bare host / bare IPv6 / [ipv6])
  local a=${1:-}
  HP_HOST=''; HP_PORT=''
  if [[ "$a" =~ ^\[([^\]]+)\]:([0-9]+)$ ]]; then HP_HOST=${BASH_REMATCH[1]}; HP_PORT=${BASH_REMATCH[2]}
  elif [[ "$a" =~ ^\[([^\]]+)\]$ ]]; then HP_HOST=${BASH_REMATCH[1]}
  elif ipv6_ok "$a"; then HP_HOST=$a
  elif [[ "$a" == *:* ]] && [[ "$a" != *:*:* ]]; then HP_HOST=${a%:*}; HP_PORT=${a##*:}
  else HP_HOST=$a; fi
}
join_hp() { # host [port] -> host:port or [ipv6]:port (bare host when port is empty)
  local h=${1:-} p=${2:-}
  h=${h#[}; h=${h%]}
  [ -n "$p" ] || { printf '%s' "$h"; return 0; }
  if [[ "$h" == *:* ]]; then printf '[%s]:%s' "$h" "$p"; else printf '%s:%s' "$h" "$p"; fi
}
v_ip() {
  local h=${1:-}; h=${h#[}; h=${h%]}
  if ipv4_ok "$h" || ipv6_ok "$h"; then return 0; fi
  err "Enter a valid IPv4 or IPv6 address."; return 1
}
v_host() {
  local a=${1:-}
  [ -n "$a" ] && [ "${#a}" -le 253 ] || { err "Enter an IP address or a domain name."; return 1; }
  split_hp "$a"
  if [[ "$a" != \[*\]:* ]] && [[ "$a" != \[*\] ]] && [[ "$a" == *:* ]] && [ -z "$HP_PORT" ]; then
    ipv6_ok "$HP_HOST" || { err "Enter an IP address or a domain name."; return 1; }
  fi
  if [ -n "$HP_PORT" ]; then v_port "$HP_PORT" >/dev/null 2>&1 || { err "Enter an IP address or a domain name."; return 1; }; fi
  if ipv4_ok "$HP_HOST" || ipv6_ok "$HP_HOST" || [[ "$HP_HOST" =~ ^[A-Za-z0-9._-]{1,253}$ ]]; then return 0; fi
  err "Enter an IP address or a domain name."; return 1
}
v_ipv4() { [[ "$1" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] && return 0; err "Enter the server's IPv4 address, such as 198.51.100.20."; return 1; }
is_pool() { case "$1" in tcp|tls|ws|wss|h2|h2c|grpc|tcp-rev|tls-rev|ws-rev|wss-rev|h2-rev|h2c-rev|grpc-rev) return 0 ;; esac; return 1; }
is_pool_list() { local c; for c in ${1//+/ }; do is_pool "$c" && return 0; done; return 1; }
has_ech_list() { local c; for c in ${1//+/ }; do case "$c" in tls|wss|h2|grpc) return 0 ;; esac; done; return 1; }
undisguised_legs() { local c out=''; for c in ${1//+/ }; do is_pool "$c" || out="${out:+$out }$c"; done; echo "$out"; }
carrier_ok() { # single carrier name, including the F19 shaped tier (3.3.0); a bond leg's :up/:down
               # direction suffix (3.3.9) is stripped and the base checked — the bond-level suffix
               # rules (udp-only :down, one leg per direction, bond-only, never shaped) live in v_carrier_list
  case "$1" in *:up|*:down) set -- "${1%:*}" ;; esac
  case "$1" in
    icmp|udp|tcp|tls|ws|wss|h2|h2c|grpc|gre|ipip|ptcp|spray) return 0 ;;
    tcp-rev|tls-rev|ws-rev|wss-rev|h2-rev|h2c-rev|grpc-rev) return 0 ;; # one reverse leg in a bond (4.1.2)
    sit|6to4|xfrm-ipsec|etherip|l2tpv3) return 0 ;;
    fou-gre|gue-ipip|vxlan|geneve|dnscrypt-udp|ntp-direct|openvpn-dco|srtp-direct) return 0 ;;
  esac
  return 1
}
carrier_leg_base() { # bond leg -> carrier name without the :up/:down direction suffix (3.3.9; no suffix = carries both directions)
  case "$1" in *:up|*:down) echo "${1%:*}" ;; *) echo "$1" ;; esac
}
carrier_leg_dir() { # bond leg -> up|down|'' ('' = bidirectional)
  case "$1" in *:up) echo up ;; *:down) echo down ;; *) echo '' ;; esac
}
# B2 (2026-11-04): the oldest engine that can run a carrier at all. Auto itself needs 2.1.0; gre/ipip arrived in 3.2.0;
# the 13 shaped carriers are 3.3.0-only on both ends; a :up/:down directional leg signals itself with the frEndpoint
# frame (0x0e), so both ends need the release that speaks it (3.3.9, wat/version.go). Used by the Kharej plan writer
# and the Iran variant builder, so an old engine never receives a carrier it cannot start or test.
carrier_min_ver() {
  case "$1" in
    *-rev|*-rev:up|*-rev:down) echo 4.1.2 ;;
    *:up|*:down) echo 3.3.9 ;;
    gre|ipip) echo 3.2.0 ;;
    ptcp|spray) echo 3.4.3 ;;
    sit|6to4|xfrm-ipsec|etherip|l2tpv3|fou-gre|gue-ipip|vxlan|geneve|dnscrypt-udp|ntp-direct|openvpn-dco|srtp-direct) echo 3.3.0 ;;
    *) echo 2.1.0 ;;
  esac
}
carrier_ok_here() { [ -n "$(bin_ver_ok "$(carrier_min_ver "$1")")" ]; }
# F19 (3.3.0): wattun-internal wire shapes. Raw tier: bare-IP peer on a raw socket like icmp/gre, IP protocols
# 41/41/50/97/115, no -listen and no -reverse, one session, Linux + root/CAP_NET_RAW. UDP tier: the udp carrier with a
# fixed per-protocol header and conventional port (peer/listen, explicit port wins), no -reverse, one session. Both
# ends must run 3.3.0 with the same name; they do NOT talk to the real protocol. Kept in sync with cmd/wattun/main.go
# and wat/udpshape.go (port table).
SHAPED_RAW='sit 6to4 xfrm-ipsec etherip l2tpv3'
SHAPED_UDP='fou-gre gue-ipip vxlan geneve dnscrypt-udp ntp-direct openvpn-dco srtp-direct'
is_shaped_raw() { case " $SHAPED_RAW " in *" $1 "*) return 0 ;; esac; return 1; }
is_shaped_udp() { case " $SHAPED_UDP " in *" $1 "*) return 0 ;; esac; return 1; }
is_shaped_carrier() { is_shaped_raw "$1" || is_shaped_udp "$1"; }
is_ext_carrier() { is_shaped_carrier "$1" || [ "$1" = ptcp ] || [ "$1" = spray ]; } # a hidden NAME-e-* helper, never a bond leg (ptcp/spray: 4.0.2)
is_shaped_list() { local c; for c in ${1//+/ }; do is_shaped_carrier "$c" && return 0; done; return 1; }
is_raw_carrier() { case "$1" in icmp|gre|ipip) return 0 ;; esac; is_shaped_raw "$1"; }
is_udp_carrier() { [ "$1" = udp ] || is_shaped_udp "$1"; }
carrier_has_listen() { ! is_raw_carrier "$1"; }
carrier_write_listen() { # carrier list -> 0 when the config needs a global listen: key (single raw shape: no listen)
  local c
  case "$1" in
    *+*) for c in ${1//+/ }; do case "$(carrier_leg_base "$c")" in udp|tcp|tls|ws|wss|h2|h2c|grpc) return 0 ;; esac; done; return 1 ;;
    *) carrier_has_listen "$1" ;;
  esac
}
shaped_udp_port() { # F19 UDP-shaped carrier -> its conventional UDP port (the engine's withDefaultPort default)
  case "$1" in
    fou-gre) echo 5555 ;; gue-ipip) echo 6080 ;; vxlan) echo 4789 ;; geneve) echo 6081 ;;
    dnscrypt-udp) echo 443 ;; ntp-direct) echo 123 ;; openvpn-dco) echo 1194 ;; srtp-direct) echo 5004 ;;
  esac
}
shaped_udp_mtu() { # carrier [default] -> the shape's datagram ceiling (wat/udpshape.go: 1400 minus its header/padding)
  local m
  case "$1" in
    dnscrypt-udp) m=1326 ;; ntp-direct) m=1336 ;; openvpn-dco) m=1396 ;; srtp-direct) m=1388 ;;
    fou-gre|gue-ipip|vxlan|geneve) m=1392 ;; *) echo "${2:-$ENG_MTU_MAX}"; return 0 ;;
  esac
  echo "$m"
}
shaped_raw_mtu() { # M1/M15: raw tier = 1400 minus the shape's fixed header (engine wat/mtuclamp_test.go pins these)
  local m
  case "$1" in
    sit|6to4) m=1360 ;; xfrm-ipsec) m=1392 ;; etherip) m=1384 ;; l2tpv3) m=1396 ;;
    *) echo "${2:-$ENG_MTU_MAX}"; return 0 ;;
  esac
  echo "$m"
}
shaped_real_name() { # F19 carrier -> the real protocol name the UI must say it is NOT
  case "$1" in
    sit) echo '6in4' ;; 6to4) echo '6to4' ;; xfrm-ipsec) echo 'IPsec/ESP' ;; etherip) echo 'EtherIP' ;;
    l2tpv3) echo 'L2TPv3' ;; fou-gre) echo 'FOu/GRE-in-UDP' ;; gue-ipip) echo 'GUE' ;; vxlan) echo 'VXLAN' ;;
    geneve) echo 'Geneve' ;; dnscrypt-udp) echo 'DNSCrypt' ;; ntp-direct) echo 'NTP' ;;
    openvpn-dco) echo 'OpenVPN DCO' ;; srtp-direct) echo 'SRTP' ;;
  esac
}
shaped_raw_proto() { # raw tier -> the IP protocol number it imitates
  case "$1" in sit|6to4) echo 41 ;; xfrm-ipsec) echo 50 ;; etherip) echo 97 ;; l2tpv3) echo 115 ;; esac
}
v_carrier_list() { # "icmp+udp" etc: every leg a known carrier, no duplicates; "auto" only alone; bond legs may
                   # carry a :up/:down direction suffix (3.3.9, both ends): :down is udp-only, the suffix is
                   # bond-only (a single carrier always carries both directions), a bond must keep at least
                   # one leg able to carry each direction, and a shaped carrier never takes a suffix (it
                   # cannot be a bond leg at all — D7, so the check runs on the stripped leg names)
  local v=${1:-} c base dir seen='' plain=0 saw_up=0 saw_down=0 bases=''
  [ -n "$v" ] || { err "Choose a carrier."; return 1; }
  if [ "$v" = auto ]; then return 0; fi
  case "$v" in *++*|+*|*+) err "Carrier list '$v' has an empty leg."; return 1 ;; esac
  case "$v" in
    *+*) # D7: the engine refuses shaped carriers in a bond in 3.3.0 (untested, per-protocol port defaults collide)
      # 4.5.1: ptcp and spray too (is_ext_carrier), the same rule as the Go manager's CanBond
      for c in ${v//+/ }; do c=$(carrier_leg_base "$c"); c=${c%-rev}
        is_ext_carrier "$c" && { err "$c works as a single carrier only; the engine refuses it in a '+'-bond ('$v')."; return 1; }; done ;;
    *) case "$v" in *:up|*:down) err "A :up/:down direction suffix only makes sense on a '+'-bond leg ('$v' alone would lose a direction)."; return 1 ;; esac ;;
  esac
  for c in ${v//+/ }; do
    base=$(carrier_leg_base "$c")
    carrier_ok "$base" || { err "Unknown carrier '$c' (use icmp, udp, tcp, tls, ws, wss, h2, h2c, grpc, gre, ipip, sit, 6to4, xfrm-ipsec, etherip, l2tpv3, fou-gre, gue-ipip, vxlan, geneve, dnscrypt-udp, ntp-direct, openvpn-dco, srtp-direct; join several with + to bond; a bond leg may end in :up or :down, 3.3.9 on both ends)."; return 1; }
    dir=$(carrier_leg_dir "$c")
    case "$dir" in
      down) [ "$base" = udp ] || { err "Carrier '$c': :down is udp-only in 3.3.9 (the engine refuses the rest)."; return 1; }
            saw_down=1 ;;
      up) saw_up=1 ;;
      *) plain=1 ;;
    esac
  done
  # a bond whose legs all point the same way has no leg left for the other direction (checked
  # before the duplicate pass so it names the real problem: :down is udp-only, so an all-:down
  # bond is also a duplicate-udp bond)
  if [ "$plain" = 0 ]; then
    [ "$saw_up" = 0 ] && { err "Carrier list '$v': every leg is :down, so nothing carries the uplink."; return 1; }
    [ "$saw_down" = 0 ] && { err "Carrier list '$v': every leg is :up, so nothing carries the downlink."; return 1; }
  fi
  for c in ${v//+/ }; do
    # dedupe on the BASE carrier like the engine does (cmd/wattun/main.go leg loop): udp:up+udp:down is two
    # different leg strings over one socket, and the engine exits 2 on it (docs/TECHNICAL.md "refused as a
    # duplicate udp") — the manager must refuse it too or it writes a config the tunnel cannot start with
    # (2026-11-20 review F1)
    local b
    b=$(carrier_leg_base "$c")
    case " $seen " in *" $b "*) err "Carrier '$b' appears twice in '$v' (a $c leg counts as its base)."; return 1 ;; esac
    seen="$seen $b"
  done
  return 0
}
shaped_supported_here() { # carrier list -> 0 when this host can run it, else prints why
  local c raw=0 shaped=0
  for c in ${1//+/ }; do
    is_shaped_carrier "$c" || continue
    shaped=1
    is_shaped_raw "$c" && raw=1
  done
  [ "$shaped" = 1 ] || return 0
  if [ "$raw" = 1 ] && [ "$(uname -s)" != Linux ]; then
    err "The raw-tier shaped carriers (sit, 6to4, xfrm-ipsec, etherip, l2tpv3) need Linux + root/CAP_NET_RAW on both ends (raw sockets); this server is not Linux."
    return 1
  fi
  if [ "$(bin_ver_ok 3.3.0)" != 1 ]; then
    err "F19 shaped carriers need wattun 3.3.0 or newer on BOTH ends; this server has ${VER:-an unknown version}. Run: $SELF update"
    return 1
  fi
  return 0
}
shaped_warn() { # carrier list : the wattun-internal warning (plus raw-tier and bond caveats) for the UI
  local c real='' raw=0 udp=0 bond=0 any=0 rawprotos='' udpports=''
  case "$1" in *+*) bond=1 ;; esac
  for c in ${1//+/ }; do
    is_shaped_carrier "$c" || continue
    any=1
    real="$real${real:+, }$(shaped_real_name "$c")"
    if is_shaped_raw "$c"; then raw=1; rawprotos="$rawprotos $(shaped_raw_proto "$c")"; else udp=1; udpports="$udpports${udpports:+, }$(shaped_udp_port "$c")"; fi
  done
  [ "$any" = 1 ] || return 0
  warn "F19 $([ "$bond" = 1 ] && echo 'leg(s)' || echo carrier) '$1': wattun-internal shape between two 3.3.0 peers, NOT real $real."
  hint "Both ends must run wattun 3.3.0+ and pick the SAME carrier name; it does not talk to the real $real protocol."
  [ "$raw" = 1 ] && hint "Raw tier: IP protocol ${rawprotos# } on a raw socket, Linux + root/CAP_NET_RAW on both ends, no listen port, no reverse, one session. Allow that protocol in the cloud firewalls."
  [ "$udp" = 1 ] && hint "UDP tier: the exit server listens on a random open UDP port (or --listen PORT; peer host:port). Open it in the exit server cloud firewall."
  [ "$bond" = 1 ] && warn "3.3.0 refuses F19 shaped carriers in a '+'-bond; use a single shaped carrier instead."
  return 0
}
shaped_peer_for_client() { # carrier peer -> the peer form the engine wants (raw tier: bare host; UDP tier: host:port)
  local c=$1 p=$2 last
  if is_shaped_raw "$c"; then
    case "$p" in *:*) last=${p##*:}; v_port "$last" >/dev/null 2>&1 && p=${p%:*} ;; esac
    printf '%s' "$p"; return 0
  fi
  case "$p" in
    *:*) printf '%s' "$p" ;; # an explicit port wins (withDefaultPort)
    *) printf '%s:%s' "$p" "$(shaped_udp_port "$c")" ;;
  esac
}
# D7 (3.3.0): shaped carriers are single-carrier — the engine refuses them in a '+'-bond, so the manager has no
# per-leg listen-/peer- YAML writer any more (shaped_bond_yaml was removed with the 3.3.0 audit fix).
# Which address a connection to HOST leaves from, and the global IPv4 addresses this server holds (3.0.0). A server with
# two addresses sends the tunnel from the one the route picks, which can be the address the users connect to.
out_ip() {
  local ip
  ip=$(ip -4 route get "$1" 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -1)
  if [ -n "$ip" ]; then echo "$ip"; return 0; fi
  ip -6 route get "$1" 2>/dev/null | sed -n 's/.* src \([0-9a-fA-F:]*\).*/\1/p' | head -1
}
local_ips() { ip -4 -o addr show scope global 2>/dev/null | awk '{sub(/\/.*/,"",$4); print $4}'; }
# carriers whose reverse mode means: Iran listens on the carrier port and Kharej connects (tcp family) or punches (udp) to it
is_rpool() { is_pool "$1" || [ "$1" = udp ]; }
rproto() { # transport of the carrier port, for firewall and busy-port checks
  case "$1" in udp|fou-gre|gue-ipip|vxlan|geneve|dnscrypt-udp|ntp-direct|openvpn-dco|srtp-direct) echo udp ;; *) echo tcp ;; esac
}
rev_capable() { [ "$1" = icmp ] || is_rpool "$1"; }
reverse_hint() { # [carrier]
  if [ "${1:-}" = udp ]; then
    hint "Reverse: the exit server sends first and the entry server only answers. For filters that punish flows the entry server starts."
    hint "Set it on both sides (wattun 3.0.0+)."
  elif is_pool "${1:-}"; then
    hint "Reverse: the exit server connects to the entry server. For when the entry server cannot reach the exit server's port, but the exit server can reach the entry server."
    hint "Set it on both sides."
  else
    hint "Reverse: the exit server pings the entry server. For a one-way block where the entry server cannot ping the exit server."
    hint "Set it on both sides (wattun 2.0.0+)."
  fi
}
v_icmp() { case "$1" in echo|timestamp) return 0 ;; esac; err "Use echo or timestamp (Linux does not answer info/mask)."; return 1; }
v_mbps_adv() { case "$1" in -|0|default) return 0 ;; esac; v_mbps "$1"; }
v_mbps() { [ -z "$1" ] && return 0; [[ "$1" =~ ^[0-9]{1,4}$ ]] && [ "$1" -ge 1 ] && return 0; err "Enter a number of MB/s (1-9999)."; return 1; }
v_sessions() { # [count] [carrier] [reverse=1] : engine max 16, and >1 only one udp/pool carrier in forward mode
  local v=$1 car=${2:-} rev=${3:-0}
  [ -z "$v" ] && return 0
  case "$v" in -|0|default) return 0 ;; esac
  [[ "$v" =~ ^[0-9]{1,3}$ ]] && [ "$((10#$v))" -ge 1 ] && [ "$((10#$v))" -le "$ENG_MAX_SESSIONS" ] || {
    err "Enter sessions count 1-$ENG_MAX_SESSIONS (or 0/default to unset)."; return 1; }
  [ "$((10#$v))" -gt 1 ] || return 0
  if [ "$rev" = 1 ]; then err "sessions > 1 does not work with reverse (the server dials one pool)."; return 1; fi
  if [ -n "$car" ] && ! sessions_carrier_ok "$car"; then
    err "sessions > 1 needs one udp/tcp/tls/ws/wss/h2/h2c/grpc carrier, not '$car' (bonds, icmp/gre/ipip and the F19 shapes run one session)."
    return 1
  fi
  return 0
}
v_conns() { [ -z "$1" ] && return 0; case "$1" in -|0|default) return 0 ;; esac; [[ "$1" =~ ^[0-9]{1,3}$ ]] && [ "$1" -ge 1 ] && [ "$1" -le "$ENG_MAX_CONNS" ] && return 0; err "Enter conns count 1-$ENG_MAX_CONNS (the engine caps a pool at $ENG_MAX_CONNS; or 0/default to unset)."; return 1; }
v_mtu() { # [mtu] [carrier] : engine bound 256..1400, up to 16384 with a pool carrier (a bond uses its smallest leg)
  local hi=$ENG_MTU_MAX_POOL
  [ -n "${2:-}" ] && hi=$(mtu_max_for "$2")
  [ -z "$1" ] && return 0
  case "$1" in -|0|default) return 0 ;; esac
  [[ "$1" =~ ^[0-9]{3,5}$ ]] && [ "$((10#$1))" -ge "$ENG_MTU_MIN" ] && [ "$((10#$1))" -le "$hi" ] && return 0
  if [ -n "${2:-}" ]; then err "Enter MTU $ENG_MTU_MIN-$hi for carrier '$2' (or 0/default to unset)."
  else err "Enter MTU $ENG_MTU_MIN-$ENG_MTU_MAX_POOL (or 0/default to unset); without a pool carrier the engine caps it at $ENG_MTU_MAX."; fi
  return 1
}
v_num() { [[ "$1" =~ ^[0-9]+$ ]] && return 0; err "Enter a valid positive number."; return 1; }
v_bind() {
  local h=${1:-}; h=${h#[}; h=${h%]}
  if [ "$h" = "::" ] || ipv4_ok "$h" || ipv6_ok "$h"; then return 0; fi
  err "Enter an IPv4 or IPv6 address such as 0.0.0.0, :: (dual-stack) or 10.0.0.5."; return 1
}
v_fec() { case "$1" in off|auto) return 0 ;; esac; err "Use off or auto."; return 1; }
# A3: stable engine knobs as first-class rows. -win-max is an Int clamped by the engine to 4..64 MB (0 = auto-tuned
# from host RAM, 3.0.3); -loss-ceiling is a bool opt-in (3.0.0). A value the engine would clamp must not be written.
v_win_max() { # MB, 4..64; empty/-/0/default = unset (engine auto)
  local v=${1:-}
  [ -z "$v" ] && return 0
  case "$v" in -|0|default) return 0 ;; esac
  [[ "$v" =~ ^[0-9]{1,2}$ ]] && [ "$((10#$v))" -ge 4 ] && [ "$((10#$v))" -le 64 ] && return 0
  err "Enter the per-stream window cap in MB (4-64), or 0/- for the engine's auto value."
  return 1
}
v_loss_ceiling() { # on/off (also true/false/1/0); off is the engine default
  case "${1:-}" in off|false|0|default|'') return 0 ;; on|true|1) return 0 ;; esac
  err "Use on or off."
  return 1
}
# A2: the wizard's FEC prompt keeps off|auto and adds `a` = auto plus open the loss-band rows after creation. Parsed by a
# pure helper so the three answers and the old-engine fallback are table-testable. On an engine older than 3.3.0 the
# band keys do not exist (unknown key stops startup), so `a` falls back to plain auto with the update hint.
REPLY_FEC_BAND=0; REPLY_FEC_OLD=0
fec_choice() { # raw answer -> REPLY_V (off|auto), REPLY_FEC_BAND (1 = open the band rows), REPLY_FEC_OLD (1 = asked on old engine)
  local v=${1:-}
  REPLY_FEC_BAND=0; REPLY_FEC_OLD=0
  case "$v" in
    ''|off|default) REPLY_V=off ;;
    auto) REPLY_V=auto ;;
    a|A)
      if [ -n "$(bin_ver_ok 3.3.0)" ]; then REPLY_V=auto; REPLY_FEC_BAND=1
      else REPLY_V=auto; REPLY_FEC_OLD=1; fi ;;
    *) err "Use off, auto or a."; return 1 ;;
  esac
  return 0
}
ask_fec() { # [default] : wizard FEC prompt; interactive answer a also opens the band rows
  local def=${1:-off}
  if [ "$NONINTERACTIVE" = 1 ]; then fec_choice "$def" || return 1; return 0; fi
  hint "auto sends parity only while loss is above 2 %; a here lets you tune the band."
  ask "FEC: off, auto, or a (auto + open the loss-band rows)" "$def"
  fec_choice "$REPLY_V" || return 1
  [ "$REPLY_FEC_OLD" = 1 ] && hint "The FEC loss band needs wattun 3.3.0 on this server (run: $SELF update); using auto with engine defaults."
  return 0
}
# -fec-on-loss/-fec-off-loss (F11, 3.3.0): percentages. The engine (cmd/wattun/fecgate.go) requires 0 < on <= 50 and
# 0 <= off < on; an invalid band stops the tunnel at startup, so the same check runs here before the key is written.
v_fec_on() { # value [current-off] : 0 < value <= 50 and above the off threshold
  local v=${1:-} off=${2:-0.5}
  [ -z "$v" ] && return 0
  case "$v" in -|default) return 0 ;; esac
  [[ "$v" =~ ^[0-9]{1,2}(\.[0-9]+)?$ ]] || { err "Enter a loss percentage above 0 and at most 50 (for example 2 or 0.5)."; return 1; }
  awk -v v="$v" -v o="$off" 'BEGIN{exit !(v > 0 && v <= 50 && v > o)}' \
    || { err "fec-on-loss must be above 0, at most 50 and above fec-off-loss ($off)."; return 1; }
  return 0
}
v_fec_off() { # value [current-on] : 0 <= value < on threshold
  local v=${1:-} on=${2:-2}
  [ -z "$v" ] && return 0
  case "$v" in -|default) return 0 ;; esac
  [[ "$v" =~ ^[0-9]{1,2}(\.[0-9]+)?$ ]] || { err "Enter 0 or a loss percentage (for example 0.5 or 2)."; return 1; }
  awk -v v="$v" -v n="$on" 'BEGIN{exit !(v >= 0 && v < n)}' \
    || { err "fec-off-loss must be 0 or more and below fec-on-loss ($on)."; return 1; }
  return 0
}
# -state-dir/-state-save (F8, 3.3.0): the engine needs an existing-or-creatable directory (it creates 0700 and probes
# writability at startup) and a whole number of seconds >= 0.
v_state_dir() { # absolute directory, or empty/-/default for the engine default (next to the config)
  local v=${1:-}
  [ -z "$v" ] && return 0
  case "$v" in -|default|0) return 0 ;; esac
  [[ "$v" =~ ^/[A-Za-z0-9._/-]*$ ]] || { err "Enter an absolute directory such as /run/wattun (no spaces), or - for the default next to the config."; return 1; }
  case "/${v#/}/" in */../*) err "The state directory cannot contain '..'."; return 1 ;; esac
  [ "${#v}" -le 200 ] || { err "That path is too long (200 characters at most)."; return 1; }
  case "$v" in # H1: the shipped unit only makes /run/wattun writable (RuntimeDirectory + ReadWritePaths)
    /run/wattun|/run/wattun/*|/etc/wattun|/etc/wattun/*) ;;
    *) warn "The shipped systemd unit only guarantees writes under /run/wattun; add '$v' to its ReadWritePaths or the engine stops at startup." ;;
  esac
  [ -e "$v" ] && [ ! -d "$v" ] && { err "$v exists and is not a directory."; return 1; }
  [ -d "$v" ] && [ ! -w "$v" ] && { err "$v is not writable; wattun would fail at startup (the shipped unit only makes /run/wattun writable via RuntimeDirectory)."; return 1; }
  return 0
}
v_state_save() { # whole seconds 0..2592000 (0 = only on shutdown); mirrors stateSaveInterval's cap
  local v=${1:-}
  [ -z "$v" ] && return 0
  case "$v" in -|default) return 0 ;; esac
  [[ "$v" =~ ^[0-9]{1,7}$ ]] && [ "$((10#$v))" -le 2592000 ] && return 0
  err "Enter the save interval in whole seconds, at most 2592000 (30 days; 0 = only on shutdown)."
  return 1
}
# -shape-data / -noise / -noise-bps / -noise-window (F13, 3.3.0): every one is validated at startup in
# cmd/wattun/noise.go, so a typo stops the tunnel instead of silently disabling shaping. These mirror those rules.
v_shape_data() { # percent 0..25; 0/empty = off (engine hard cap 25)
  local v=${1:-}
  [ -z "$v" ] && return 0
  case "$v" in -|default|0|0.0) return 0 ;; esac
  [[ "$v" =~ ^[0-9]{1,2}(\.[0-9]+)?$ ]] || { err "Enter the padding budget in percent (0 = off, up to 25)."; return 1; }
  awk -v v="$v" 'BEGIN{exit !(v > 0 && v <= 25)}' || { err "shape-data must be 0 (off) or up to 25 percent, got $v."; return 1; }
  return 0
}
v_noise_mode() { case "${1:-}" in ''|off|low|med|custom) return 0 ;; esac; err "Use off, low, med or custom."; return 1; }
v_noise_bps() { # bytes/second, only with noise custom: 64..1000000 (noiseBudget)
  local v=${1:-}
  [ -n "$v" ] || { err "noise custom needs a byte budget (64..1000000 B/s)."; return 1; }
  [[ "$v" =~ ^[0-9]{1,7}$ ]] && [ "$((10#$v))" -ge 64 ] && [ "$((10#$v))" -le 1000000 ] && return 0
  err "Enter the filler budget in bytes/second (64..1000000)."
  return 1
}
v_noise_window() { # "HH:MM-HH:MM" local clock, start != end, may wrap past midnight; empty/- = all day
  local v=${1:-} a b am bm
  [ -z "$v" ] && return 0
  case "$v" in -|default) return 0 ;; esac
  [[ "$v" =~ ^([0-9]|[01][0-9]|2[0-3]):[0-5][0-9]-([0-9]|[01][0-9]|2[0-3]):[0-5][0-9]$ ]] \
    || { err 'Enter a local-clock window such as 02:00-06:00 (HH:MM-HH:MM), or - for all day.'; return 1; }
  a=${v%%-*}; b=${v#*-}
  am=$(( 10#${a%%:*} * 60 + 10#${a##*:} )); bm=$(( 10#${b%%:*} * 60 + 10#${b##*:} ))
  [ "$am" != "$bm" ] || { err "The noise window cannot start and end at the same time; leave it empty for all day."; return 1; }
  return 0
}
# -allow-clients / -allow-clients-file (W10, 3.3.0): server-side admission allowlist, checked before a session is
# admitted (cmd/wattun/clientallow.go). Bare addresses are kept as /32 or /128; entries are masked like the engine does.
ipv6_ok() { # pragmatic syntax check; netip.ParseAddr in the engine is the authority
  local a=${1:-} zone='' g last
  [ -n "$a" ] || return 1
  case "$a" in *%*) zone=${a##*%}; a=${a%%%*}; [ -n "$zone" ] && [[ "$zone" =~ ^[A-Za-z0-9_.-]+$ ]] || return 1 ;; esac
  [ "${#a}" -le 45 ] && [[ "$a" == *:* ]] && [[ "$a" =~ ^[0-9A-Fa-f:.]+$ ]] || return 1
  case "$a" in *:::*) return 1 ;; esac
  case "${a/::/}" in *::*) return 1 ;; esac # at most one "::"
  case "$a" in :*) [[ "$a" == ::* ]] || return 1 ;; esac
  case "$a" in *:) [[ "$a" == *:: ]] || return 1 ;; esac
  g=$(printf '%s\n' "$a" | awk '
    BEGIN { FS = "::" }
    { dbl = ($0 ~ /::/) ? 1 : 0; g = 0; bad = 0
      for (p = 1; p <= NF; p++) {
        if ($p == "") continue
        m = split($p, u, /:+/)
        for (i = 1; i <= m; i++) {
          if (u[i] == "") { bad = 1; break }
          if (u[i] ~ /\./) { if (p != NF || i != m) bad = 1; else g += 2 }
          else if (u[i] ~ /^[0-9A-Fa-f]{1,4}$/) g += 1
          else bad = 1
        }
        if (bad) break
      }
      if (bad) { print -1; exit }
      if (dbl ? (g > 7) : (g != 8)) { print -1; exit }
      print g }') || return 1
  [ "${g:--1}" -ge 0 ] 2>/dev/null || return 1
  case "$a" in *.*) last=${a##*:}; [ -z "$last" ] || ipv4_ok "$last" || return 1 ;; esac
  return 0
}
ip_or_cidr_ok() { # one allowlist entry: bare IPv4/IPv6 address or CIDR prefix
  local a=${1:-} addr pfx
  [ -n "$a" ] || return 1
  case "$a" in */*) addr=${a%%/*}; pfx=${a#*/} ;; *) addr=$a; pfx='' ;; esac
  if ipv4_ok "$addr"; then
    [ -z "$pfx" ] && return 0
    [[ "$pfx" =~ ^[0-9]{1,2}$ ]] && [ "$((10#$pfx))" -le 32 ] && return 0
    return 1
  fi
  if ipv6_ok "$addr"; then
    [ -z "$pfx" ] && return 0
    [[ "$pfx" =~ ^[0-9]{1,3}$ ]] && [ "$((10#$pfx))" -le 128 ] || return 1
    # M3: the engine normalizes a mapped prefix to IPv4 and refuses mapped bits < /96; reject it here instead.
    case "$addr" in ::ffff:*|::FFFF:*) [ "$((10#$pfx))" -lt 96 ] && return 1 ;; esac
    return 0
  fi
  return 1
}
v_allow_clients() { # comma/space separated addresses or prefixes; empty/- = admit every source
  local v=${1:-} e
  [ -z "$v" ] && return 0
  case "$v" in -|default) return 0 ;; esac
  for e in ${v//,/ }; do
    ip_or_cidr_ok "$e" || { err "'$e' is not an IPv4/IPv6 address or CIDR prefix."; return 1; }
  done
  return 0
}
# M4: the service unit has ProtectSystem=strict/ProtectHome=yes and ReadWritePaths=/etc/wattun, so a list file
# anywhere else (e.g. /root) passes a root-shell check but fatals at startup. Require the path under /etc/wattun (under
# $CONF in a sandbox, whose configs live in the test dir). A CDN carrier/sni tunnel is refused by the engine anyway.
allow_clients_dir() { [ "$SANDBOX" = 1 ] && { printf '%s' "$CONF"; return 0; }; printf '/etc/wattun'; }
allow_clients_cdn_risk() { # carrier-list [sni] -> 0 when -allow-clients cannot be used (engine refuses the combination)
  local c
  case "${2:-}" in ''|-) ;; *) return 0 ;; esac
  for c in ${1//+/ }; do case "$c" in ws|wss|h2|h2c|grpc) return 0 ;; esac; done
  return 1
}
v_allow_clients_file() { # path under the state dir; the engine reads it once at startup and refuses it if empty
  local v=${1:-} e dir
  [ -z "$v" ] && return 0
  case "$v" in -|default) return 0 ;; esac
  dir=$(allow_clients_dir)
  [[ "$v" =~ ^/[A-Za-z0-9._/-]*$ ]] || { err "Enter an absolute path to the list file (no spaces), or - for the inline list."; return 1; }
  case "$v" in
    "$dir"/*) ;;
    *) err "Put the allowlist file under $dir/ (the shipped unit can only read that path); got $v."; return 1 ;;
  esac
  [ -f "$v" ] || { err "$v does not exist (the engine reads the file at startup)."; return 1; }
  [ -r "$v" ] || { err "$v is not readable."; return 1; }
  local found=0
  # the engine splits on comma, space, tab, CR and newline (clientallow.go isClientSeparator); default IFS covers all
  # but the comma
  for e in $(tr ',' ' ' <"$v"); do
    [ -n "$e" ] || continue
    found=1
    ip_or_cidr_ok "$e" || { err "$v: '$e' is not an IPv4/IPv6 address or CIDR prefix."; return 1; }
  done
  [ "$found" = 1 ] || { err "$v has no entries; the engine refuses an empty allowlist."; return 1; }
  return 0
}
# H6: one list, AC_ALLMODES, is the single source for the validator, the unattended --fake-mode parser, the picker,
# the matrix and the usage text. It must match wat/desync.go's accepted modes (13 since 2.9.0/3.0.0); the old second
# list in the manager made the unattended path reject 5 documented modes the engine accepts.
AC_ALLMODES='rst synrst paws seq seqsum sum ttl split hlen0 fakeip ff all auto'
fake_mode_ok() { case " $AC_ALLMODES " in *" $1 "*) return 0 ;; esac; return 1; }
v_fake_mode() { fake_mode_ok "${1:-}" && return 0; err "Use one of: $AC_ALLMODES."; return 1; }
fake_mode_desc() { # mode -> one-line picker description (version notes; unknown modes get a generic line)
  case "$1" in
    auto) echo 'tests the route at start, up to 18 s (3.0.0+)' ;;
    seqsum) echo 'seq + bad checksum, SNI-allowlist filters (2.8.0+)' ;;
    sum) echo 'bad checksum, stateful NATs (2.7.1+)' ;;
    seq) echo 'out-of-window sequence (2.7.0+)' ;;
    ttl) echo 'short TTL (2.7.0+)' ;;
    rst) echo 'bad-checksum RST, recommended (2.9.0+)' ;;
    synrst) echo 'when rst is filtered (2.10.5+)' ;;
    paws) echo 'stale timestamp, filters that check checksums (3.0.2+)' ;;
    split) echo 'split the ClientHello across segments' ;;
    hlen0) echo 'zero-length record first' ;;
    fakeip) echo 'fake-IP handshake variant' ;;
    ff) echo 'flags-and-fragments mode' ;;
    all) echo 'run every desync mode' ;;
    *) echo 'direct desync mode' ;;
  esac
}
# Checksum markers need a middlebox that drops the damaged segment; on an open reverse path the peer may take it and
# the tunnel dies (field 2.11.0, fr-tcp-sum). wattun 3.0.0 refuses them with -reverse; refuse them here as well.
rev_sum_refused() { # name mode -> 0 (and an error) when the pair is refused
  is_reverse "$1" || return 1
  case "$2" in sum|seqsum) err "fake-mode $2 does not work on a reverse tunnel (checksum markers can kill the flow there); use rst or synrst."; return 0 ;; esac
  return 1
}
v_fake_ttl() { [ -z "$1" ] && return 0; [[ "$1" =~ ^[0-9]{1,3}$ ]] && [ "$1" -le 255 ] && return 0; err "Enter a hop count 1-255 (or leave empty for auto)."; return 1; }
v_pool_rotate() { [ -z "$1" ] && return 0; case "$1" in 0|off) return 0 ;; esac; [[ "$1" =~ ^[0-9]+(ms|s|m|h)$ ]] && return 0; err "Enter a lifetime such as 90s, 30m or 4h (or 0 to turn it off)."; return 1; }
v_quota_period() { case "${1,,}" in ''|-|none|day|week|month) return 0 ;; esac; err "Enter day, week or month (or - for a quota that never resets)."; return 1; }
v_pool_bytes() { local s=${1,,}; [ -z "$s" ] && return 0; case "$s" in 0|0b|off) return 0 ;; esac; [[ "$s" =~ ^[0-9]+(\.[0-9]+)?(k|m|g|t)b?$ ]] && return 0; err "Enter a byte count such as 500MB, 4G or 300k (or 0 to turn it off)."; return 1; }
v_sni_name() {
  local part parts
  local IFS=','
  read -ra parts <<< "$1"
  [ "${#parts[@]}" -gt 0 ] || { err "Enter a server name such as mci.ir."; return 1; }
  for part in "${parts[@]}"; do
    part="${part#"${part%%[![:space:]]*}"}"
    part="${part%"${part##*[![:space:]]}"}"
    [[ "$part" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$ ]] || { err "Enter a server name such as mci.ir."; return 1; }
  done
  return 0
}
v_ech() {
  [ -z "$1" ] && return 0
  local v=${1,,}
  case "$v" in off|auto|ladder) return 0 ;; esac
  if [[ "$1" =~ ^[A-Za-z0-9+/=_-]{16,}$ ]]; then return 0; fi
  err "--ech: use off, auto, ladder or a base64 ECHConfigList (got '$1')."
  return 1
}
v_governor() {
  [ -z "$1" ] && return 0
  local v=${1,,}
  case "$v" in on|off|true|false|1|0) return 0 ;; esac
  err "--governor: use on, off, true or false (got '$1')."
  return 1
}
v_preset() {
  [ -z "$1" ] && return 0
  local v=${1,,}
  case "$v" in
    cloudflare|cf|cloudflare-tested|tested|worked|rst-fast|fast|mci|irancell|mokhaberat|tci|blackout|emergency|strict|conservative|low-churn|off|clear|none) return 0 ;;
    "iran whitelist - mci"|"iran whitelist - irancell/mokhaberat"|"emergency blackout mode"|"conservative / low-churn"|"conservative/low-churn") return 0 ;;
  esac
  err "Unknown preset '$1'. Available: cloudflare, rst-fast, mci, irancell, blackout, conservative"
  return 1
}
v_dns_listen() {
  local a=${1,,}
  [ -z "$a" ] && return 0
  case "$a" in 0|off) return 0 ;; esac
  if [[ "$1" =~ ^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}):([0-9]{1,5})$ ]]; then
    local ip="${BASH_REMATCH[1]}"
    local port="${BASH_REMATCH[2]}"
    ipv4_ok "$ip" || { err "DNS listen IP is invalid."; return 1; }
    v_port "$port" || return 1
    return 0
  fi
  err "--dns-listen: enter an address like 127.0.0.1:53 or 127.0.0.1:5353 (or off)."
  return 1
}
v_src_ip() {
  local ip=${1,,} h=${1:-}
  [ -z "$ip" ] && return 0
  case "$ip" in 0|off) return 0 ;; esac
  h=${h#[}; h=${h%]}
  ipv4_ok "$h" || ipv6_ok "$h" || { err "--src-ip: enter a valid IPv4/IPv6 address (or off)."; return 1; }
  return 0
}
v_path() { [[ "$1" =~ ^/[A-Za-z0-9._/-]*$ ]] && return 0; err "The path must start with / (example: /wat)."; return 1; }
v_token() {
  if read_token "$1"; then return 0; fi
  err "That is not a valid token. It starts with wat1: and is one long line."; return 1
}
v_key() { [ "${#1}" -ge 8 ] && [[ "$1" =~ ^[^[:space:]]+$ ]] && return 0; err "The key is at least 8 characters, no spaces."; return 1; }
v_domain_opt() {
  [ -z "$1" ] && return 0
  [[ "$1" =~ ^[A-Za-z0-9][A-Za-z0-9.-]*[A-Za-z0-9]$ ]] && [[ "$1" == *.* ]] && return 0
  err "Enter a domain name such as vpn.example.com (or press Enter to skip)."; return 1
}
v_nonempty() { [ -n "$1" ] && return 0; err "This value is required."; return 1; }

# ======================================================================================
#  Diagrams
# ======================================================================================
step_diagram() { # [1|2 highlight]
  local hl=${1:-0} c1=$BOLD c2=$BOLD cols
  cols=$(term_cols)
  [ "$hl" = 1 ] && c2=$GRY; [ "$hl" = 2 ] && c1=$GRY
  if [ "$hl" = 2 ]; then
    printf '  %s✔ [1] Kharej%s %s(outside)%s  %s─── wat1: token ───►%s  %s[2] Iran%s %s(inside)%s\n' \
      "$GRN" "$RST" "$GRY" "$RST" "$CYN" "$RST" "$CYN$BOLD" "$RST" "$GRY" "$RST"
    return 0
  fi
  if [ "$cols" -lt 68 ]; then
    printf '  %s[1] Kharej%s %s(outside)  ─── wat1: token ───►%s\n' "$c1" "$RST" "$GRY" "$RST"
    printf '  %s[2] Iran%s %s(inside, users connect here)%s\n' "$c2" "$RST" "$GRY" "$RST"
  else
    printf '  %s[1] Kharej%s %s(outside)%s  %s─── wat1: token ───►%s  %s[2] Iran%s %s(inside)%s\n' \
      "$c1" "$RST" "$GRY" "$RST" "$GRY" "$RST" "$c2" "$RST" "$GRY" "$RST"
    printf '      %sruns service                              users connect here%s\n' "$GRY" "$RST"
  fi
}
conn_diagram() { # carrier canonical... : Users ──► Iran :8443 ═══[ icmp · 42 ms ]═══► Kharej ──► 127.0.0.1:443
  local cr=$1 it n=0 L T P sfx br cols line_len; shift
  cols=$(term_cols)
  br="$cr"
  [ "${T_REV:-0}" = 1 ] && br+=" · rev"
  [ -n "${LINK_RTT:-}" ] && br+=" · ${LINK_RTT} ms"
  for it in "$@"; do
    n=$((n+1)); [ "$n" -gt 4 ] && continue
    L=$(spec_L "$it"); T=$(spec_T "$it"); P=$(spec_P "$it"); sfx=''; [ "$P" = udp ] && sfx=/udp
    line_len=$(( 38 + ${#L} + ${#sfx} + ${#br} + ${#T} + ${#sfx} ))
    if [ "$cols" -ge 78 ] && [ "$line_len" -le $((cols - 2)) ]; then
      printf '  Users %s──►%s Iran :%s%s %s═══[ %s ]═══►%s Kharej %s──►%s 127.0.0.1:%s%s\n' \
        "$GRY" "$RST" "$L" "$sfx" "$CYN" "$br" "$RST" "$GRY" "$RST" "$T" "$sfx"
    else
      printf '  Users %s──►%s Iran :%s%s\n' "$GRY" "$RST" "$L" "$sfx"
      printf '    %s═══[ %s ]═══►%s Kharej %s──►%s 127.0.0.1:%s%s\n' \
        "$CYN" "$br" "$RST" "$GRY" "$RST" "$T" "$sfx"
    fi
  done
  [ "$n" -gt 4 ] && hint "  … and $((n-4)) more"
  return 0
}

# ======================================================================================
#  Tunnel info & telemetry
# ======================================================================================
TI_STATE=stopped; TI_RTT=0; TI_STREAMS=0; TI_SESS=0; TI_IN=0; TI_OUT=0; TI_RATE=0; TI_RAW=''
TI_CAR_COUNT=0; TI_CAR_ALIVE=0; TI_CAR_MUTED=0
CAR_COUNT=0; CAR_NAME=(); CAR_ALIVE=(); CAR_RTT=(); CAR_LOSS=(); CAR_SHARE=(); CAR_MUTED=()
parse_carriers() { # json
  local json=$1 carr_block item
  CAR_COUNT=0; CAR_NAME=(); CAR_ALIVE=(); CAR_RTT=(); CAR_LOSS=(); CAR_SHARE=(); CAR_MUTED=()
  carr_block=$(grep -o '"carriers": *\[[^]]*\]' <<<"$json" | head -1)
  [ -n "$carr_block" ] || return 0
  while read -r item; do
    [ -n "$item" ] || continue
    local nm al rtt ls sh mu
    nm=$(grep -o '"name": *"[^"]*"' <<<"$item" | head -1 | cut -d'"' -f4)
    al=$(grep -o '"alive": *[^,}]*' <<<"$item" | head -1 | sed 's/.*: *//; s/"//g')
    rtt=$(grep -o '"srtt_ms": *[^,}]*' <<<"$item" | head -1 | sed 's/.*: *//; s/"//g')
    ls=$(grep -o '"loss": *[^,}]*' <<<"$item" | head -1 | sed 's/.*: *//; s/"//g')
    sh=$(grep -o '"share": *[^,}]*' <<<"$item" | head -1 | sed 's/.*: *//; s/"//g')
    mu=$(grep -o '"muted": *[^,}]*' <<<"$item" | head -1 | sed 's/.*: *//; s/"//g')
    CAR_NAME+=("${nm:-unknown}")
    CAR_ALIVE+=("${al:-false}")
    CAR_RTT+=("${rtt:-0}")
    CAR_LOSS+=("${ls:-0}")
    CAR_SHARE+=("${sh:-0}")
    CAR_MUTED+=("${mu:-false}")
    CAR_COUNT=$((CAR_COUNT+1))
  done < <(grep -o '{[^{}]*}' <<<"$carr_block")
}
TI_MIN_RTT=0; TI_LOSS=0; TI_DGRAM_FLOWS=0; TI_LIVE_PICK=''
tinfo() { # name -> TI_*  (state: up | degraded | down | standby | unknown | stopped), TI_WHY says why when it is not obvious
  local par='' s='' on=0 miss=0
  TI_STATE=stopped; TI_RTT=0; TI_MIN_RTT=0; TI_LOSS=0; TI_STREAMS=0; TI_SESS=0; TI_DGRAM_FLOWS=0
  TI_IN=0; TI_OUT=0; TI_RATE=0; TI_RAW=''; TI_WHY=''; TI_LIVE_PICK=''
  TI_CAR_COUNT=0; TI_CAR_ALIVE=0; TI_CAR_MUTED=0; TI_LIVE=$(cfg "$1" carrier); TI_AUTO=0
  par=$(companion_of "$1")
  if [ -n "$par" ]; then
    TI_AUTO=1
    systemctl is-active -q "${WAT_PREFIX}@$1" 2>/dev/null && on=1
    [ "$on" = 1 ] || return 0
    TI_RAW=$(stats "$1") || TI_RAW=$(stats "$1") || TI_RAW=''
    if [ -z "$TI_RAW" ]; then TI_STATE=unknown; TI_WHY='stats did not answer, status not known'; return 0; fi
    if [ "$(jget "$TI_RAW" alive)" = true ]; then TI_STATE=up
    else
      s=$(stats "$par") || s=$(stats "$par") || true
      if [ "$(jget "$s" alive)" = true ]; then TI_STATE=standby; TI_WHY="not in use, the entry server is connected through $par"
      else TI_STATE=down; fi
    fi
  elif is_auto_kharej "$1"; then
    TI_AUTO=1
    local u any_up=0 sum_in=0 sum_out=0 sum_rate=0 sum_sess=0 sum_str=0 sum_df=0
    local best_rtt='' best_mr=0 best_ls=0 primary_raw='' live_pick=''
    local u_in u_out u_rate u_sess u_str u_df u_al u_rtt u_mr u_ls ulive one c j
    local -a units=("$1") m_name=() m_alive=() m_rtt=() m_loss=() m_share=() m_muted=()
    while IFS= read -r u; do [ -n "$u" ] && units+=("$u"); done < <(auto_helpers "$1")
    for u in "${units[@]}"; do
      systemctl is-active -q "${WAT_PREFIX}@$u" 2>/dev/null || continue
      on=1
      if [ "$u" = "$1" ] || [ "$u" = "$1-r" ]; then
        s=$(stats "$u") || s=$(stats "$u") || { miss=$((miss+1)); continue; }
        [ -n "$s" ] || { miss=$((miss+1)); continue; } # silent stats port: treat as unknown, not down
      else
        s=$(stats_flat "$u") || s=$(stats_flat "$u") || { miss=$((miss+1)); continue; }
      fi
      [ -n "$primary_raw" ] || primary_raw=$s
      u_in=$(jget "$s" bytes_in_total); u_out=$(jget "$s" bytes_out_total)
      [ -n "$u_in" ] || { u_in=$(jget "$s" bytes_in); u_out=$(jget "$s" bytes_out); }
      u_rate=$(jget "$s" rate_bps); u_sess=$(jget "$s" sessions)
      u_str=$(jget_flat "$s" streams_total streams); u_df=$(jget "$s" dgram_flows)
      sum_in=$(awk -v a="$sum_in" -v b="${u_in:-0}" 'BEGIN{printf "%.0f", a+b}')
      sum_out=$(awk -v a="$sum_out" -v b="${u_out:-0}" 'BEGIN{printf "%.0f", a+b}')
      sum_rate=$(awk -v a="$sum_rate" -v b="${u_rate:-0}" 'BEGIN{printf "%.0f", a+b}')
      sum_sess=$(( sum_sess + ${u_sess:-0} ))
      sum_str=$(( sum_str + ${u_str:-0} ))
      sum_df=$(( sum_df + ${u_df:-0} ))
      u_al=$(jget "$s" alive)
      if [ "$u_al" = true ] || { [ "${u_sess:-0}" -gt 0 ] 2>/dev/null; }; then
        [ "$u_al" = true ] && { any_up=1; primary_raw=$s; }
        u_rtt=$(jget_flat "$s" rtt_ms srtt_ms); u_mr=$(jget "$s" min_rtt_ms); u_ls=$(jget "$s" loss_pct)
        awk -v r="${u_rtt:-0}" 'BEGIN{exit !(r < 0.5)}' && u_rtt=${u_mr:-0}
        if [ -z "$best_rtt" ] || awk -v a="${u_rtt:-0}" -v b="$best_rtt" 'BEGIN{exit !(a > 0 && (b <= 0 || a < b))}'; then
          best_rtt=${u_rtt:-0}; best_mr=${u_mr:-0}; best_ls=${u_ls:-0}
        fi
        if [ "$u" = "$1" ]; then
          ulive=$({ grep -o '"clients": *\[[^]]*\]' <<<"$s" | sed 's/},[[:space:]]*{/}\n{/g' | grep -o '"carrier": *"[^"]*"' | cut -d'"' -f4
            grep -o '"carriers": *\[[^]]*\]' <<<"$s" | sed 's/},[[:space:]]*{/}\n{/g' | grep '"alive": *true' | grep -o '"name": *"[^"]*"' | cut -d'"' -f4
          } | sed '/^$/d' | sort -u)
          if [ -z "$ulive" ]; then
            one=$(cfg "$u" carrier); case "$one" in *+*|'') ;; *) ulive=$one ;; esac
          fi
          for c in $ulive; do live_pick+="${live_pick:++}$c"; done
          parse_carriers "$s"
          for ((j=0; j<CAR_COUNT; j++)); do
            if [ "${CAR_ALIVE[$j]}" = true ] || [ "${CAR_MUTED[$j]}" = true ]; then
              m_name+=("${CAR_NAME[$j]}"); m_alive+=("${CAR_ALIVE[$j]}"); m_rtt+=("${CAR_RTT[$j]}")
              m_loss+=("${CAR_LOSS[$j]}"); m_share+=("${CAR_SHARE[$j]}"); m_muted+=("${CAR_MUTED[$j]}")
            fi
          done
        elif [ "$u" = "$1-r" ]; then
          ulive=$(grep -o '"carriers": *\[[^]]*\]' <<<"$s" | sed 's/},[[:space:]]*{/}\n{/g' | grep '"alive": *true' | grep -o '"name": *"[^"]*"' | cut -d'"' -f4 | sort -u)
          if [ -z "$ulive" ]; then
            one=$(cfg "$u" carrier); case "$one" in *+*|'') ;; *) ulive=$one ;; esac
          fi
          for c in $ulive; do live_pick+="${live_pick:++}r:$c"; done
          parse_carriers "$s"
          for ((j=0; j<CAR_COUNT; j++)); do
            if [ "${CAR_ALIVE[$j]}" = true ] || [ "${CAR_MUTED[$j]}" = true ]; then
              m_name+=("r:${CAR_NAME[$j]}"); m_alive+=("${CAR_ALIVE[$j]}"); m_rtt+=("${CAR_RTT[$j]}")
              m_loss+=("${CAR_LOSS[$j]}"); m_share+=("${CAR_SHARE[$j]}"); m_muted+=("${CAR_MUTED[$j]}")
            fi
          done
        else
          c=${u#"$1"-e-}
          live_pick+="${live_pick:++}$c"
          m_name+=("$c"); m_alive+=(true); m_rtt+=("${u_rtt:-0}")
          m_loss+=("$(awk -v l="${u_ls:-0}" 'BEGIN{printf "%.4f", l/100}')")
          m_share+=(1); m_muted+=(false)
        fi
      fi
    done
    [ "$on" = 1 ] || return 0
    if [ "$any_up" = 1 ]; then TI_STATE=up; TI_WHY=''
    elif [ "$miss" -gt 0 ]; then TI_STATE=unknown; TI_WHY='stats did not answer, status not known'; return 0
    else TI_STATE=down; fi
    TI_RAW=$primary_raw
    TI_IN=$sum_in; TI_OUT=$sum_out; TI_RATE=$sum_rate; TI_SESS=$sum_sess; TI_STREAMS=$sum_str; TI_DGRAM_FLOWS=$sum_df
    TI_RTT=${best_rtt:-0}; TI_MIN_RTT=${best_mr:-0}; TI_LOSS=${best_ls:-0}
    TI_LIVE_PICK=$live_pick
    TI_LIVE=${live_pick:-$(cfg "$1" carrier)}
    CAR_NAME=("${m_name[@]+"${m_name[@]}"}"); CAR_ALIVE=("${m_alive[@]+"${m_alive[@]}"}")
    CAR_RTT=("${m_rtt[@]+"${m_rtt[@]}"}"); CAR_LOSS=("${m_loss[@]+"${m_loss[@]}"}")
    CAR_SHARE=("${m_share[@]+"${m_share[@]}"}"); CAR_MUTED=("${m_muted[@]+"${m_muted[@]}"}")
    CAR_COUNT=${#CAR_NAME[@]}; TI_CAR_COUNT=$CAR_COUNT
    return 0
  else
    local other=''
    [ "$(companion_of "$1-r")" = "$1" ] && other=$1-r
    systemctl is-active -q "${WAT_PREFIX}@$1" 2>/dev/null && on=1
    if [ -n "$other" ] && systemctl is-active -q "${WAT_PREFIX}@$other" 2>/dev/null; then
      s=$(stats "$other") || s=$(stats "$other") || miss=1
    fi
    if [ "$on" = 1 ]; then
      TI_RAW=$(stats "$1") || TI_RAW=$(stats "$1") || TI_RAW=''
      if [ -z "$TI_RAW" ]; then TI_STATE=unknown; TI_WHY='stats did not answer, status not known'; return 0; fi
    elif [ -z "$par" ] && [ -n "$s" ]; then TI_RAW=$s
    elif [ -z "$par" ] && [ "$miss" = 1 ]; then TI_STATE=unknown; TI_WHY="$other stats did not answer, status not known"; return 0
    else return 0; fi
    if [ "$on" = 1 ] && [ "$(jget "$TI_RAW" alive)" = true ]; then TI_STATE=up
    elif [ "$miss" = 1 ]; then TI_STATE=unknown; TI_WHY="$other stats did not answer, status not known"
    elif [ "$(jget "$s" alive)" != true ]; then TI_STATE=down
    elif [ -n "$par" ]; then TI_STATE=standby; TI_WHY="not in use, the entry server is connected through $par"
    else TI_STATE=up; TI_RAW=$s; TI_WHY="The entry server is connected through $other"; fi
  fi
  TI_RTT=$(jget_flat "$TI_RAW" rtt_ms srtt_ms); TI_MIN_RTT=$(jget "$TI_RAW" min_rtt_ms); TI_LOSS=$(jget "$TI_RAW" loss_pct)
  TI_STREAMS=$(jget_flat "$TI_RAW" streams_total streams); TI_SESS=$(jget "$TI_RAW" sessions); TI_DGRAM_FLOWS=$(jget "$TI_RAW" dgram_flows)
  TI_IN=$(jget "$TI_RAW" bytes_in_total); TI_OUT=$(jget "$TI_RAW" bytes_out_total); TI_RATE=$(jget "$TI_RAW" rate_bps)
  [ -n "$TI_IN" ] || { TI_IN=$(jget "$TI_RAW" bytes_in); TI_OUT=$(jget "$TI_RAW" bytes_out); } # before 2.4.19: since the last restart
  awk -v r="${TI_RTT:-0}" 'BEGIN{exit !(r < 0.5)}' && TI_RTT=${TI_MIN_RTT:-0} # a server between samples reports srtt 0
  : "${TI_RTT:=0}" "${TI_MIN_RTT:=0}" "${TI_LOSS:=0}" "${TI_STREAMS:=0}" "${TI_SESS:=0}" "${TI_DGRAM_FLOWS:=0}" "${TI_IN:=0}" "${TI_OUT:=0}" "${TI_RATE:=0}"
  parse_carriers "$TI_RAW"
  TI_CAR_COUNT=$CAR_COUNT
  if [ "$CAR_COUNT" -gt 0 ]; then
    local j; TI_LIVE=''
    for ((j=0; j<CAR_COUNT; j++)); do [ "${CAR_ALIVE[$j]}" = true ] && TI_LIVE+="${TI_LIVE:++}${CAR_NAME[$j]}"; done
  fi
  if [ "$TI_STATE" = up ] && [ "$CAR_COUNT" -gt 0 ] && [ "$TI_AUTO" = 0 ]; then
    local i unmuted_live=0 unmuted_total=0
    for ((i=0; i<CAR_COUNT; i++)); do
      if [ "${CAR_MUTED[$i]}" = true ]; then
        TI_CAR_MUTED=$((TI_CAR_MUTED+1))
      else
        unmuted_total=$((unmuted_total+1))
        [ "${CAR_ALIVE[$i]}" = true ] && unmuted_live=$((unmuted_live+1))
      fi
    done
    TI_CAR_ALIVE=$unmuted_live
    if [ "$unmuted_total" -gt 1 ] && [ "$unmuted_live" -lt "$unmuted_total" ]; then
      TI_STATE=degraded; TI_WHY="$((unmuted_total - unmuted_live)) of $unmuted_total carriers down"
    fi
  fi
}
SC_COL=''; SC_TXT=''; SC_DOT='●'
state_cell() { # role state
  case "$2" in
    up) SC_COL=$GRN; SC_DOT='●'; SC_TXT=up ;;
    degraded) SC_COL=$YEL; SC_DOT='◐'; SC_TXT=partial ;;
    standby) SC_COL=$GRY; SC_DOT='◌'; SC_TXT=standby ;;
    unknown) SC_COL=$YEL; SC_DOT='◐'; SC_TXT=unknown ;;
    down) SC_COL=$RED; SC_DOT='○'; if [ "$1" = Kharej ]; then SC_TXT=waiting; else SC_TXT=down; fi ;;
    *) SC_COL=$GRY; SC_DOT='◌'; SC_TXT=stopped ;;
  esac
}
ports_summary() { # name [maxlen] -> "443 · 8443→443 · 53/udp"
  local n=$1 max=${2:-50} out='' piece it cnt=0 total=0
  while IFS= read -r it; do
    [ -n "$it" ] || continue
    total=$((total+1))
    piece=$(spec_human "$it")
    [ "$(role "$n")" = Kharej ] && { piece=$(spec_T "$it"); [ "$(spec_P "$it")" = udp ] && piece="$piece/udp"; }
    if [ $(( ${#out} + ${#piece} + 5 )) -gt "$max" ]; then continue; fi
    out="${out:+$out · }$piece"; cnt=$((cnt+1))
  done < <(yml_maps "$n")
  if [ "$total" -eq 0 ]; then [ "$(role "$n")" = Kharej ] && echo "any port" || echo "no ports yet"; return; fi
  [ "$cnt" -lt "$total" ] && out="$out +$((total-cnt))"
  echo "$out"
}

# ---- dashboard ----
DASH_N=()
dash_row() { # idx name
  local i=$1 n=$2 r cr load rtt tr pl par cols car_display idx_pad='' cs
  cols=$(term_cols)
  r=$(role "$n"); cr=$(carrier_label "$n"); par=$(companion_of "$n")
  tinfo "$n"; state_cell "$r" "$TI_STATE"
  if is_auto_kharej "$n"; then cr=${TI_LIVE_PICK:-auto}; fi # the type Iran picked, once it is connected
  load=''; rtt='-'
  if [ "$TI_STATE" != stopped ]; then
    if [ "$r" = Kharej ]; then load="${TI_SESS}c"; else load="${TI_STREAMS}s"; fi
    if [ "$TI_STATE" = up ] || [ "$TI_STATE" = degraded ]; then
      rtt="$(printf '%.0f ms' "$TI_RTT")"
    fi
  fi
  tr=''; [ "$TI_STATE" != stopped ] && tr="↓$(human "$TI_IN") ↑$(human "$TI_OUT")"
  pl="$(ports_summary "$n" 38)"
  [ -n "$par" ] && pl="reverse of $par"
  cs=$(cdn_summary "$n" short); [ -n "$cs" ] && pl="$pl  ${CYN}[$cs]${RST}"
  if [ "$TI_STATE" != stopped ] && ac_dialer "$n" && is_pool_list "$(cfg "$n" carrier)" \
     && [ -z "$(cfg "$n" fake-sni)$(cfg "$n" pool-rotate)$(cfg "$n" pool-rotate-bytes)" ]; then
    pl="$pl  ${YEL}[anti-censor off]${RST}"
  fi

  [ "$i" -lt 10 ] && idx_pad=' '
  if [ "$cols" -lt 74 ]; then
    if [[ "$cr" == *"+"* ]]; then
      local -a bcnt; IFS='+' read -ra bcnt <<<"$cr"; car_display="bond[${#bcnt[@]}]"
    else
      car_display="${cr:0:8}"
    fi
    printf '  %s%s %-11s %-6s %s%s %-8s%s %5s  %s\n' \
      "$(key_label "$i")" "$idx_pad" "${n:0:11}" "$(role_label "$r")" "$SC_COL" "$SC_DOT" "$SC_TXT" "$RST" "$rtt" "$car_display"
    [ -n "$tr$pl" ] && printf '       %s%s%s\n' "$GRY" "${tr:+$tr · }$pl" "$RST"
  else
    car_display="${cr:0:12}"
    printf '  %s%s %-14s %-6s %-12s %s%s %-8s%s %6s  %s\n' \
      "$(key_label "$i")" "$idx_pad" "${n:0:14}" "$(role_label "$r")" "$car_display" "$SC_COL" "$SC_DOT" "$SC_TXT" "$RST" "$rtt" "${tr:+$tr · }${load}"
    [ -n "$pl" ] && printf '       %s%s%s\n' "$GRY" "$pl" "$RST"
  fi
}
dash_table() {
  local n i=0 cols; DASH_N=()
  cols=$(term_cols)
  for n in $(listed_tunnels); do DASH_N+=("$n"); done
  if [ "${#DASH_N[@]}" -eq 0 ]; then
    printf '  No tunnels configured. Press %s to create one' "$(key_label n)"
    case "$(server_side)" in
      kharej) printf ' (Kharej).\n' ;;
      iran) printf ' (paste token from Kharej).\n' ;;
      *) printf ' (Kharej first, then Iran).\n' ;;
    esac
    return 0
  fi
  if [ "$cols" -lt 74 ]; then
    printf '  %s%-4s %-11s %-6s %-10s %5s  %s%s\n' "$GRY" '#' NAME ROLE STATE RTT CARRIER "$RST"
  else
    printf '  %s%-4s %-14s %-6s %-12s %-10s %6s  %s%s\n' "$GRY" '#' NAME ROLE CARRIER STATE RTT TRAFFIC "$RST"
  fi
  for n in "${DASH_N[@]}"; do i=$((i+1)); dash_row "$i" "$n"; done
}
dash_actions() {
  local cnt=${#DASH_N[@]} open=()
  [ "$cnt" -eq 1 ] && open=(1 open)
  [ "$cnt" -gt 1 ] && open=("1-$cnt" open)
  echo; hr
  if [ "$cnt" -gt 0 ]; then
    menu_line ${open[@]+"${open[@]}"} n new a batch m monitor s settings u update q quit
  else
    menu_line n new s settings u update q quit
  fi
}

# ======================================================================================
#  Firewall, service helpers
# ======================================================================================
fw_open() { # "443/tcp 53/udp" ...
  local list=$* fw='' p
  [ -n "$list" ] || return 0
  if command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q "Status: active"; then fw=ufw
  elif command -v firewall-cmd >/dev/null && firewall-cmd --state >/dev/null 2>&1; then fw=firewalld; fi
  if [ -z "$fw" ]; then
    hint "Open $list in your provider's firewall, if it has one."; return 0
  fi
  for p in $list; do
    if [ "$fw" = ufw ]; then ufw allow "$p" >/dev/null && ok "ufw: allowed $p"
    else firewall-cmd -q --permanent --add-port="$p" && ok "firewalld: allowed $p"; fi
  done
  [ "$fw" = firewalld ] && firewall-cmd -q --reload
  return 0
}
fw_kind() { # prints ufw, firewalld or nothing
  if command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q "Status: active"; then echo ufw
  elif command -v firewall-cmd >/dev/null && firewall-cmd --state >/dev/null 2>&1; then echo firewalld; fi
}
fw_close() { # "443/tcp 53/udp" ... : mirror of fw_open, never asks
  local fw p; fw=$(fw_kind); [ -n "$fw" ] || return 0
  for p in $*; do
    if [ "$fw" = ufw ]; then ufw delete allow "$p" >/dev/null 2>&1 && ok "ufw: closed $p"
    else firewall-cmd -q --permanent --remove-port="$p" 2>/dev/null && ok "firewalld: closed $p"; fi
  done
  [ "$fw" = firewalld ] && firewall-cmd -q --reload
  return 0
}

# ======================================================================================
#  Iran-only client ports
# ======================================================================================
IRAN_IPSET="wattun_iran"
IRAN_IP_URL="https://www.ipdeny.com/ipblocks/data/countries/ir.zone"
IRAN_CACHE_FILE="$CONF/.iran_cidrs.zone"

iran_fw_ports() { # returns space-separated list of all local client ports on this Iran server
  local f l p
  local -A seen=()
  for f in "$CONF"/*.yml; do
    [ -f "$f" ] || continue
    [ "$(grep '^mode:' "$f" | awk '{print $2}')" = client ] || [ "$(grep '^mode:' "$f")" = "" ] || continue
    while IFS= read -r l; do
      p=$(echo "$l" | awk '{print $2}' | tr -d '"'"'" | cut -d: -f1 | cut -d- -f1 | cut -d/ -f1)
      if [[ "$p" =~ ^[0-9]+$ ]] && [ "$p" -ge 1 ] && [ "$p" -le 65535 ]; then
        seen["$p"]=1
      fi
    done < <(grep -E '^[[:space:]]*-[[:space:]]+[0-9]+' "$f" 2>/dev/null)
  done
  echo "${!seen[@]}"
}

iran_fw_fetch() {
  mkdir -p "$CONF"
  spin_start "Downloading official the entry server IPv4 ranges (ipdeny.com)"
  curl -fsSL --max-time 15 "$IRAN_IP_URL" -o "$CONF/.iran_cidrs.zone.tmp" 2>/dev/null
  local rc=$?
  spin_stop
  if [ $rc -eq 0 ] && [ -s "$CONF/.iran_cidrs.zone.tmp" ]; then
    mv -f "$CONF/.iran_cidrs.zone.tmp" "$IRAN_CACHE_FILE"
    ok "Downloaded $(wc -l < "$IRAN_CACHE_FILE") Iranian CIDR blocks."
    return 0
  fi
  rm -f "$CONF/.iran_cidrs.zone.tmp"
  if [ -s "$IRAN_CACHE_FILE" ]; then
    warn "Download failed; using previously cached the entry server CIDR list ($(wc -l < "$IRAN_CACHE_FILE") ranges)."
    return 0
  fi
  err "Download failed and there is no cached list, so nothing was changed. Check this server's internet access and try again."
  return 1
}

iran_fw_apply() { # ports...
  local ports="$*"
  [ -n "$ports" ] || ports=$(iran_fw_ports)
  [ -n "$ports" ] || { err "No client ports found or specified. Usage: $SELF iran-firewall on [port,port...]"; return 1; }

  if ! command -v ipset >/dev/null 2>&1; then
    step "Installing ipset" apt-get update -qq && apt-get install -y -qq ipset || { err "Failed to install ipset."; return 1; }
  fi
  iran_fw_fetch || return 1

  step "Creating ipset $IRAN_IPSET" ipset create "$IRAN_IPSET" hash:net maxelem 65536 -exist
  step "Populating Iranian IP blocks into ipset" bash -c "
    while IFS= read -r net; do
      [[ \"\$net\" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$ ]] && ipset add -exist '$IRAN_IPSET' \"\$net\"
    done < '$IRAN_CACHE_FILE'
  "
  local cnt
  cnt=$(ipset list "$IRAN_IPSET" 2>/dev/null | grep -c '^[0-9]')
  if [ "${cnt:-0}" -lt 50 ]; then # a real list has hundreds of ranges; a short one is a bad download and would lock everyone out
    ipset destroy "$IRAN_IPSET" 2>/dev/null
    err "The Iran range list has only ${cnt:-0} entries (expected hundreds). Nothing was changed."; return 1
  fi

  local p pt
  for p in $ports; do
    p=${p//,/ }
    for pt in $p; do
      [[ "$pt" =~ ^[0-9]+$ ]] || continue
      iptables -D INPUT -p tcp --dport "$pt" -m set --match-set "$IRAN_IPSET" src -j ACCEPT 2>/dev/null || true
      iptables -D INPUT -p tcp --dport "$pt" -j DROP 2>/dev/null || true
      iptables -D INPUT -p udp --dport "$pt" -m set --match-set "$IRAN_IPSET" src -j ACCEPT 2>/dev/null || true
      iptables -D INPUT -p udp --dport "$pt" -j DROP 2>/dev/null || true

      iptables -I INPUT -p tcp --dport "$pt" -j DROP
      iptables -I INPUT -p tcp --dport "$pt" -m set --match-set "$IRAN_IPSET" src -j ACCEPT
      iptables -I INPUT -p udp --dport "$pt" -j DROP
      iptables -I INPUT -p udp --dport "$pt" -m set --match-set "$IRAN_IPSET" src -j ACCEPT
      ok "Port $pt: protected (Iran-only allowed, foreign IPs dropped)"
    done
  done

  if command -v netfilter-persistent >/dev/null 2>&1; then
    netfilter-persistent save >/dev/null 2>&1 # the ipset itself is not saved by this: see the note below
  elif [ -d /etc/iptables ]; then
    iptables-save > /etc/iptables/rules.v4 2>/dev/null || true
  fi
  ok "Iran-only protection is ON: client ports accept connections from Iranian addresses only."
  warn "The rules and the address set are not kept across a reboot: run  $SELF iran-firewall on  again after one (or install iptables-persistent and ipset-persistent)."
}

iran_fw_remove() { # [ports...]
  local ports="$*"
  [ -n "$ports" ] || ports=$(iran_fw_ports)
  local p pt
  for p in $ports; do
    p=${p//,/ }
    for pt in $p; do
      [[ "$pt" =~ ^[0-9]+$ ]] || continue
      iptables -D INPUT -p tcp --dport "$pt" -m set --match-set "$IRAN_IPSET" src -j ACCEPT 2>/dev/null || true
      iptables -D INPUT -p tcp --dport "$pt" -j DROP 2>/dev/null || true
      iptables -D INPUT -p udp --dport "$pt" -m set --match-set "$IRAN_IPSET" src -j ACCEPT 2>/dev/null || true
      iptables -D INPUT -p udp --dport "$pt" -j DROP 2>/dev/null || true
      ok "Port $pt: protection removed (open to all IPs)"
    done
  done
  ok "Iran-only protection is OFF."
}

iran_fw_status() {
  page "Iran-only client ports"
  if ipset list "$IRAN_IPSET" >/dev/null 2>&1; then
    local cnt
    cnt=$(ipset list "$IRAN_IPSET" 2>/dev/null | grep -c '^[0-9]' || echo 0)
    say "  $(kv 'iran ipset' "${GRN}on${RST} ${GRY}($cnt ranges)${RST}")"
  else
    say "  $(kv 'iran ipset' "${GRY}off${RST}")"
  fi
  say "  $(kv 'client ports' "$(iran_fw_ports)")"
  echo
  say "  ${GRY}iptables rules${RST}"
  local rules
  rules=$(iptables -S INPUT 2>/dev/null | grep "$IRAN_IPSET" || true)
  if [ -n "$rules" ]; then
    printf '%s\n' "$rules" | sed "s/^/    $GRN/; s/\$/$RST/"
  else
    say "    ${GRY}none${RST}"
  fi
}

iran_firewall_cmd() {
  case "${1:-}" in
    on|enable) shift; iran_fw_apply "$@" ;;
    off|disable) shift; iran_fw_remove "$@" ;;
    status) iran_fw_status ;;
    update) iran_fw_fetch && ok "Updated cached the entry server CIDRs." ;;
    *)
      page "Iran-only client ports"
      say "  Limits your client ports to connections from Iranian addresses."
      say "  Incoming client connections on your proxy ports will only be accepted from Iranian IPs."
      say "  Connections from other countries (scanners, probes, and your own users abroad) are dropped."
      echo
      say "  Commands:"
      say "    ${CYN}wattun iran-firewall on${RST}      [ports] - activate Iran-only protection"
      say "    ${CYN}wattun iran-firewall off${RST}     [ports] - disable protection"
      say "    ${CYN}wattun iran-firewall status${RST}  - view status and active rules"
      say "    ${CYN}wattun iran-firewall update${RST}  - refresh Iranian IP range list"
      echo
      confirm "Toggle protection now?" y || return 0
      if iptables -S INPUT 2>/dev/null | grep -q "$IRAN_IPSET"; then
        iran_fw_remove
      else
        iran_fw_apply
      fi
      ;;
  esac
}
unit_up() { # name : enable + start, wait up to 10 s for "active"
  local i
  ensure_template || return 1
  systemctl --quiet enable --now "${WAT_PREFIX}@$1" || return 1
  for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20; do
    systemctl is-active -q "${WAT_PREFIX}@$1" && { sleep 1; systemctl is-active -q "${WAT_PREFIX}@$1" && return 0; }
    sleep 0.5
  done
  return 1
}
auto_for_each_unit() { # parent action(start|stop|restart|enable|disable)
  local parent=$1 act=$2 u
  local -a units=("$parent")
  if is_auto_kharej "$parent"; then
    while IFS= read -r u; do [ -n "$u" ] && units+=("$u"); done < <(auto_helpers "$parent")
  fi
  for u in "${units[@]}"; do
    case "$act" in
      start) unit_up "$u" >/dev/null 2>&1 || [ "$u" != "$parent" ] || return 1 ;;
      stop) systemctl stop "${WAT_PREFIX}@$u" >/dev/null 2>&1 ;;
      restart) systemctl restart "${WAT_PREFIX}@$u" >/dev/null 2>&1 || [ "$u" != "$parent" ] || return 1 ;;
      enable) systemctl enable "${WAT_PREFIX}@$u" >/dev/null 2>&1 ;;
      disable) systemctl disable "${WAT_PREFIX}@$u" >/dev/null 2>&1 ;;
    esac
  done
  if [ "$act" = stop ] && is_auto_kharej "$parent"; then
    systemctl stop "${WAT_PREFIX}-autowatch-$parent.service" >/dev/null 2>&1
    systemctl reset-failed "${WAT_PREFIX}-autowatch-$parent.service" >/dev/null 2>&1
  fi
  return 0
}
start_unit() { # name : with feedback (starts hidden auto helpers too)
  local n=$1 u
  # a process left from an earlier config (same name) would keep its old peer and listen
  systemctl is-active -q "${WAT_PREFIX}@$n" && systemctl restart "${WAT_PREFIX}@$n" 2>/dev/null
  if step "Starting ${WAT_PREFIX}@$n" unit_up "$n"; then
    if is_auto_kharej "$n"; then
      for u in $(auto_helpers "$n"); do unit_up "$u" >/dev/null 2>&1 || true; done
    fi
    return 0
  fi
  err "Tunnel '$n' failed to start. Last log lines:"; journalctl -u "${WAT_PREFIX}@$n" -n 15 --no-pager -o cat 2>/dev/null; return 1
}
link_alive() { [ "$(jget "$(stats_flat "$1")" alive)" = true ]; }
wait_link() { # name seconds : spinner + progress bar while waiting for the link
  local n=$1 max=${2:-25} t0=$SECONDS el i=0 f
  if is_reverse "$n" && [ "$max" -lt 45 ]; then max=45; fi # Kharej reverse dialer backoff is up to 30 s
  [ "$ANIM" = 1 ] && cur_hide || printf '  Waiting for the link (up to %ss)...\n' "$max"
  while :; do
    if link_alive "$n"; then
      [ "$ANIM" = 1 ] && { printf '\r\e[K'; cur_show; }
      LINK_RTT=$(ms "$(jget_flat "$(stats_flat "$n")" rtt_ms srtt_ms)"); return 0
    fi
    el=$((SECONDS-t0))
    if [ "$el" -ge "$max" ] || ! systemctl is-active -q "${WAT_PREFIX}@$n" 2>/dev/null; then break; fi
    if [ "$ANIM" = 1 ]; then
      for f in 1 2 3 4; do
        printf '\r\e[K  %s%s%s Waiting for the link  [%s]  %ds / %ds' "$CYN" "${SPIN_FR[$((i%10))]}" "$RST" "$(bar "$el" "$max" 20)" "$el" "$max"
        i=$((i+1)); sleep 0.12
      done
    else sleep 1; fi
  done
  [ "$ANIM" = 1 ] && { printf '\r\e[K'; cur_show; }
  return 1
}

# ======================================================================================
#  Port mapping editor
#    uses: MAPS (canonical items), PE_ROLE (Iran|Kharej), PE_TUNNEL (name or ''),
#          PE_ALLOW (Kharej's allow list from the token, may be empty), PE_OWNED (ports this tunnel already owns)
# ======================================================================================
MAPS=(); PE_ROLE=Iran; PE_TUNNEL=''; PE_ALLOW=(); PE_OWNED=(); PE_MSG=''
pe_owned_has() { local o; for o in ${PE_OWNED[@]+"${PE_OWNED[@]}"}; do [ "$o" = "$1" ] && return 0; done; return 1; }
pe_msg() { PE_MSG+="$1"$'\n'; }
pe_try_add() { # canonical [replace-index] : validate and add/replace ; rc 1 + message when rejected
  local item=$1 idx=${2:--1} i L T P who u
  L=$(spec_L "$item"); T=$(spec_T "$item"); P=$(spec_P "$item")
  if [ "$PE_ROLE" = Kharej ] && [ "$L" != "$T" ]; then
    pe_msg "${RED}✘${RST} $(spec_human "$item"): on the exit list only the port your service uses (like 443 or 53/udp)."; return 1
  fi
  for ((i=0; i<${#MAPS[@]}; i++)); do
    [ "$i" = "$idx" ] && continue
    if [ "$PE_ROLE" = Iran ]; then
      [ "$(spec_L "${MAPS[$i]}")" = "$L" ] && [ "$(spec_P "${MAPS[$i]}")" = "$P" ] && { pe_msg "${RED}✘${RST} Entry port $L/$P is already mapped (row $((i+1)))."; return 1; }
    else
      [ "$(spec_T "${MAPS[$i]}")" = "$T" ] && [ "$(spec_P "${MAPS[$i]}")" = "$P" ] && { pe_msg "${RED}✘${RST} Port $T/$P is already in the list (row $((i+1)))."; return 1; }
    fi
  done
  if [ "$PE_ROLE" = Iran ]; then
    if ! pe_owned_has "$L/$P" && port_busy "$L" "$P"; then
      u=$(port_user "$L" "$P"); pe_msg "${RED}✘${RST} Port $L/$P is already in use on this server${u:+ by $u}. Pick another entry port."; return 1
    fi
    who=$(tunnel_using_public "$L" "$P" "$PE_TUNNEL") && { pe_msg "${RED}✘${RST} Port $L/$P is already published by tunnel '$who'."; return 1; }
    allowed_has "$T" "$P" || pe_msg "${YEL}!${RST} The exit server does not allow $T/$P. Add it to the exit server's ports or it will be refused."
  else
    if [ "$P" = tcp ] && ! timeout 1 bash -c "</dev/tcp/127.0.0.1/$T" 2>/dev/null; then
      pe_msg "${YEL}!${RST} Nothing answers on 127.0.0.1:$T yet. Fine if you start your service later."
    fi
  fi
  if [ "$idx" -ge 0 ]; then MAPS[idx]=$item; else MAPS+=("$item"); fi
  return 0
}
pe_draw() {
  local i it L T P mark warned=0 bad
  page "Ports" "${PE_TUNNEL:-new tunnel} · $PE_ROLE"
  if [ "$PE_ROLE" = Iran ]; then
    printf '  %s%3s  %-19s      %-23s %s%s\n' "$GRY" '#' 'Listen' 'Target' 'Proto' "$RST"
  else
    printf '  %s%3s  %-31s %s%s\n' "$GRY" '#' 'Port' 'Proto' "$RST"
  fi
  if [ "${#MAPS[@]}" -eq 0 ]; then
    if [ "$PE_ROLE" = Kharej ]; then printf '  %s     all ports allowed%s\n' "$GRY" "$RST"
    else printf '  %s     none yet%s\n' "$GRY" "$RST"; fi
  fi
  for ((i=0; i<${#MAPS[@]}; i++)); do
    it=${MAPS[$i]}; L=$(spec_L "$it"); T=$(spec_T "$it"); P=$(spec_P "$it"); mark=' '
    if [ "$PE_ROLE" = Iran ]; then
      allowed_has "$T" "$P" || { mark="${YEL}!${RST}"; warned=1; }
      printf '  %s%3s%s  %-19s ──►  %-23s %-5s %s\n' "$GRY" $((i+1)) "$RST" "$L" "$T" "$P" "$mark"
    else
      printf '  %s%3s%s  %-31s %s\n' "$GRY" $((i+1)) "$RST" "$T" "$P"
    fi
  done
  [ "$warned" = 1 ] && hint "! Port not in the exit server allowlist"
  if [ "$PE_ROLE" = Iran ] && [ "${#PE_ALLOW[@]}" -gt 0 ]; then
    bad=''; for it in "${PE_ALLOW[@]}"; do bad="$bad $(spec_T "$it")/$(spec_P "$it")"; done
    hint "Exit server allows:${bad//\/tcp/}"
  fi
  echo
  if [ -n "$PE_MSG" ]; then printf '%b' "${PE_MSG}" | sed 's/^/  /'; echo; PE_MSG=''; fi
  if [ "$PE_ROLE" = Iran ]; then
    hint "Add: 443 · 8443:443 · 53/udp"
    hint "Note: encrypts entry server <-> exit server only; use TLS, Reality or Shadowsocks on panel inbound."
  else hint "Add: 443 · 8443 · 53/udp"; fi
  menu_line Enter save a add 'e #' edit 'r #' remove c clear 'f NAME' copy q cancel
}
pe_bulk() {
  local line=$1 tok toks=() before=${#MAPS[@]} it
  read -ra toks <<<"${line//[,;]/ }"
  for tok in "${toks[@]}"; do
    if norm_spec "$tok"; then for it in "${NS_OUT[@]}"; do pe_try_add "$it"; done
    else pe_msg "${RED}✘${RST} $NS_ERR"; fi
  done
  [ "${#MAPS[@]}" -gt "$before" ] && pe_msg "${GRN}✔${RST} Added $((${#MAPS[@]}-before))."
  return 0
}
pe_guided_add() {
  local l t p it
  if [ "$PE_ROLE" = Iran ]; then
    echo; ask_ok "The entry port (users connect here)" "" v_port || { pe_msg "Cancelled."; return; }; l=$((10#$REPLY_V))
    ask_ok "The exit port (where your service listens)" "$l" v_port || { pe_msg "Cancelled."; return; }; t=$((10#$REPLY_V))
  else
    echo; ask_ok "Port of your service on this server" "" v_port || { pe_msg "Cancelled."; return; }; t=$((10#$REPLY_V)); l=$t
  fi
  ask "Protocol: tcp, udp or both" tcp; p=${REPLY_V,,}
  if norm_spec "$l:$t/$p"; then for it in "${NS_OUT[@]}"; do pe_try_add "$it"; done; else pe_msg "${RED}✘${RST} $NS_ERR"; fi
}
pe_pick_index() { # arg -> PE_IDX (0-based) ; asks when missing
  local a=$1
  if [ -z "$a" ]; then ask "Row number" ""; a=$REPLY_V; fi
  if [[ "$a" =~ ^[0-9]+$ ]] && [ "$a" -ge 1 ] && [ "$a" -le "${#MAPS[@]}" ]; then PE_IDX=$((a-1)); return 0; fi
  pe_msg "${RED}✘${RST} No such row '$a'."; return 1
}
PE_IDX=0
pe_edit() {
  local l t p it cur
  pe_pick_index "$1" || return 0
  cur=${MAPS[$PE_IDX]}; p=$(spec_P "$cur")
  echo
  if [ "$PE_ROLE" = Iran ]; then
    ask_ok "Entry port" "$(spec_L "$cur")" v_port || return 0; l=$((10#$REPLY_V))
    ask_ok "Exit port" "$(spec_T "$cur")" v_port || return 0; t=$((10#$REPLY_V))
  else
    ask_ok "Port" "$(spec_T "$cur")" v_port || return 0; t=$((10#$REPLY_V)); l=$t
  fi
  ask "Protocol: tcp or udp" "$p"; p=${REPLY_V,,}
  case $p in tcp|udp) ;; *) pe_msg "${RED}✘${RST} Protocol must be tcp or udp here (to get both, add a second row)."; return 0 ;; esac
  norm_spec "$l:$t/$p" && { pe_try_add "${NS_OUT[0]}" "$PE_IDX" && pe_msg "${GRN}✔${RST} Row $((PE_IDX+1)) updated."; }
  return 0
}
pe_remove() {
  local a=$1 x out=() i keep drop=()
  if [ -z "$a" ]; then ask "Row number(s) to remove (e.g. 2 or 1,3)" ""; a=$REPLY_V; fi
  [ -n "$a" ] || return 0
  for x in ${a//,/ }; do
    if [[ "$x" =~ ^[0-9]+$ ]] && [ "$x" -ge 1 ] && [ "$x" -le "${#MAPS[@]}" ]; then drop+=("$x"); else pe_msg "${RED}✘${RST} No such row '$x'."; fi
  done
  [ "${#drop[@]}" -gt 0 ] || return 0
  for ((i=0; i<${#MAPS[@]}; i++)); do
    keep=1; for x in "${drop[@]}"; do [ "$x" = $((i+1)) ] && keep=0; done
    [ "$keep" = 1 ] && out+=("${MAPS[$i]}")
  done
  MAPS=("${out[@]+"${out[@]}"}")
  pe_msg "${GRN}✔${RST} Removed."
}
pe_from() { # name : bring in the port rows of another tunnel, optionally moving them
  local n=$1 it c L P who s added=0 held=0 bad=0 src=() keep=() save=()
  [ -n "$n" ] || { pe_msg "Type: ${BOLD}from NAME${RST}   (NAME = another tunnel on this server)"; return 0; }
  [ -f "$CONF/$n.yml" ] || { pe_msg "${RED}✘${RST} No tunnel named '$n'."; return 0; }
  [ "$n" = "${PE_TUNNEL:-}" ] && { pe_msg "${YEL}!${RST} That is this tunnel."; return 0; }
  while IFS= read -r it; do [ -n "$it" ] && src+=("$it"); done < <(yml_maps "$n")
  [ "${#src[@]}" -gt 0 ] || { pe_msg "${YEL}!${RST} '$n' publishes no ports."; return 0; }
  confirm "Add the ${#src[@]} port(s) of '$n' to this list? (the rows you already have stay)" y || return 0
  for it in "${src[@]}"; do
    L=$(spec_L "$it"); P=$(spec_P "$it"); c=0
    for s in ${MAPS[@]+"${MAPS[@]}"}; do
      [ "$(spec_L "$s")" = "$L" ] && [ "$(spec_P "$s")" = "$P" ] && c=1
    done
    [ "$c" = 1 ] && continue
    who=$(tunnel_using_public "$L" "$P" "$PE_TUNNEL")
    if [ -n "$who" ] && [ "$who" != "$n" ]; then
      pe_msg "${RED}✘${RST} $L/$P is published by '$who'."; bad=$((bad+1)); continue
    fi
    MAPS+=("$it"); added=$((added+1)); held=$((held+1))
  done
  pe_msg "${GRN}✔${RST} $added port(s) copied from '$n'."
  [ "$bad" -gt 0 ] && pe_msg "${YEL}!${RST} $bad skipped: another tunnel publishes them."
  # the same Iran port cannot be published twice: offer to finish the move on the other tunnel
  if [ "$held" -gt 0 ] && confirm "'$n' still publishes $held of them: remove them from '$n' now? (a move; both reload in 3 s)" y; then
    save=("${MAPS[@]+"${MAPS[@]}"}")
    load_maps "$n"; keep=()
    for it in ${MAPS[@]+"${MAPS[@]}"}; do
      c=0
      for s in "${save[@]}"; do [ "$it" = "$s" ] && { c=1; break; }; done
      [ "$c" = 0 ] && keep+=("$it")
    done
    MAPS=("${keep[@]+"${keep[@]}"}")
    if write_ports "$n"; then ok "Moved $held port(s) off '$n'."
    else err "Could not rewrite '$n'; its ports were left as they were."; fi
    MAPS=("${save[@]+"${save[@]}"}")
  fi
}

port_editor() { # rc 0 = done (MAPS ready), 1 = cancelled
  local line cmd arg msg
  if [ "$NONINTERACTIVE" = 1 ]; then # --map replaces what the token pre-filled; otherwise keep the pre-filled rows
    if [ -n "$NI_MAP" ]; then MAPS=(); PE_MSG=''; pe_bulk "$NI_MAP"; fi
    msg=$PE_MSG; PE_MSG=''
    [ -n "$msg" ] && printf '%b' "$msg" | sed 's/^/  /'
    if [[ "$msg" == *✘* ]]; then err "Some ports were rejected (see above). Fix them with --map LISTEN:TARGET[,..]"; return 1; fi
    if [ "$PE_ROLE" = Iran ] && [ "${#MAPS[@]}" -eq 0 ]; then err "No ports to publish: give --map LISTEN:TARGET[,..] (example: --map 8443:443)"; return 1; fi
    return 0
  fi
  while :; do
    pe_draw
    printf '  %s▸%s ' "$CYN" "$RST"
    IFS= read -r line || eof_exit
    line=${line#"${line%%[![:space:]]*}"}; line=${line%"${line##*[![:space:]]}"}
    cmd=${line%% *}; arg=''; [[ "$line" == *" "* ]] && arg=${line#* }
    case "${cmd,,}" in
      ''|d|done|ok)
        if [ "$PE_ROLE" = Iran ] && [ "${#MAPS[@]}" -eq 0 ]; then pe_msg "${YEL}!${RST} Add at least one port first (example: 443)."; continue; fi
        if [ "$PE_ROLE" = Kharej ] && [ "${#MAPS[@]}" -eq 0 ]; then
          if ! confirm "No list: the entry server can reach any port on this server. Save?" n; then continue; fi
        fi
        return 0 ;;
      q|quit|cancel|esc|b|back) return 1 ;;
      a|add) pe_guided_add ;;
      e|edit) pe_edit "$arg" ;;
      r|rm|remove|del|delete) pe_remove "$arg" ;;
      c|clear) MAPS=(); pe_msg "Cleared." ;;
      f|from|copy) pe_from "$arg" ;;
      '?'|h|help) pe_msg "Examples: 443   8443:443   8443->443/udp   53/both   (several at once: 443, 8443:443, 53/udp)"; pe_msg "The entry port = what users connect to on this server. The exit port = your service." ;;
      *) if [[ "$line" == *[0-9]* ]]; then pe_bulk "$line"; else pe_msg "${YEL}!${RST} Not understood: '$line'. Type ports like 443 or 8443:443, or ? for help."; fi ;;
    esac
  done
}

# ======================================================================================
#  Wizards
# ======================================================================================
CARRIER=''
# A4 (2026-11-04): the interactive Kharej picker gets one "More transports" branch for the 13 F19 shaped carriers. They
# are single-carrier only (the engine refuses shaped-in-bond), need 3.3.0 on both ends, and the raw tier needs root and
# CAP_NET_RAW; the real-protocol warning is reused. The unattended path already accepts them through --carrier.
SHAPED_OPTS=()
shaped_pick_list() { # fills SHAPED_OPTS (raw tier first) in the order the picker numbers them
  local c
  SHAPED_OPTS=()
  for c in $SHAPED_RAW; do SHAPED_OPTS+=("$c"); done
  for c in $SHAPED_UDP; do SHAPED_OPTS+=("$c"); done
}
shaped_pick_index() { # number -> carrier name (pure); rc 1 when the number is not in the list
  local i=${1:-}
  shaped_pick_list
  [[ "$i" =~ ^[0-9]{1,2}$ ]] || return 1
  [ "$((10#$i))" -ge 1 ] && [ "$((10#$i))" -le "${#SHAPED_OPTS[@]}" ] || return 1
  echo "${SHAPED_OPTS[$((10#$i-1))]}"
}
pick_shaped_carrier() { # interactive: numbered shaped list -> REPLY_V ; rc 1 = cancelled
  local i=0 c
  shaped_pick_list
  echo
  say "  ${BOLD}More transports${RST} ${GRY}(advanced; wattun-internal wire shapes, NOT the real protocols)${RST}"
  say "  ${GRY}Both ends need wattun 3.3.0; single carrier only; raw tier needs root/CAP_NET_RAW.${RST}"
  for c in $SHAPED_RAW; do i=$((i+1)); say "   $(key_label "$i") $c  ${GRY}raw tier, IP protocol $(shaped_raw_proto "$c")${RST}"; done
  for c in $SHAPED_UDP; do i=$((i+1)); say "   $(key_label "$i") $c  ${GRY}UDP shape, random open port${RST}"; done
  echo
  ask "Number 1-$i (Enter = cancel)" ""
  [ -n "$REPLY_V" ] || return 1
  REPLY_V=$(shaped_pick_index "$REPLY_V") || { err "No shaped carrier number '$REPLY_V'."; return 1; }
  v_carrier_list "$REPLY_V" || return 1
  shaped_supported_here "$REPLY_V" || return 1
  shaped_warn "$REPLY_V"
  return 0
}
pick_carrier() { # [auto] : with "auto" (Kharej wizard) the first choice is the auto carrier
  local t i n opts=() descs=()
  if [ "${1:-}" = auto ]; then
    opts+=(auto); descs+=("${BOLD}Auto (recommended)${RST}: this server accepts every type; the Iran server tests them all and
        keeps the best. Later, on the Iran server, you can switch to another type or join several (tunnel page, m).")
  fi
  opts+=(icmp udp tcp tls wss ws grpc h2 gre ipip)
  # gre/ipip: raw-IP like icmp; peer must be a bare IP
  descs+=("icmp  ping packets; works when everything else is blocked (the usual case on filtered routes)"
    "udp   fastest and lowest latency, if UDP passes" "tcp   plain TCP, if TCP passes"
    "tls   TCP that looks like a normal HTTPS site" "wss   WebSocket over TLS; works behind Cloudflare or another CDN"
    "ws    WebSocket without TLS (CDN on port 80, or a proxy that adds TLS)" "grpc  gRPC, for CDNs that allow it" "h2    HTTP/2"
    "gre   GRE (IP protocol 47); raw-IP like icmp, root and Linux only" "ipip  IP-in-IP (protocol 4); raw-IP like icmp, root and Linux only")
  n=${#opts[@]}
  if [ "$NONINTERACTIVE" = 1 ]; then
    CARRIER=${NI_CARRIER:-${opts[0]}}
    if [ "$CARRIER" = auto ]; then echo "  carrier: auto"; return 0; fi
    # unattended fixed type: any engine carrier, alone or joined with + (a shaped carrier is allowed too, with a note)
    v_carrier_list "$CARRIER" || return 1
    shaped_supported_here "$CARRIER" || return 1
    echo "  carrier: $CARRIER"; return 0
  fi
  say "  ${BOLD}Connection type${RST}: how the two servers talk to each other"
  for ((i=0; i<n; i++)); do
    case "${opts[$i]}" in
      icmp) [ "${opts[0]}" = auto ] && say "  ${GRY}Or choose one type yourself (fixed; to change it later, make a new tunnel):${RST}"
            say "   ${GRY}Gets through the strictest filters${RST}" ;;
      udp) say "   ${GRY}Fast and simple, if your route lets them through${RST}" ;;
      tls) say "   ${GRY}Looks like web traffic: harder to block, and the only kind a CDN carries${RST}" ;;
    esac
    say "    ${CYN}$((i+1))${RST} ${descs[$i]}"
  done
  say "    ${CYN}0${RST} h2c  HTTP/2 without TLS (a CDN or proxy that terminates TLS)"
  say "    ${CYN}m${RST} More transports (advanced) … 13 shaped carriers, both ends 3.3.0, single only"
  for t in 1 2 3; do
    printf '  %s?%s Press a number %s[1 = %s]%s ' "$CYN" "$RST" "$GRY" "${opts[0]}" "$RST"
    key_read
    case "$KEY" in
      enter) CARRIER=${opts[0]} ;;
      0) CARRIER=h2c ;;
      m|M) if pick_shaped_carrier; then CARRIER=$REPLY_V; echo "$CARRIER"; return 0; fi; continue ;;
      [1-9]) if [ "$KEY" -le "$n" ]; then CARRIER=${opts[$((KEY-1))]}; else echo; warn "Press 1-$n, 0 for h2c, or m for the shaped carriers."; continue; fi ;;
      esc|q) echo; return 1 ;;
      *) echo; warn "Press 1-$n, 0 for h2c, or m for the shaped carriers."; continue ;;
    esac
    echo "$CARRIER"; return 0
  done
  return 1
}
summary_line() { printf '    %s%-14s%s %s\n' "$GRY" "$1" "$RST" "$2"; }

wizard_kharej() {
  local name cr listen='' path='' sni='' itype='' mbps='' fec='' fecb='' addr key m peer allow t rev='' iranip='' advdef=n udpdns='' lisip='' ask='' cdn_mode=0 latch=''
  T_PAIR='' # a stale T_PAIR from an earlier token display must not ride this mint; the default (or an expert row) sets it below
  page "New tunnel" "Exit server"
  [ "$NONINTERACTIVE" = 1 ] || conf_set side kharej
  name=$(suggest_name kharej); [ -n "$NI_NAME" ] && name=$NI_NAME
  # by hand Kharej always opens every type and Iran picks one; a fixed type is for unattended runs (--carrier)
  if [ "$NONINTERACTIVE" = 1 ]; then pick_carrier auto || return 1; cr=$CARRIER; else cr=auto; fi
  if [ "$cr" = auto ]; then wizard_kharej_auto "$name"; return; fi
  # F19 shaped carriers: refuse early what the engine would refuse at startup (Linux/root for the raw tier, 3.3.0 both
  # ends), and say out loud that these are wattun-internal shapes rather than the real protocols.
  is_shaped_list "$cr" && { shaped_supported_here "$cr" || return 1; shaped_warn "$cr"; }
  case "$cr" in ws|wss|grpc|h2|h2c) path=$(rand_path); [ -n "$NI_PATH" ] && path=$NI_PATH ;; esac
  if carrier_write_listen "$cr" && [ -n "$NI_LISTEN" ]; then
    if listen_blocked "$(rproto "$cr")" "$NI_LISTEN"; then
      err "Port $NI_LISTEN is already used by $(listen_conflict_desc "$(rproto "$cr")" "$NI_LISTEN")."; return 1
    fi
    listen=$NI_LISTEN
  fi
  sni=$NI_SNI; mbps=$NI_MBPS
  if [ -n "${NI_CDN:-}" ]; then
    v_domain_opt "$NI_CDN" || return 1
    cdn_mode=1
    [ -n "$sni" ] || sni=$NI_CDN
  fi
  if [ "$cr" = udp ] && { [ "$NI_UDPDNS" = 1 ] || { [ "$NONINTERACTIVE" != 1 ] && [ -z "$NI_LISTEN" ]; }; }; then # DNS-shaped udp (3.0.0)
    ask=1
    if [ "$NI_UDPDNS" != 1 ]; then
      echo
      hint "Some routes cut UDP flows but pass DNS-looking UDP on port 53. Needs wattun 3.0.0+ on both ends."
      confirm "Use DNS-shaped UDP on port 53? (only if plain udp does not work on your route)" n || ask=0
    fi
    if [ "$ask" = 1 ]; then
      [ "$(bin_ver_ok 3.0.0)" = 1 ] || { err "DNS-shaped udp needs wattun 3.0.0 or newer on this server (run: $SELF update)."; return 1; }
      udpdns=1; listen=53
      lisip=$(out_ip 8.8.8.8) # port 53 is often held by the local resolver on 127.0.0.53 only, so bind this server's own address
    fi
  fi
  advdef=n; [ -n "$NI_LISTEN$NI_PATH$NI_SNI$NI_MBPS" ] && advdef=y # a flag for an advanced setting opens that block (defaults = the flags)

  # allowed ports: all unless --ports is given (the port editor stays in the tunnel menu)
  MAPS=(); PE_ROLE=Kharej; PE_TUNNEL=$name; PE_ALLOW=(); PE_OWNED=(); PE_MSG=''
  allow=''
  if [ -n "$NI_PORTS" ]; then ni_kharej_ports || return 1; allow=$(maps_allow_str); fi

  # address Iran connects to
  if [ -n "$NI_ADDR" ]; then addr=$NI_ADDR
  elif [ -n "${NI_CDN:-}" ]; then addr=$NI_CDN
  else spin_start "Detecting public IP"; addr=$(public_ip); spin_stop; fi
  if [ -z "$NI_ADDR" ] && [ -z "${NI_CDN:-}" ] && [ -n "$addr" ] && ip_is_private "$addr"; then
    warn "$addr is a private address; the entry server cannot reach it."
    confirm "Use $addr anyway?" n || addr=''
  elif [ -z "$addr" ]; then
    warn "Could not detect public IP."
    [ "$NONINTERACTIVE" = 1 ] && hint "Give it with --addr HOST"
  fi
  if [ -z "$addr" ]; then
    ask_ok "Public IP or domain" "" v_host || return 1; addr=$REPLY_V
  else
    ok "Public address  $addr"
  fi
  case "$cr" in
    wss|grpc|h2|ws|h2c) # behind a CDN, Iran dials the domain and Kharej must listen on a Cloudflare-proxyable port
      if [ "$NONINTERACTIVE" != 1 ] && [ -z "${NI_CDN:-}" ]; then
        ask_ok "CDN domain (Enter to keep $addr)" "$addr" v_host || return 1; addr=$REPLY_V
      fi ;;
  esac
  if is_cdn_carrier "$cr"; then
    split_hp "$addr"
    if ! ipv4_ok "$HP_HOST" && ! ipv6_ok "$HP_HOST"; then cdn_mode=1; fi
  fi
  if carrier_write_listen "$cr" && [ -z "$listen" ]; then
    listen=$(default_listen "$cr" "$cdn_mode") || { err "Could not find a free open port on this server."; return 1; }
    if [ "$cdn_mode" = 1 ] && [ "${CF_ORIGIN_FALLBACK:-0}" = 1 ]; then
      warn "Non-443/80 Cloudflare ports busy; using :$listen (add a Cloudflare Origin Rule)."
    fi
  fi

  # advanced
  echo
  hint "Defaults: $name · $addr${listen:+:$listen}${path:+ $path} · unlimited · FEC off"
  if confirm "Edit advanced settings?" "$advdef"; then
    ask_ok "Tunnel name" "$name" v_name && name=$REPLY_V || return 1
    ask_ok "Public IP or domain" "$addr" v_host || return 1; addr=$REPLY_V
    if [ "$cr" = icmp ]; then
      ask_ok "ICMP type (echo, timestamp)" echo v_icmp || return 1; itype=$REPLY_V
      echo; reverse_hint icmp
      if confirm "Reverse direction (the exit server pings the entry server)?" n; then
        ask_ok "Entry server IPv4 address" "" v_ipv4 || return 1; iranip=$REPLY_V; rev=1
      fi
    else
      if carrier_write_listen "$cr"; then
        while :; do
          ask_ok "Listen port" "$listen" v_port || return 1
          if listen_blocked "$(rproto "$cr")" "$REPLY_V"; then err "Port $REPLY_V is already used by $(listen_conflict_desc "$(rproto "$cr")" "$REPLY_V")."; else listen=$((10#$REPLY_V)); break; fi
          t=$((${t:-0}+1)); [ "$t" -ge 3 ] && { err "Too many tries, going back."; return 1; }
        done
      fi
      # reverse is for icmp/udp/pool carriers; the F19 shapes (and hand-made bonds) do not take it
      if is_rpool "$cr" && [[ "$cr" != *+* ]]; then
        echo; reverse_hint "$cr"
        if confirm "Reverse direction (the exit server dials the entry server:$listen)?" n; then
          ask_ok "Entry IP address" "" v_ip || return 1; iranip=${REPLY_V#[}; iranip=${iranip%]}; rev=1
        fi
      fi
    fi
    case "$cr" in ws|wss|grpc|h2|h2c) ask_ok "URL path" "$path" v_path || return 1; path=$REPLY_V ;; esac
    case "$cr" in wss|tls|grpc|h2) ask "SNI (empty = none)" "$sni"; sni=$REPLY_V ;; esac
    ask_ok "Speed limit MB/s (empty = none)" "$mbps" v_mbps || return 1; mbps=$REPLY_V
    ask_fec off || return 1; fec=$REPLY_V; fecb=$REPLY_FEC_BAND
  fi
  valid_name "$name" || { err "The name '$name' is not available."; return 1; }
  split_hp "$addr"; addr=$HP_HOST
  case "$cr" in wss|grpc|h2|tls) [ -z "$sni" ] && ! ipv4_ok "$addr" && ! ipv6_ok "$addr" && sni=$addr ;; esac

  # summary
  echo
  summary_line "Name" "$name (Exit server)"
  summary_line "Carrier" "$cr${itype:+ ($itype)}${listen:+ :$listen}${path:+ $path}${udpdns:+ (DNS-shaped)}"
  summary_line "Address" "$addr"
  if [ "$rev" = 1 ]; then
    if [ "$cr" = icmp ]; then summary_line "Direction" "reverse → $iranip"
    else summary_line "Direction" "reverse → $(join_hp "$iranip" "$listen")"; fi
  fi
  summary_line "Allow ports" "${allow:-any}"
  [ -n "$mbps" ] && summary_line "Speed limit" "$mbps MB/s"
  [ "$fec" = auto ] && summary_line "FEC" "auto"
  echo
  confirm "Create tunnel '$name'?" y || { warn "Cancelled."; return 1; }
  echo

  key=$(new_key); m=$(free_metrics_port)
  peer=$(join_hp "$addr" "$listen")
  # Owner directive (2026-11-22): zero extra manual steps. The first mint embeds the
  # token-bootstrap pairing (field 10, pair=full unless an expert row preset a tier) and the
  # server config carries latch-port — no ask for either; the engine derives the pairing from
  # the token, a stored .pairing overrides it, `pairing: false` disables. FIELD 10 IS
  # `pair=<tier>` verbatim (wat.ParsePairingTokenField is L5-strict: a bare tier word is a
  # lookalike and silently arms NOTHING — found live on the first real pair, 2026-11-23).
  T_PAIR=${T_PAIR:-pair=$SCEPTER_DEFAULT_TIER}
  latch=$(pick_latch_port "$listen" "$m")
  write_server() {
    local old; old=$(umask); umask 077
    printf '%s\n' "$key" >"$CONF/$name.key" || return 1
    {
      echo "# WatTunnel - the exit server (server). Created by wattun-manager."
      echo "mode: server"
      echo "key-file: $CONF/$name.key"
      echo "carrier: $cr"
      [ -n "$listen" ] && { [ "$rev" != 1 ] || [ "$cr" = udp ]; } && echo "listen: \"$(join_hp "$lisip" "$listen")\"" # reverse udp binds it as the source port
      [ "$udpdns" = 1 ] && echo "udp-dns: true"
      [ -n "$path" ] && echo "path: $path"
      [ -n "$itype" ] && [ "$itype" != echo ] && echo "icmp-type: $itype"
      [ -n "$latch" ] && [ "$rev" != 1 ] && echo "latch-port: $latch" # the scepter latch listener (3.5.0); picked collision-free
      if [ "$rev" = 1 ]; then
        echo "reverse: true"
        if is_rpool "$cr"; then
          echo "peer: $(join_hp "$iranip" "$listen")"
          [ -n "$sni" ] && { echo "sni: $sni"; echo "host: $sni"; }
          echo "pool-rotate: 30m"
        else echo "peer: $iranip"; fi
      fi
      [ -n "$mbps" ] && echo "max-mbps: $mbps"
      [ "$fec" = auto ] && echo "fec: auto"
      [ -n "$m" ] && echo "metrics: 127.0.0.1:$m" # F25: free_metrics_port found no port; write no invalid line
      maps_yaml_block
    } >"$CONF/$name.yml"
    make_token "$cr" "$peer" "$key" "${path:-${udpdns:+dns}}" "$sni" "$itype" "$allow" "$rev" "" "$T_PAIR" >"$CONF/$name.token"
    umask "$old"
  }
  mkdir -p "$CONF"; chmod 700 "$CONF"
  step "Writing key, config and token" write_server || return 1
  start_unit "$name" || return 1
  [ -n "$listen" ] && [ "$rev" != 1 ] && fw_open "$listen/$(rproto "$cr")"
  if [ "$rev" = 1 ] && is_rpool "$cr"; then hint "Cloud firewall: allow outbound to $iranip:$listen/$(rproto "$cr")."
  elif [ "$rev" = 1 ] || [ "$cr" = icmp ]; then hint "Cloud firewall: allow ICMP."; fi
  kreply_wanted "$name" && kreply_offer # normal ICMP: the kernel here would echo every request from Iran (3.0.0)

  echo
  celebrate "Exit tunnel '$name' ready"
  echo
  printf '  %s%s%s\n\n' "$BOLD$YEL" "$(cat "$CONF/$name.token")" "$RST"
  token_qr "$(cat "$CONF/$name.token")"
  step_diagram 2
  echo
  say "  Next on the entry server: run ${CYN}${SELF}${RST} → $(key_label n) → paste token"
  hint "Token contains secret key — share privately ($SELF token $name)"
  hint "Pairing rides this token (field 10, $T_PAIR): the entry server's wizard picks it up, no watp1: line needed."
  [ "$NONINTERACTIVE" = 1 ] && printf 'TUNNEL=%s\nTOKEN=%s\n' "$name" "$(cat "$CONF/$name.token")"
  if [ "$fecb" = 1 ] && [ "$NONINTERACTIVE" != 1 ]; then
    echo; adv_menu "$name"
  fi
  return 0
}

ni_kharej_ports() { # --ports "18999,2000,53/udp" -> MAPS (Kharej side: the service ports Iran may reach)
  local msg
  pe_bulk "$NI_PORTS"
  msg=$PE_MSG; PE_MSG=''
  [ -n "$msg" ] && printf '%b' "$msg" | sed 's/^/  /'
  if [[ "$msg" == *✘* ]]; then err "--ports '$NI_PORTS' was rejected (see above)"; return 1; fi
  return 0
}

# ======================================================================================
#  Anti-Censorship Presets, Selection Helpers, and Numbered Pickers
# ======================================================================================
# Anti-censor runs on the side that DIALS the carrier: Iran normally, Kharej when the pool tunnel is reverse (2.10.12).
ac_dialer() { # name
  [ "$(uname -s)" = Linux ] || return 1
  if is_pool_list "$(cfg "$1" carrier)" && is_reverse "$1"; then [ "$(role "$1")" = Kharej ]; else [ "$(role "$1")" = Iran ]; fi
}

preset_canonical() {
  local p="${1,,}"
  case "$p" in
    cloudflare|cf|cloudflare-tested|tested|worked) echo cloudflare ;;
    rst-fast|fast) echo rst-fast ;;
    mci|mci-whitelist|hamrah|hamrah-aval) echo mci ;;
    irancell|mokhaberat|tci|irancell-whitelist) echo irancell ;;
    blackout|emergency|strict) echo blackout ;;
    conservative|low-churn|mild) echo conservative ;;
    "iran whitelist - mci") echo mci ;;
    "iran whitelist - irancell/mokhaberat"|"iran whitelist - irancell"|"iran whitelist - mokhaberat") echo irancell ;;
    "emergency blackout mode") echo blackout ;;
    "conservative / low-churn"|"conservative/low-churn") echo conservative ;;
    off|clear|none) echo off ;;
    *) echo "$1" ;;
  esac
}

is_builtin_preset() {
  case "$(preset_canonical "$1")" in
    cloudflare|rst-fast|mci|irancell|blackout|conservative) return 0 ;;
  esac
  return 1
}

show_builtin_preset() {
  local p; p=$(preset_canonical "$1")
  case "$p" in
    cloudflare)
      cat <<'EOF'
# WatTunnel built-in preset: Cloudflare (field-tested 2.10.12)
# Fake hello naming www.cloudflare.com plus a bad-checksum RST that clears the filter's flow state, no churn:
# the combination that carried a wss tunnel through a Cloudflare edge when the real SNI was filtered
FAKESNI=www.cloudflare.com
FAKEMODE=rst
FAKETTL=
POOLROT=
POOLBYTES=
ECH=
GOVERNOR=
EOF
      ;;
    rst-fast)
      cat <<'EOF'
# WatTunnel built-in preset: rst-fast (3.0.0)
# The fastest direct setup measured on a cut-after-first-bytes route (field 2.11.0): bad-checksum RST, 4 sessions
# of 4 connections, 30 min pool rotation. On a reverse tunnel the sessions part is skipped (not supported there).
FAKESNI=www.cloudflare.com
FAKEMODE=rst
FAKETTL=
POOLROT=30m
POOLBYTES=
ECH=
GOVERNOR=
SESSIONS=4
CONNS=4
EOF
      ;;
    mci)
      cat <<'EOF'
# WatTunnel built-in preset: Iran Whitelist - MCI
# Optimized for Hamrah Aval (MCI) whitelist restrictions; rst since 3.0.0 (seqsum failed on a cut-after-first-bytes route)
FAKESNI=mci.ir
FAKEMODE=rst
FAKETTL=
POOLROT=30m
POOLBYTES=500MB
ECH=ladder
GOVERNOR=true
EOF
      ;;
    irancell)
      cat <<'EOF'
# WatTunnel built-in preset: Iran Whitelist - Irancell/Mokhaberat
# Optimized for MTN Irancell and TCI allowlist bypass. seq only helps an SNI-allowlist filter; on a route that cuts
# every flow after the first bytes use rst-fast or mci (rst) instead
FAKESNI=irancell.ir
FAKEMODE=seq
FAKETTL=
POOLROT=20m
POOLBYTES=300MB
ECH=ladder
GOVERNOR=true
EOF
      ;;
    blackout)
      cat <<'EOF'
# WatTunnel built-in preset: Emergency Blackout Mode
# Aggressive anti-censorship settings for strict national intranet / blackout regimes; rst since 3.0.0
FAKESNI=mci.ir
FAKEMODE=rst
FAKETTL=
POOLROT=90s
POOLBYTES=100MB
ECH=ladder
GOVERNOR=true
EOF
      ;;
    conservative)
      cat <<'EOF'
# WatTunnel built-in preset: Conservative / Low-Churn
# Low reconnect churn for stable connections under mild DPI filtering (SNI-allowlist filters; seq does not survive a
# cut-after-first-bytes route)
FAKESNI=mci.ir
FAKEMODE=seq
FAKETTL=
POOLROT=4h
POOLBYTES=4GB
ECH=auto
GOVERNOR=true
EOF
      ;;
  esac
}

detect_preset() {
  local n=$1 fs fm rot rbytes cr
  cr=$(cfg "$n" carrier)
  if [ "$cr" = icmp ]; then
    if [ "$(cfg "$n" governor)" = true ]; then
      echo "${GRN}Governor Active (ICMP Pacer)${RST}"
    else
      echo "${GRY}none / disabled${RST}"
    fi
    return
  fi
  fs=$(cfg "$n" fake-sni)
  fm=$(cfg "$n" fake-mode); [ -z "$fm" ] && [ -n "$fs" ] && fm=seq
  rot=$(cfg "$n" pool-rotate)
  rbytes=$(cfg "$n" pool-rotate-bytes)
  if [ -z "$fs" ] && [ -z "$rot" ] && [ "$(cfg "$n" governor)" != true ]; then
    echo "${GRY}none / disabled${RST}"; return
  fi
  if [ "$fs" = "www.cloudflare.com" ] && [ "$fm" = "rst" ] && [ -z "$rot" ]; then
    echo "${GRN}Cloudflare (field-tested)${RST}"; return
  fi
  if [ "$fs" = "www.cloudflare.com" ] && [ "$fm" = "rst" ] && [ "$rot" = "30m" ]; then
    echo "${GRN}rst-fast${RST}"; return
  fi
  if [ "$fs" = "mci.ir" ] && [ "$fm" = "rst" ] && [ "$rot" = "30m" ]; then
    echo "${GRN}Iran Whitelist - MCI${RST}"; return
  fi
  if [ "$fs" = "irancell.ir" ] && [ "$fm" = "seq" ] && [ "$rot" = "20m" ]; then
    echo "${GRN}Iran Whitelist - Irancell/Mokhaberat${RST}"; return
  fi
  if [ "$fs" = "mci.ir" ] && [ "$fm" = "rst" ] && [ "$rot" = "90s" ]; then
    echo "${RED}Emergency Blackout Mode${RST}"; return
  fi
  if [ "$fs" = "mci.ir" ] && [ "$fm" = "seq" ] && [ "$rot" = "4h" ]; then
    echo "${BLU}Conservative / Low-Churn${RST}"; return
  fi
  echo "${CYN}Custom${RST}"
}

pick_preset() { # [default] -> REPLY_V
  local def=${1:-mci}
  if [ "$NONINTERACTIVE" = 1 ]; then
    REPLY_V=${NI_PRESET:-$def}
    return 0
  fi
  say "  Preset              ${GRY}sni · mode · rotate${RST}"
  say "  $(key_label 1) Cloudflare      ${GRY}www.cloudflare.com · rst · off, passed a CDN whitelist${RST}"
  say "  $(key_label 2) MCI whitelist   ${GRY}mci.ir · rst · 30m / 500MB, ECH ladder${RST}"
  say "  $(key_label 3) Irancell        ${GRY}irancell.ir · seq · 20m / 300MB, SNI-allowlist only${RST}"
  say "  $(key_label 4) Blackout        ${GRY}mci.ir · rst · 90s / 100MB, ECH ladder${RST}"
  say "  $(key_label 5) Low churn       ${GRY}mci.ir · seq · 4h / 4GB, ECH auto, SNI-allowlist only${RST}"
  say "  $(key_label 6) Off             ${GRY}plain tunnel, full speed${RST}"
  say "  $(key_label 7) Fast            ${GRY}www.cloudflare.com · rst · 30m, 4 × 4 conns${RST}"
  echo
  printf '  %s?%s %s[1 = Cloudflare]%s ' "$CYN" "$RST" "$GRY" "$RST"
  key_read
  case "$KEY" in
    1) REPLY_V="cloudflare" ;;
    2) REPLY_V="mci" ;;
    3) REPLY_V="irancell" ;;
    4) REPLY_V="blackout" ;;
    5) REPLY_V="conservative" ;;
    6) REPLY_V="off" ;;
    7) REPLY_V="rst-fast" ;;
    enter) REPLY_V="$def" ;;
    esc|q) echo; return 1 ;;
    *) REPLY_V="$def" ;;
  esac
  echo "$REPLY_V"
  return 0
}

pick_sni_preset() { # [default] -> REPLY_V
  local def=${1:-mci.ir}
  if [ "$NONINTERACTIVE" = 1 ]; then
    REPLY_V=${NI_FAKESNI:-$def}
    return 0
  fi
  say "  Fake SNI ${GRY}(a domain the filter lets through)${RST}"
  say "  $(key_label 0) off"
  say "  $(key_label 1) mci.ir            ${GRY}MCI${RST}"
  say "  $(key_label 2) shop.mci.ir       ${GRY}MCI shop${RST}"
  say "  $(key_label 3) irancell.ir       ${GRY}Irancell${RST}"
  say "  $(key_label 4) my.irancell.ir    ${GRY}MyIrancell${RST}"
  say "  $(key_label 5) tci.ir            ${GRY}TCI${RST}"
  say "  $(key_label 6) rightel.ir        ${GRY}RighTel${RST}"
  say "  $(key_label 7) divar.ir          ${GRY}Divar${RST}"
  say "  $(key_label 8) digikala.com      ${GRY}Digikala${RST}"
  say "  $(key_label 9) bale.ai           ${GRY}Bale${RST}"
  say "  $(key_label s) srbiau.ac.ir      ${GRY}university portal${RST}"
  say "  $(key_label c) other domain"
  echo
  printf '  %s?%s %s[1 = mci.ir]%s ' "$CYN" "$RST" "$GRY" "$RST"
  key_read
  case "$KEY" in
    0) REPLY_V="off" ;;
    1) REPLY_V="mci.ir" ;;
    2) REPLY_V="shop.mci.ir" ;;
    3) REPLY_V="irancell.ir" ;;
    4) REPLY_V="my.irancell.ir" ;;
    5) REPLY_V="tci.ir" ;;
    6) REPLY_V="rightel.ir" ;;
    7) REPLY_V="divar.ir" ;;
    8) REPLY_V="digikala.com" ;;
    9) REPLY_V="bale.ai" ;;
    s|S) REPLY_V="srbiau.ac.ir" ;;
    c|C) echo; ask_ok "Allowlisted SNI domain" "$def" v_sni_name || return 1 ;;
    enter) REPLY_V="$def" ;;
    esc|q) echo; return 1 ;;
    *) REPLY_V="$def" ;;
  esac
  echo "$REPLY_V"
  return 0
}

pick_fake_mode() { # [default] -> REPLY_V ; the list comes from AC_ALLMODES (H6)
  local def=${1:-rst} i=0 m
  local -a modes
  if [ "$NONINTERACTIVE" = 1 ]; then
    REPLY_V=${NI_FAKEMODE:-$def}
    v_fake_mode "$REPLY_V" || return 1
    return 0
  fi
  read -ra modes <<<"$AC_ALLMODES"
  say "  Desync mode"
  for m in "${modes[@]}"; do
    i=$((i+1)); [ "$i" -le 9 ] || continue
    say "  $(key_label "$i") $m  ${GRY}$(fake_mode_desc "$m")${RST}"
  done
  say "  $(key_label c) other  ${GRY}(type a mode; all: $AC_ALLMODES)${RST}"
  echo
  printf '  %s?%s %s[Enter = %s]%s ' "$CYN" "$RST" "$GRY" "$def" "$RST"
  key_read
  case "$KEY" in
    [1-9]) if [ "$KEY" -le "${#modes[@]}" ]; then REPLY_V=${modes[$((KEY-1))]}; else REPLY_V=$def; fi ;;
    c|C) echo; ask_ok "Desync mode ($AC_ALLMODES)" "$def" v_fake_mode || return 1 ;;
    enter) REPLY_V="$def" ;;
    esc|q) echo; return 1 ;;
    *) REPLY_V="$def" ;;
  esac
  v_fake_mode "$REPLY_V" || return 1
  echo "$REPLY_V"
  return 0
}

pick_pool_rotate() { # [default] -> REPLY_V
  local def=${1:-30m}
  if [ "$NONINTERACTIVE" = 1 ]; then
    REPLY_V=${NI_POOLROT:-$def}
    return 0
  fi
  say "  Rotate connections every"
  say "  $(key_label 1) off"
  say "  $(key_label 2) 30m   ${GRY}recommended${RST}"
  say "  $(key_label 3) 90s   ${GRY}blackout${RST}"
  say "  $(key_label 4) 10m"
  say "  $(key_label 5) 2h"
  say "  $(key_label 6) 4h"
  say "  $(key_label c) other ${GRY}(15m, 1h ...)${RST}"
  echo
  printf '  %s?%s %s[Enter = %s]%s ' "$CYN" "$RST" "$GRY" "$def" "$RST"
  key_read
  case "$KEY" in
    1) REPLY_V="off" ;;
    2) REPLY_V="30m" ;;
    3) REPLY_V="90s" ;;
    4) REPLY_V="10m" ;;
    5) REPLY_V="2h" ;;
    6) REPLY_V="4h" ;;
    enter) REPLY_V="$def" ;;
    c|C) echo; ask_ok "Pool rotation lifetime" "$def" v_pool_rotate || return 1 ;;
    esc|q) echo; return 1 ;;
    *) REPLY_V="$def" ;;
  esac
  echo "$REPLY_V"
  return 0
}

pick_pool_rotate_bytes() { # [default] -> REPLY_V
  local def=${1:-500MB}
  if [ "$NONINTERACTIVE" = 1 ]; then
    REPLY_V=${NI_POOLBYTES:-$def}
    return 0
  fi
  say "  Rotate connections after"
  say "  $(key_label 1) off"
  say "  $(key_label 2) 500MB  ${GRY}recommended${RST}"
  say "  $(key_label 3) 100MB  ${GRY}blackout${RST}"
  say "  $(key_label 4) 1GB"
  say "  $(key_label 5) 4GB"
  say "  $(key_label c) other ${GRY}(250MB, 2GB ...)${RST}"
  echo
  printf '  %s?%s %s[Enter = %s]%s ' "$CYN" "$RST" "$GRY" "$def" "$RST"
  key_read
  case "$KEY" in
    1) REPLY_V="off" ;;
    2) REPLY_V="500MB" ;;
    3) REPLY_V="100MB" ;;
    4) REPLY_V="1GB" ;;
    5) REPLY_V="4GB" ;;
    enter) REPLY_V="$def" ;;
    c|C) echo; ask_ok "Pool rotation byte budget" "$def" v_pool_bytes || return 1 ;;
    esc|q) echo; return 1 ;;
    *) REPLY_V="$def" ;;
  esac
  echo "$REPLY_V"
  return 0
}

pick_ech() { # [default] -> REPLY_V
  local def=${1:-ladder}
  if [ "$NONINTERACTIVE" = 1 ]; then
    REPLY_V=${NI_ECH:-$def}
    return 0
  fi
  say "  ECH"
  say "  $(key_label 1) ladder  ${GRY}looks up ECH through the exit server (2.9.0+)${RST}"
  say "  $(key_label 2) auto    ${GRY}looks up ECH directly (Cloudflare, Google, Quad9)${RST}"
  say "  $(key_label 3) off"
  say "  $(key_label c) other   ${GRY}a base64 ECHConfigList${RST}"
  echo
  printf '  %s?%s %s[1 = ladder]%s ' "$CYN" "$RST" "$GRY" "$RST"
  key_read
  case "$KEY" in
    1) REPLY_V="ladder" ;;
    2) REPLY_V="auto" ;;
    3) REPLY_V="off" ;;
    enter) REPLY_V="$def" ;;
    c|C) echo; ask_ok "ECH config (ladder, auto, off, or base64)" "$def" v_ech || return 1 ;;
    esc|q) echo; return 1 ;;
    *) REPLY_V="$def" ;;
  esac
  echo "$REPLY_V"
  return 0
}

pick_dns_listen() { # [default] -> REPLY_V
  local def=${1:-off}
  if [ "$NONINTERACTIVE" = 1 ]; then
    REPLY_V=${NI_DNSLISTEN:-$def}
    return 0
  fi
  say "  DNS forwarder ${GRY}(answers DNS through the tunnel)${RST}"
  say "  $(key_label 1) off"
  say "  $(key_label 2) 127.0.0.1:53   ${GRY}this server${RST}"
  say "  $(key_label 3) 127.0.0.1:5353 ${GRY}this server, other port${RST}"
  say "  $(key_label 4) 0.0.0.0:53     ${GRY}every device on the LAN${RST}"
  say "  $(key_label c) other address:port"
  echo
  printf '  %s?%s %s[1 = off]%s ' "$CYN" "$RST" "$GRY" "$RST"
  key_read
  case "$KEY" in
    1) REPLY_V="off" ;;
    2) REPLY_V="127.0.0.1:53" ;;
    3) REPLY_V="127.0.0.1:5353" ;;
    4) REPLY_V="0.0.0.0:53" ;;
    c|C) echo; ask_ok "Custom DNS listen address:port" "127.0.0.1:53" v_dns_listen || return 1 ;;
    enter) REPLY_V="$def" ;;
    esc|q) echo; return 1 ;;
    *) REPLY_V="$def" ;;
  esac
  echo "$REPLY_V"
  return 0
}

pick_src_ip() { # [default] -> REPLY_V
  local def=${1:-off}
  if [ "$NONINTERACTIVE" = 1 ]; then
    REPLY_V=${NI_SRCIP:-$def}
    return 0
  fi
  say "  Source IP ${GRY}(which local address the tunnel leaves from)${RST}"
  say "  $(key_label 0) off  ${GRY}the route picks${RST}"
  local ips=() idx=1
  if command -v ip >/dev/null 2>&1; then
    while read -r _ ifn _ ifa _; do
      local clean_ip="${ifa%%/*}"
      [ "$clean_ip" = "127.0.0.1" ] && continue
      ips+=("$clean_ip ($ifn)")
      printf '  %s %s\n' "$(key_label "$idx")" "$clean_ip ($ifn)"
      idx=$((idx+1))
    done < <(ip -4 -o addr show scope global 2>/dev/null)
  fi
  printf '  %s other address\n' "$(key_label c)"
  echo
  printf '  %s?%s %s[0 = off]%s ' "$CYN" "$RST" "$GRY" "$RST"
  key_read
  case "$KEY" in
    0) REPLY_V="off" ;;
    c|C) echo; ask_ok "Custom IPv4 address" "" v_src_ip || return 1 ;;
    enter) REPLY_V="$def" ;;
    esc|q) echo; return 1 ;;
    *)
      if [[ "$KEY" =~ ^[1-9]$ ]] && [ "$KEY" -le "${#ips[@]}" ]; then
        local sel="${ips[$((KEY-1))]}"
        REPLY_V="${sel%% *}"
      else
        REPLY_V="$def"
      fi
      ;;
  esac
  echo "$REPLY_V"
  return 0
}

apply_preset() { # tunnel preset
  local tun=$1 raw_preset=$2 pr changed=0
  pr=$(preset_canonical "$raw_preset")
  local cr; cr=$(cfg "$tun" carrier)
  local r; r=$(role "$tun")
  if is_pool_list "$cr" && is_reverse "$tun"; then
    [ "$r" = Kharej ] || { err "'$tun' is a reverse entry tunnel (the listener). Anti-censorship desync runs on the dialer (the exit server)."; return 1; }
  else
    [ "$r" = Iran ] || { err "'$tun' is not an entry tunnel (anti-censorship presets run on the dialer)."; return 1; }
  fi
  [ "$(bin_ver_ok 2.7.0)" = 1 ] || { err "Anti-censorship features need wattun 2.7.0 or newer (run: $SELF update)."; return 1; }
  if [ "$cr" != icmp ] && ! is_pool_list "$cr"; then
    err "Carrier '$cr' does not support anti-censorship features (only pool carriers and icmp are supported)."; return 1
  fi

  local fs='' fm='' ft='' rot='' rbytes='' ech='' gov='' sess='' conns=''
  case "$pr" in
    cloudflare)
      fs="www.cloudflare.com"; fm="rst"; ft=""; rot=""; rbytes=""; ech=""; gov="" ;;
    rst-fast)
      fs="www.cloudflare.com"; fm="rst"; ft=""; rot="30m"; rbytes=""; ech=""; gov=""; sess=4; conns=4 ;;
    mci)
      fs="mci.ir"; fm="rst"; ft=""; rot="30m"; rbytes="500MB"; ech="ladder"; gov="true" ;;
    irancell)
      fs="irancell.ir"; fm="seq"; ft=""; rot="20m"; rbytes="300MB"; ech="ladder"; gov="true" ;;
    blackout)
      fs="mci.ir"; fm="rst"; ft=""; rot="90s"; rbytes="100MB"; ech="ladder"; gov="true" ;;
    conservative)
      fs="mci.ir"; fm="seq"; ft=""; rot="4h"; rbytes="4GB"; ech="auto"; gov="true" ;;
    off|clear|none)
      fs=""; fm=""; ft=""; rot=""; rbytes=""; ech=""; gov="" ;;
    *) err "Unknown preset '$raw_preset'. Available: cloudflare, rst-fast, mci, irancell, blackout, conservative"; return 1 ;;
  esac

  if [ "$cr" = icmp ]; then
    if [ "$gov" = true ]; then
      set_value "$tun" governor true; changed=1
    elif [ "$pr" = off ]; then
      unset_value "$tun" governor; changed=1
    fi
  fi

  if is_pool_list "$cr"; then
    if [ -n "$fs" ]; then
      set_value "$tun" fake-sni "$fs"; changed=1
      set_value "$tun" fake-mode "$fm"; changed=1
      if [ -n "$ft" ]; then set_value "$tun" fake-ttl "$ft"; else unset_value "$tun" fake-ttl; fi
    elif [ -n "$(cfg "$tun" fake-sni)" ]; then
      unset_value "$tun" fake-sni; unset_value "$tun" fake-mode; unset_value "$tun" fake-ttl; changed=1
    fi

    if [ -n "$rot" ]; then set_value "$tun" pool-rotate "$rot"; changed=1
    elif [ -n "$(cfg "$tun" pool-rotate)" ]; then unset_value "$tun" pool-rotate; changed=1; fi

    if [ -n "$rbytes" ]; then set_value "$tun" pool-rotate-bytes "$rbytes"; changed=1
    elif [ -n "$(cfg "$tun" pool-rotate-bytes)" ]; then unset_value "$tun" pool-rotate-bytes; changed=1; fi

    if [ -n "$conns" ]; then set_value "$tun" conns "$conns"; changed=1; fi
    # sessions > 1 is refused with -reverse (the server dials one pool), so rst-fast skips it there
    if [ -n "$sess" ] && ! is_reverse "$tun"; then set_value "$tun" sessions "$sess"; changed=1; fi

    if has_ech_list "$cr"; then
      if [ -n "$ech" ]; then set_value "$tun" ech "$ech"; changed=1
      elif [ -n "$(cfg "$tun" ech)" ]; then unset_value "$tun" ech; changed=1; fi
    fi
  fi

  [ "$changed" = 1 ] || { hint "Preset '$pr' already matches current settings."; return 0; }
  ok "Applied anti-censorship preset '$pr' to $tun."
  local udl; udl=$(undisguised_legs "$cr")
  [ -n "$udl" ] && is_pool_list "$cr" && hint "The '$udl' leg(s) of this bond stay undisguised."
  if step "Restarting ${WAT_PREFIX}@$tun" systemctl restart "${WAT_PREFIX}@$tun"; then ok "Restart applied."
  else err "Restart failed: run  systemctl restart ${WAT_PREFIX}@$tun"; return 1; fi
  return 0
}

wizard_iran() {
  local name tok have manual=0 bind='' mbps='' fec='' fecb='' itype='' sni='' path='' m i allow_note it new_pub=() t=0 rport='' advdef=n linkok=1 askres
  local T_FAKESNI='' T_FAKEMODE='' T_FAKETTL='' T_POOLROT='' T_POOLBYTES='' T_ECH='' T_GOVERNOR='' T_DNSLISTEN='' T_SRCIP=''
  page "New tunnel" "Entry server"
  [ "$NONINTERACTIVE" = 1 ] || conf_set side iran
  name=$(suggest_name iran); [ -n "$NI_NAME" ] && name=$NI_NAME
  mbps=$NI_MBPS; [ -n "$mbps" ] && advdef=y
  T_CARRIER=''; T_PEER=''; T_KEY=''; T_PATH=''; T_SNI=''; T_ICMP=''; T_PORTS=''; T_REV=''; T_AUTO=''; T_PAIR=''
  T_LEG_C=(); T_LEG_P=()
  AUTO_TOKEN=''; AT_EXTRA=''; CT_DESC=''
  echo
  ask_ok "Token from the exit server (wat1:...)" "$NI_TOKEN" v_token || return 1
  tok=$REPLY_V; read_token "$tok"
  # Owner directive (2026-11-22): pasting the token is the only step. A field-10
  # pair rides it — the engine derives the pairing from the token, so this wizard
  # never asks for a watp1: line and writes no pairing: key (the Go cockpit keeps
  # the attach screen for explicit/rotate flows).
  [ -n "$T_PAIR" ] && hint "Pairing rides this token (field 10): nothing else to paste or set."
  if [ "$T_CARRIER" = auto ]; then
    ok "auto token · ${T_PEER%%[:,]*} · ${T_PORTS:-any port}"
    auto_iran_front "$tok" || return 1
  else
    v_carrier_list "$T_CARRIER" || return 1 # D7: also refuses a hand-made token that puts shaped carriers in a bond
    token_bond_legs || return 1 # M1: split a bond token's per-leg endpoints; T_PEER becomes the first leg's entry
    if is_shaped_list "$T_CARRIER"; then # F19: same engine requirements on this end, and normalize the peer form
      shaped_supported_here "$T_CARRIER" || return 1
      if is_shaped_carrier "$T_CARRIER"; then
        T_PEER=$(shaped_peer_for_client "$T_CARRIER" "$T_PEER")
        case "$T_PEER" in *:*) v_port "${T_PEER##*:}" || return 1 ;; esac
      fi
      shaped_warn "$T_CARRIER"
    fi
    ok "Token · $T_CARRIER${T_ICMP:+ ($T_ICMP)} · ${T_PEER%%,*} · allows ${T_PORTS:-any port}"
    if [ "$T_REV" = 1 ]; then
      if is_rpool "$T_CARRIER"; then hint "Reverse: the exit server dials the entry server :${T_PEER##*:}"
      else hint "Reverse: the exit server sends pings, the entry server replies"; fi
    fi
    cdn_wizard_tune # CDN carrier + domain: automatic edge / TLS tuning (wattun >= 2.2.0), silent otherwise
  fi
  rport=''
  local -a rports=()
  local lc lv lproto
  if [ "$T_REV" = 1 ] && [[ "$T_CARRIER" != *+* ]] && is_rpool "$T_CARRIER"; then
    rport=${T_PEER##*:}
    v_port "$rport" >/dev/null 2>&1 && [ "$rport" != "$T_PEER" ] || { err "The exit address has no valid carrier port, so reverse cannot be set up."; return 1; }
    rport=$((10#$rport))
    rports+=("$rport/$(rproto "$T_CARRIER")")
  elif [ "$T_REV" = 1 ] && [[ "$T_CARRIER" == *+* ]] && [ -n "${AT_EXTRA:-}" ]; then
    while IFS= read -r it; do
      case "$it" in listen-*:*)
        lc=${it%%:*}; lc=${lc#listen-}; lv=${it#*:}; lv=${lv//\"/}; lv=${lv//[[:space:]]/}
        split_hp "$lv"
        if [ -n "$HP_PORT" ] && v_port "$HP_PORT" >/dev/null 2>&1; then
          rports+=("$((10#$HP_PORT))/$(rproto "$lc")")
        fi ;;
      esac
    done <<<"$AT_EXTRA"
  fi

  # port mappings
  MAPS=(); PE_ROLE=Iran; PE_TUNNEL=$name; PE_OWNED=()
  allow_to_array "$T_PORTS"
  PE_MSG=''
  if [ "${#PE_ALLOW[@]}" -gt 0 ]; then
    local skipped=0
    PE_MSG="${GRN}✔${RST} Pre-filled from token (Enter keeps, e # edits)"$'\n'
    # same checks as a hand-typed row: busy port, another tunnel publishing it
    for it in "${PE_ALLOW[@]}"; do pe_try_add "$(spec_T "$it"):$(spec_T "$it")/$(spec_P "$it")" || skipped=$((skipped+1)); done
    [ "$skipped" -gt 0 ] && pe_msg "${YEL}!${RST} $skipped port(s) conflicted — map manually (e.g. 8443:443)"
  fi
  port_editor || { warn "Cancelled."; return 1; }
  if [ "${#rports[@]}" -gt 0 ]; then
    for it in "${rports[@]}"; do
      lv=${it%/*}; lproto=${it##*/}
      if listen_blocked "$lproto" "$lv"; then
        err "Port $lv/$lproto is already in use here by $(listen_conflict_desc "$lproto" "$lv"). Reverse needs it free: pick another carrier port on the exit server and make a new token."
        return 1
      fi
      for ((i=0; i<${#MAPS[@]}; i++)); do
        if [ "$(spec_L "${MAPS[$i]}")" = "$lv" ] && [ "$(spec_P "${MAPS[$i]}")" = "$lproto" ]; then
          err "Port $lv/$lproto is also a port you publish here. The carrier port must differ: pick another one on the exit server and make a new token."
          return 1
        fi
      done
    done
  fi

  # advanced
  echo
  [ "$NONINTERACTIVE" = 1 ] && hint "Defaults: name $name, all addresses, no speed limit, FEC off."
  if [ "$NONINTERACTIVE" = 1 ] && confirm "Change advanced settings?" "$advdef"; then
    ask_ok "Tunnel name" "$name" v_name && name=$REPLY_V || return 1
    ask_ok "Bind address for the public ports" 0.0.0.0 v_bind || return 1; bind=$REPLY_V
    ask_ok "Speed ceiling in MB/s (empty = no cap; icmp alone: 16)" "$mbps" v_mbps || return 1; mbps=$REPLY_V
    ask_fec off || return 1; fec=$REPLY_V; fecb=$REPLY_FEC_BAND
    if [ "$T_CARRIER" = icmp ]; then ask_ok "ICMP type (must match the exit server)" "${T_ICMP:-echo}" v_icmp || return 1; T_ICMP=$REPLY_V; fi
    case "$T_CARRIER" in wss|tls|grpc|h2) ask "Domain / SNI (empty = none)" "$T_SNI"; T_SNI=$REPLY_V ;; esac
    case "$T_CARRIER" in ws|wss|grpc|h2|h2c) ask_ok "URL path" "${T_PATH:-/wat}" v_path || return 1; T_PATH=$REPLY_V ;; esac
  fi
  # Which of this server's addresses the tunnel leaves from (3.0.0): the default is whatever the route picks, which on a
  # server with two addresses may be the one users connect to; a provider that restricts that address then sees the tunnel.
  if [ "$T_REV" != 1 ] && [ -z "$T_AUTO" ] && [ -z "$T_SRCIP" ] && [ "$NONINTERACTIVE" != 1 ] && [ "$(uname -s)" = Linux ]      && [ "$(local_ips | wc -l)" -gt 1 ]; then
    local oip; oip=$(out_ip "${T_PEER%%[:,]*}")
    echo
    hint "Outbound IP: ${oip:-auto} (change: tunnel page -> z -> 9)"
  fi
  # Resilience options (2.6.0-2.8.1): fake-sni (name, mode, ttl) and pool-rotate churn — the
  # blackout/whitelisting survival kit (docs/TECHNICAL.md). Strictly for censored routes, so NOT part
  # of the plain-tunnel flow: one explicit ask, then the same prompts as before. Unattended flags or a
  # saved profile prefill it and skip the ask — a preset IS the ask.
  # Anti-censorship & resilience options (2.6.0-2.9.0): presets, fake-sni, pool-rotate, ech, governor
  if [ "$T_REV" != 1 ] && [ -z "$T_AUTO" ] && [ "$(uname -s)" = Linux ]; then
    prof_pick_defaults
    # Unattended preset or flags (the SNI/ECH/pool knobs apply to every pool leg of a bond)
    if [ -n "$NI_PRESET" ] && ! is_pool_list "$T_CARRIER"; then
      err "Preset '$NI_PRESET' needs a tcp/tls/ws/wss/h2/h2c/grpc tunnel: '$T_CARRIER' has no SNI to disguise."
      return 1
    fi
    if [ -n "$NI_FAKESNI$NI_FAKEMODE$NI_FAKETTL$NI_POOLROT$NI_POOLBYTES$NI_ECH" ] && ! is_pool_list "$T_CARRIER"; then
      err "--fake-sni, --pool-rotate and --ech need a tcp/tls/ws/wss/h2/h2c/grpc tunnel (got '$T_CARRIER')."
      return 1
    fi
    if [ -n "$NI_PRESET" ]; then
      case "$NI_PRESET" in
        rst-fast) T_FAKESNI="www.cloudflare.com"; T_FAKEMODE="rst"; T_POOLROT="30m"; NI_SESSIONS=${NI_SESSIONS:-4}; NI_CONNS=${NI_CONNS:-4} ;;
        mci) T_FAKESNI="mci.ir"; T_FAKEMODE="rst"; T_POOLROT="30m"; T_POOLBYTES="500MB"; T_ECH="ladder"; T_GOVERNOR="true" ;;
        irancell) T_FAKESNI="irancell.ir"; T_FAKEMODE="seq"; T_POOLROT="20m"; T_POOLBYTES="300MB"; T_ECH="ladder"; T_GOVERNOR="true" ;;
        blackout) T_FAKESNI="mci.ir"; T_FAKEMODE="rst"; T_POOLROT="90s"; T_POOLBYTES="100MB"; T_ECH="ladder"; T_GOVERNOR="true" ;;
        conservative) T_FAKESNI="mci.ir"; T_FAKEMODE="seq"; T_POOLROT="4h"; T_POOLBYTES="4GB"; T_ECH="auto"; T_GOVERNOR="true" ;;
      esac
    fi
    [ -n "$NI_ECH" ] && T_ECH=$NI_ECH
    [ -n "$NI_GOVERNOR" ] && T_GOVERNOR=$NI_GOVERNOR
    [ -n "$NI_DNSLISTEN" ] && T_DNSLISTEN=$NI_DNSLISTEN
    [ -n "$NI_SRCIP" ] && T_SRCIP=$NI_SRCIP

    askres=y
    if [ -z "$NI_FAKESNI$NI_FAKEMODE$NI_FAKETTL$NI_POOLROT$NI_POOLBYTES$NI_PRESET$NI_ECH$NI_GOVERNOR$NI_DNSLISTEN$NI_SRCIP$T_FAKESNI$T_FAKEMODE$T_FAKETTL$T_POOLROT$T_POOLBYTES$T_ECH$T_GOVERNOR$T_DNSLISTEN$T_SRCIP" ]; then
      if [ "$NONINTERACTIVE" = 1 ]; then
        confirm "Set up anti-censor (only for censored routes)?" n || askres=n
        [ "$askres" = n ] && hint "No disguise: a busy direct tunnel can be filtered within an hour. Turn it on later with z on the tunnel page."
      else askres=n; fi # by hand: tunnel page, z
    fi

    if [ "$askres" = y ] && [ -z "$NI_FAKESNI$NI_PRESET" ] && [ -z "$T_FAKESNI" ]; then
      if is_pool_list "$T_CARRIER"; then
        echo
        say "  Anti-censor profile            ${GRY}sni          mode  churn          ech${RST}"
        say "  $(key_label 1) MCI whitelist              ${GRY}mci.ir       rst   30m / 500MB    ladder${RST}"
        say "  $(key_label 2) Irancell whitelist         ${GRY}irancell.ir  seq   20m / 300MB    ladder${RST}"
        say "  $(key_label 3) Blackout                   ${GRY}mci.ir       rst   90s / 100MB    ladder${RST}"
        say "  $(key_label 4) Low churn                  ${GRY}mci.ir       seq   4h / 4GB       auto${RST}"
        say "  $(key_label 5) Custom                     ${GRY}pick each value${RST}"
        say "  $(key_label 6) Skip                       ${GRY}no disguise${RST}"
        hint "2 and 4 (seq mode) only help against SNI-allowlist filters."
        printf '  %s?%s Profile %s[1]%s ' "$CYN" "$RST" "$GRY" "$RST"
        key_read
        case "$KEY" in
          1|enter) T_FAKESNI="mci.ir"; T_FAKEMODE="rst"; T_POOLROT="30m"; T_POOLBYTES="500MB"; T_ECH="ladder"; T_GOVERNOR="true" ;;
          2) T_FAKESNI="irancell.ir"; T_FAKEMODE="seq"; T_POOLROT="20m"; T_POOLBYTES="300MB"; T_ECH="ladder"; T_GOVERNOR="true" ;;
          3) T_FAKESNI="mci.ir"; T_FAKEMODE="rst"; T_POOLROT="90s"; T_POOLBYTES="100MB"; T_ECH="ladder"; T_GOVERNOR="true" ;;
          4) T_FAKESNI="mci.ir"; T_FAKEMODE="seq"; T_POOLROT="4h"; T_POOLBYTES="4GB"; T_ECH="auto"; T_GOVERNOR="true" ;;
          5) # Custom step-by-step
             pick_sni_preset "${T_FAKESNI:-mci.ir}" || return 1; T_FAKESNI=$REPLY_V
             if [ "$T_FAKESNI" = off ] || [ "$T_FAKESNI" = 0 ]; then T_FAKESNI=''; fi
             if [ -n "$T_FAKESNI" ]; then
               pick_fake_mode "${T_FAKEMODE:-rst}" || return 1; T_FAKEMODE=$REPLY_V
               if [ "$T_FAKEMODE" = ttl ]; then
                 ask "Fake TTL (hop count, empty = auto-calibrate)" "${T_FAKETTL:-}"; T_FAKETTL=$REPLY_V
                 v_fake_ttl "$T_FAKETTL" || return 1
               fi
             fi
             pick_pool_rotate "${T_POOLROT:-30m}" || return 1; T_POOLROT=$REPLY_V
             if [ "$T_POOLROT" = off ] || [ "$T_POOLROT" = 0 ]; then T_POOLROT=''; fi
             pick_pool_rotate_bytes "${T_POOLBYTES:-500MB}" || return 1; T_POOLBYTES=$REPLY_V
             if [ "$T_POOLBYTES" = off ] || [ "$T_POOLBYTES" = 0 ]; then T_POOLBYTES=''; fi
             if has_ech_list "$T_CARRIER"; then
               pick_ech "${T_ECH:-ladder}" || return 1; T_ECH=$REPLY_V
               if [ "$T_ECH" = off ]; then T_ECH=''; fi
             fi
             ;;
          6|esc|q) T_FAKESNI=''; T_FAKEMODE=''; T_POOLROT=''; T_POOLBYTES=''; T_ECH=''; T_GOVERNOR='' ;;
        esac
      elif [ "$T_CARRIER" = icmp ]; then
        echo
        say "  ${BOLD}ICMP resilience${RST}: the volume governor, not an SNI profile."
        confirm "Enable the ICMP volume governor (prevents reroute blackouts)?" y && T_GOVERNOR=true || T_GOVERNOR=false
      else
        hint "Anti-censorship profiles apply to tcp/tls/ws/wss/h2/h2c/grpc; '$T_CARRIER' has no SNI to disguise. Skipping."
      fi
    fi

    # Fallback validation for any flags that were passed explicitly (e.g. --fake-sni mci.ir)
    if [ -n "$NI_FAKESNI" ] && [ -z "$T_FAKESNI" ]; then
      T_FAKESNI=$NI_FAKESNI
    fi
    if [ "$T_FAKESNI" = off ] || [ "$T_FAKESNI" = 0 ]; then T_FAKESNI=''; fi
    if [ -n "$T_FAKESNI" ]; then
      v_sni_name "$T_FAKESNI" || return 1
      [ "$(bin_ver_ok 2.7.0)" = 1 ] || err "fake-sni needs wattun 2.7.0 or newer on this server (run: $SELF update)."
      [ -n "${NI_FAKEMODE:-}" ] && T_FAKEMODE=$NI_FAKEMODE
      [ -n "$T_FAKEMODE" ] || T_FAKEMODE=rst
      v_fake_mode "$T_FAKEMODE" || return 1
      T_FAKETTL=${NI_FAKETTL:-${T_FAKETTL:-}}
      if [ "$T_FAKEMODE" = ttl ] && [ -n "$T_FAKETTL" ]; then v_fake_ttl "$T_FAKETTL" || return 1; fi
    fi
    if [ -n "$NI_POOLROT" ]; then T_POOLROT=$NI_POOLROT; fi
    if [ -n "$NI_POOLBYTES" ]; then T_POOLBYTES=$NI_POOLBYTES; fi
    if [ -n "$T_POOLROT" ] && [ "$T_POOLROT" != 0 ] && [ "$T_POOLROT" != off ]; then
      [ "$(bin_ver_ok 2.8.0)" = 1 ] || { err "pool-rotate needs wattun 2.8.0 or newer on this server (run: $SELF update)."; return 1; }
    fi
    if [ -n "$T_POOLBYTES" ] && [ "$T_POOLBYTES" != 0 ] && [ "$T_POOLBYTES" != off ]; then
      [ "$(bin_ver_ok 2.8.1)" = 1 ] || { err "pool-rotate-bytes needs wattun 2.8.1 or newer on this server (run: $SELF update)."; return 1; }
    fi
  fi
  valid_name "$name" || { err "The name '$name' is not available."; return 1; }

  # summary
  echo
  allow_note=''; for ((i=0; i<${#MAPS[@]}; i++)); do allow_note="$allow_note $(spec_human "${MAPS[$i]}")"; done
  if [ "$NONINTERACTIVE" = 1 ]; then
    summary_line "Name" "$name"
    summary_line "Carrier" "$T_CARRIER${T_ICMP:+ ($T_ICMP)}"
    summary_line "Exit server" "$T_PEER"
    [ -n "$CT_DESC" ] && summary_line "CDN tuning" "$CT_DESC"
    if [ -n "$T_FAKESNI" ]; then
      local fsum="Fake SNI" fsv="$T_FAKESNI (${T_FAKEMODE:-seq} mode)"
      [ "$T_FAKEMODE" = ttl ] && [ -n "$T_FAKETTL" ] && fsv="$fsv, ttl $T_FAKETTL"
      summary_line "$fsum" "$fsv"
    fi
    [ -n "$T_POOLROT" ] && [ "$T_POOLROT" != 0 ] && [ "$T_POOLROT" != off ] && summary_line "Pool rotate" "$T_POOLROT${T_POOLBYTES:+ / $T_POOLBYTES}"
    [ -n "$T_ECH" ] && [ "$T_ECH" != off ] && summary_line "ECH" "$T_ECH"
    [ "$T_GOVERNOR" = true ] && summary_line "Governor" "on"
    if [ "$T_REV" = 1 ]; then
      if [ -n "$rport" ]; then summary_line "Direction" "reverse (the exit server dials :$rport)"
      else summary_line "Direction" "reverse (the exit server sends pings)"; fi
    fi
    summary_line "Publishes" "${allow_note# }"
    [ -n "$bind" ] && [ "$bind" != 0.0.0.0 ] && summary_line "Bind" "$bind"
    [ -n "$mbps" ] && summary_line "Speed limit" "$mbps MB/s"
    [ "$fec" = auto ] && summary_line "FEC" "auto"
  else
    [ "${UI_W:-0}" -gt 0 ] || ui_init_width
    box_top "Summary · $name"
    box_row "$(kv 'Carrier' "$T_CARRIER${T_ICMP:+ ($T_ICMP)}")"
    box_row "$(kv 'Exit server' "$T_PEER")"
    [ -n "$CT_DESC" ] && box_row "$(kv 'CDN' "$CT_DESC")"
    if [ -n "$T_FAKESNI" ]; then
      local fsv="$T_FAKESNI (${T_FAKEMODE:-seq})"
      [ "$T_FAKEMODE" = ttl ] && [ -n "$T_FAKETTL" ] && fsv="$fsv, ttl $T_FAKETTL"
      box_row "$(kv 'Fake SNI' "$fsv")"
    fi
    [ -n "$T_POOLROT" ] && [ "$T_POOLROT" != 0 ] && [ "$T_POOLROT" != off ] && box_row "$(kv 'Rotate' "$T_POOLROT${T_POOLBYTES:+ / $T_POOLBYTES}")"
    [ -n "$T_ECH" ] && [ "$T_ECH" != off ] && box_row "$(kv 'ECH' "$T_ECH")"
    [ "$T_GOVERNOR" = true ] && box_row "$(kv 'Governor' "on")"
    if [ "$T_REV" = 1 ]; then
      if [ -n "$rport" ]; then box_row "$(kv 'Direction' "reverse (Kharej dials :$rport)")"
      else box_row "$(kv 'Direction' "reverse (Kharej sends pings)")"; fi
    fi
    box_row "$(kv 'Publishes' "${allow_note# }")"
    [ -n "$bind" ] && [ "$bind" != 0.0.0.0 ] && box_row "$(kv 'Bind' "$bind")"
    [ -n "$mbps" ] && box_row "$(kv 'Max speed' "$mbps MB/s")"
    [ "$fec" = auto ] && box_row "$(kv 'FEC' "auto")"
    box_bot
  fi
  local udl; udl=$(undisguised_legs "$T_CARRIER")
  [ -n "$T_FAKESNI$T_POOLROT$T_POOLBYTES" ] && [ -n "$udl" ] && warn "Bond leg(s) '$udl' stay undisguised (only TCP/TLS/HTTP legs use fake-SNI)."
  case "$T_CARRIER" in
    wss|grpc|h2)
      if [ "$T_REV" != 1 ] && [ -z "$CT_DESC" ] && { ph=${T_PEER%%,*}; ipv4_ok "${ph%:*}"; }; then
        echo
        warn "Direct IP peer (${ph%:*}) — bypasses Cloudflare"
        hint "Use a CF-proxied domain, or run: $SELF cdn-tune $name"
      fi ;;
  esac
  echo
  if [ "$NONINTERACTIVE" = 1 ]; then confirm "Create this tunnel?" y || { warn "Nothing was created."; return 1; }; fi

  m=$(free_metrics_port)
  write_client() {
    local old; old=$(umask); umask 077
    printf '%s\n' "$T_KEY" >"$CONF/$name.key" || return 1
    {
      echo "# WatTunnel - the entry server (client). Created by wattun-manager."
      echo "mode: client"
      echo "key-file: $CONF/$name.key"
      echo "carrier: $T_CARRIER"
      echo "peer: $T_PEER"
      # The pasted token is stored beside the config (0600): the Go cockpit's paired
      # detection reads NAME.token's field 10 (owner directive 2026-11-23).
      [ -n "$tok" ] && { umask 077; printf '%s\n' "$tok" >"$CONF/$name.token"; }
      local _bl # M1: a bond token's per-leg endpoints (empty for a single carrier); each leg dials its own.
                # A directional leg (:up/:down, 3.3.9) dials the same address as its base carrier, and the
                # engine registers per-carrier flags under the base name, so the key loses the suffix.
      for ((_bl=0; _bl<${#T_LEG_C[@]}; _bl++)); do echo "peer-$(carrier_leg_base "${T_LEG_C[$_bl]}"): ${T_LEG_P[$_bl]}"; done
      if [ "$T_CARRIER" = udp ] && [ "$T_PATH" = dns ]; then echo "udp-dns: true" # DNS-shaped udp: the token's path field carries "dns"
      elif [ -n "$T_PATH" ]; then echo "path: $T_PATH"; fi
      [ -n "$T_SNI" ] && { echo "sni: $T_SNI"; echo "host: $T_SNI"; }
      [ -n "$T_FAKESNI" ] && { echo "fake-sni: $T_FAKESNI"; [ -n "$T_FAKEMODE" ] && echo "fake-mode: $T_FAKEMODE"; [ "$T_FAKEMODE" = ttl ] && [ -n "$T_FAKETTL" ] && echo "fake-ttl: $T_FAKETTL"; }
      [ -n "$T_POOLROT" ] && [ "$T_POOLROT" != 0 ] && [ "$T_POOLROT" != off ] && echo "pool-rotate: $T_POOLROT"
      [ -n "$T_POOLBYTES" ] && [ "$T_POOLBYTES" != 0 ] && [ "$T_POOLBYTES" != off ] && echo "pool-rotate-bytes: $T_POOLBYTES"
      if [ -n "$T_ECH" ]; then
        [ "$T_ECH" != off ] && echo "ech: $T_ECH"
        [ -n "$AT_EXTRA" ] && AT_EXTRA=$(printf '%s\n' "$AT_EXTRA" | grep -v '^ech:' || true)
      fi
      [ "$T_GOVERNOR" = true ] && echo "governor: true"
      [ -n "$T_DNSLISTEN" ] && [ "$T_DNSLISTEN" != off ] && echo "dns-listen: $T_DNSLISTEN"
      [ -n "$T_SRCIP" ] && [ "$T_SRCIP" != off ] && echo "src-ip: $T_SRCIP"
      [ -n "$T_ICMP" ] && [ "$T_ICMP" != echo ] && echo "icmp-type: $T_ICMP"
      [ "$T_REV" = 1 ] && echo "reverse: true"
      [ -n "$rport" ] && echo "listen: \":$rport\""
      # Owner directive (2026-11-22): automatic latch revival needs the port on
      # Iran too — when the pairing rides the token, the client config carries the
      # default (Kharej's wizard may have moved off it on a collision; the Go
      # cockpit self-heals the real port from doctor.fetch).
      [ -n "$T_PAIR" ] && [ "$T_REV" != 1 ] && echo "latch-port: $SCEPTER_LATCH_DEFAULT" # no latch on reverse: Kharej's re-dial revives it
      [ -n "$AT_EXTRA" ] && printf '%s\n' "$AT_EXTRA"
      ech_cache_line "$name"
      [ -n "$bind" ] && [ "$bind" != 0.0.0.0 ] && echo "bind: $bind"
      [ -n "$mbps" ] && echo "max-mbps: $mbps"
      [ "$fec" = auto ] && echo "fec: auto"
      sessions_line
      conns_line
      mtu_line
      [ -n "$m" ] && echo "metrics: 127.0.0.1:$m" # F25: free_metrics_port found no port; write no invalid line
      maps_yaml_block
    } >"$CONF/$name.yml"
    umask "$old"
  }
  mkdir -p "$CONF"; chmod 700 "$CONF"
  sessions_check
  step "Writing key and config" write_client || return 1
  if [ -n "$AUTO_TOKEN" ]; then # kept so auto-test / auto-heal can test again later
    ( umask 077; printf '%s\n' "$AUTO_TOKEN" >"$CONF/$name.auto" ); chmod 600 "$CONF/$name.auto"
  fi
  start_unit "$name" || return 1
  [ "$T_CARRIER" = icmp ] && [ "$T_REV" = 1 ] && kreply_offer
  [ "${#rports[@]}" -gt 0 ] && fw_open "${rports[*]}" # before the link check: Kharej cannot connect until reverse ports are open
  for ((i=0; i<${#MAPS[@]}; i++)); do new_pub+=("$(spec_L "${MAPS[$i]}")/$(spec_P "${MAPS[$i]}")"); done
  fw_open "${new_pub[*]}"
  if ! systemctl is-enabled -q "$HEAL_UNIT.timer" 2>/dev/null; then
    heal_enable >/dev/null && [ "$NONINTERACTIVE" = 1 ] && ok "Auto-heal on (Settings, h)"
  fi
  echo
  if wait_link "$name" 25; then
    conn_card "$name" "$T_CARRIER" "$LINK_RTT" "${MAPS[@]}"
  else
    linkok=0
    err "Not connected yet — running doctor"
    test_tunnel "$name"
  fi
  if [ "$NONINTERACTIVE" = 1 ] && [ "$linkok" = 1 ] && is_pool_list "$T_CARRIER" && [ "$(uname -s)" = Linux ] && [ -z "$T_FAKESNI$T_POOLROT$T_POOLBYTES" ] \
     && ! grep -q '^fake-sni:' <<<"${AT_EXTRA:-}"; then
    if [ "$T_REV" = 1 ]; then hint "If a censor blocks it: anti-censor is set on the exit server (the side that dials), tunnel page, z."
    else hint "If a censor blocks it: tunnel page, z."; fi
  fi
  if [ "$fecb" = 1 ] && [ "$NONINTERACTIVE" != 1 ]; then
    echo; hint "FEC auto is on; opening the loss-band rows now."
    adv_menu "$name"
  fi
  if [ "$NONINTERACTIVE" = 1 ]; then
    printf 'LINK=%s\nTUNNEL=%s\n' "$([ "$linkok" = 1 ] && echo up || echo down)" "$name"
    [ "$linkok" = 1 ] || return 1
  fi
  return 0
}

SESS_USE=''
sessions_check() { # --sessions N: only when the installed wattun knows the key (>= 2.3.0; older engines reject unknown keys)
  SESS_USE=''
  [ -n "$NI_SESSIONS" ] || return 0
  if ver_ge "$(bin_ver || true)" 2.3.0 2>/dev/null; then SESS_USE=$NI_SESSIONS
  else warn "--sessions $NI_SESSIONS ignored: it needs wattun 2.3.0 or newer (this is ${VER:-unknown}); run: $SELF update"; fi
  return 0
}
sessions_line() { # the engine refuses sessions with icmp/gre/ipip, bonds, reverse, or more than 16
  # no default here: the engine's auto value fits the host (2 on 2 CPUs). Forcing 4 or 8 made sessions fight over
  # the same queue: direct tcp 2026-11-03, 2 sessions 248 MB/s, 8 sessions 68 MB/s.
  [ -n "$SESS_USE" ] || return 0
  if [ "$T_REV" = 1 ]; then warn "--sessions ignored: not supported in reverse mode" >&2; return 0; fi
  if ! sessions_carrier_ok "$T_CARRIER"; then
    warn "--sessions ignored: not supported with carrier '$T_CARRIER' (needs one udp/tcp/tls/ws/wss/h2/h2c/grpc carrier)" >&2
    return 0
  fi
  echo "sessions: $(( SESS_USE > ENG_MAX_SESSIONS ? ENG_MAX_SESSIONS : SESS_USE ))"; return 0
}
conns_line() {
  [ -n "${NI_CONNS:-}" ] && echo "conns: $NI_CONNS"
  return 0
}
mtu_line() { # a non-pool leg caps the engine's datagram size at 1400: warn instead of writing a value it clamps
  [ -n "${NI_MTU:-}" ] || return 0
  local hi; hi=$(mtu_max_for "${T_CARRIER:-}")
  if [ "${NI_MTU}" -gt "$hi" ]; then
    warn "--mtu $NI_MTU ignored: carrier '${T_CARRIER:-?}' caps the datagram at $hi (the engine would clamp it silently)." >&2
    return 0
  fi
  echo "mtu: $NI_MTU"
}

# ======================================================================================
#  Auto carrier: one token, Iran tests every connection type and keeps the best
#    Kharej: unit NAME (all carriers at once) + NAME-r (the reverse side, written by a watcher as soon as Iran's IP
#    is known). Iran: auto_test runs one throw-away client per variant and uses the built-in /speedtest.
#    Token field 9 (the plan): "d=udp:4443,tcp:4443,...;r=tcp:24431,..." (see make_token).
# ======================================================================================
AUTO_RUN=${WAT_AUTO_RUN:-/run/$WAT_PREFIX-auto}
AUTO_D=''; AUTO_NOTE=''; AUTO_ADDR=''; AUTO_EXT=0; AUTO_EXT_D=''
# Auto mode is data-driven: the token's plan (field 9) is the only source of direct/reverse variants (order = test
# order). AUTO_VAR_CDN needs a Cloudflare domain in the token, AUTO_VAR_REVERSE is the reverse set (icmp first, then
# pool legs), AUTO_VAR_ANTI is the direct pool subset that gets the fake-SNI/fingerprint variants of the anti-censor
# preset. AUTO_VAR_DIRECT is the default standard plan written by a new Kharej token; an old token's plan is honoured
# as-is, so a manager can never test a carrier Kharej does not listen on.
# B1/B2/B3 (2026-11-04): the plan grammar is `carrier[:port]`; a raw carrier (gre/ipip, and the F19 raw shapes) has no
# listen port and appears as a bare entry. gre/ipip need both ends >= 3.2.0 and are part of the normal plan; the 13
# shaped carriers are an explicit extended opt-in (both ends 3.3.0) and never mixed into a normal token.
AUTO_VAR_DIRECT='icmp udp tcp tls wss h2 grpc ws h2c gre ipip'
AUTO_VAR_EXT_UDP=$SHAPED_UDP # extended-only UDP-tier shapes (conventional/allocated port)
AUTO_VAR_EXT_RAW=$SHAPED_RAW # extended-only raw-tier shapes (bare plan entry, no listen/firewall)
AUTO_VAR_CDN='wss grpc'
AUTO_VAR_REVERSE='icmp tcp tls ws wss h2 h2c grpc'
AUTO_VAR_ANTI='tcp tls wss h2 grpc ws h2c'
# Anti-censor fast preset (2026-11-21): the two desync modes that clear a permit-list filter in the field
# (rst, synrst — see the anti grid's field note) against the two operator allowlist SNIs and the Cloudflare
# edge name: 6 rows per direct pool carrier instead of the full grid's ~28, minutes instead of half an hour.
AT_FAST_MODES='rst synrst'
AT_FAST_SNIS='mci.ir irancell.ir cloudflare.com'
# The reverse listen ports of a new auto token: one random open port per reverse carrier except icmp.
auto_rplan_build() { # [base] -> "tcp:P1,tls:P2,..." (when base given: sequential from base; else random open ports)
  local out='' c p=${1:-}
  if [ -z "$p" ]; then
    auto_pick_rplan
    return $?
  fi
  for c in $AUTO_VAR_REVERSE; do
    [ "$c" = icmp ] && continue
    out="${out:+$out,}$c:$p"; p=$((p+1))
  done
  printf '%s' "$out"
}
auto_pick_rplan() { # [exclude_space_sep] -> "tcp:P1,tls:P2,..." unique random open ports across AUTO_VAR_REVERSE
  local excl=" ${1:-} " tf raw rp c p out='' proto
  for tf in "$CONF"/*.token; do
    [ -e "$tf" ] || continue
    raw=$(sed 's/^wat1://' "$tf" | base64 -d 2>/dev/null || true)
    [ -n "$raw" ] || continue
    rp=$(printf '%s' "$raw" | awk -F'|' '{print $9}')
    rp=$(plan_part "$rp" r)
    for c in ${rp//,/ }; do
      p=$(plan_entry_port "$c")
      [ -n "$p" ] && excl+="$p "
    done
  done
  for c in $AUTO_VAR_REVERSE; do
    [ "$c" = icmp ] && continue
    proto=$(rproto "$c")
    p=$(rand_open_port "$proto" "$excl") || return 1
    excl+="$p "
    out="${out:+$out,}$c:$p"
  done
  printf '%s' "$out"
}
plan_part() { # plan d|r -> "udp:4443,tcp:4443,..."
  local x
  for x in ${1//;/ }; do [ "${x%%=*}" = "$2" ] && { echo "${x#*=}"; return 0; }; done
  return 0
}
plan_has() { # list carrier -> 0 when the plan has that carrier (bare `gre` or `vxlan:4789`)
  local x
  for x in ${1//,/ }; do [ "${x%%:*}" = "$2" ] && return 0; done
  return 1
}
# A6 (2026-11-04): the Iran side shows what the token plan carries, split standard/extended, before testing. Extended
# entries are the F19 shaped carriers; an old engine skips them (auto_variants/AT_SKIPPED) so the budget counts only
# what is really measured.
auto_plan_standard() { # plan-d -> its non-shaped carrier names in plan order
  local c n out=''
  for c in ${1//,/ }; do n=${c%%:*}; is_ext_carrier "$n" && continue; out="${out:+$out }$n"; done
  printf '%s' "$out"
}
auto_plan_extnames() { # plan-d -> its shaped carrier names in plan order (empty for a normal token)
  local c n out=''
  for c in ${1//,/ }; do n=${c%%:*}; is_shaped_carrier "$n" && out="${out:+$out }$n"; done
  printf '%s' "$out"
}
auto_plan_intro() { # plan-d -> human lines for the test screen ("standard carriers: …" / "extended carriers: …")
  local d=$1 std ext
  std=$(auto_plan_standard "$d"); ext=$(auto_plan_extnames "$d")
  printf 'standard carriers: %s\n' "${std:-none}"
  [ -n "$ext" ] && printf 'extended carriers: %s (both ends must run 3.3.0; shaped transports, not the real protocols)\n' "$ext"
  return 0
}

# B3 (2026-11-04): extended Auto opens ONE hidden single-carrier server unit per shaped carrier, because the 3.3.0
# engine refuses any '+' bond containing a shaped carrier (D7). The parent auto unit keeps the standard carriers +
# gre/ipip; a `.autoext` sidecar (holding the parent name) hides each child from tunnel lists/pickers while delete,
# uninstall, heal, prune and widen still manage them.
is_auto_ext() { [ -f "$CONF/$1.autoext" ]; }
auto_ext_names() { # parent -> its extended unit names ($parent-e-<shape>); only units whose .autoext names this parent
  local f b p
  for f in "$CONF/$1-e-"*.yml; do
    [ -e "$f" ] || continue
    b=${f##*/}; b=${b%.yml}
    p=''; [ -f "$CONF/$b.autoext" ] && read -r p <"$CONF/$b.autoext" # read, not $(cat): no fork per helper
    [ "$p" = "$1" ] || continue # M1: a user tunnel named NAME-e-* is not a child
    echo "$b"
  done
  return 0
}
auto_ext_space_taken() { # name : is any NAME-e-* config present (the hidden-child namespace stays reserved)
  local f; for f in "$CONF/$1-e-"*.yml; do [ -e "$f" ] && return 0; done; return 1
}
auto_ext_child() { printf '%s-e-%s' "$1" "$2"; }
auto_ext_plan_entries() { # [exclude_space_sep] -> "vxlan:P1,...,sit,..." for every shaped carrier (random open UDP ports)
  local c p q used=" ${1:-} " out=''
  for c in ${AUTO_D:-}; do
    for p in ${c//,/ }; do q=$(plan_entry_port "$p"); [ -n "$q" ] && used+="$q "; done
  done
  for c in $AUTO_VAR_EXT_UDP; do
    q=$(rand_open_port udp "$used") || q=''
    [ -n "$q" ] || { AUTO_NOTE+="  $c: no free UDP port, skipped."$'\n'; continue; }
    used+="$q "; out="${out:+$out,}$c:$q"
  done
  for c in $AUTO_VAR_EXT_RAW; do out="${out:+$out,}$c"; done
  printf '%s' "$out"
}
auto_ext_write_units() { # name entries : write the hidden per-shape server configs + sidecars and open their UDP ports
  local name=$1 entries=$2 e c p u m fw='' keyf="$CONF/$1.key" bad=''
  mkdir -p "$CONF"
  for e in ${entries//,/ }; do # M1: never overwrite a .yml that is not already a child of this parent
    u=$(auto_ext_child "$name" "${e%%:*}")
    [ -e "$CONF/$u.yml" ] || continue
    [ "$(cat "$CONF/$u.autoext" 2>/dev/null)" = "$name" ] || bad=$u
  done
  [ -z "$bad" ] || { err "Refusing to overwrite $CONF/$bad.yml: it is not an extended listener of '$name'."; return 1; }
  for e in ${entries//,/ }; do
    c=${e%%:*}; p=$(plan_entry_port "$e"); u=$(auto_ext_child "$name" "$c")
    m=$(cfg "$u" metrics); m=${m##*:}; [ -n "$m" ] || m=$(free_metrics_port)
    {
      echo "# WatTunnel - the exit server extended test listener for auto tunnel '$name' ($c). Hidden; created by wattun-manager."
      echo "mode: server"
      echo "key-file: $keyf"
      echo "carrier: $c"
      [ -n "$p" ] && echo "listen: \":$p\""
      [ -n "$m" ] && echo "metrics: 127.0.0.1:$m" # F25: free_metrics_port found no port; write no invalid line
      maps_yaml_block # H2: without the parent's allowlist the engine falls back to its permissive 1-65535 default
      # H2: inherit the parent's per-port limits, source allowlist, and shared server tunables.
      if [ -f "$CONF/$name.yml" ]; then
        awk '/^(limits|allow-clients|allow-clients-file|max-mbps|fec|fec-on-loss|fec-off-loss|win-max|loss-ceiling|shape-data|noise|noise-bps|noise-window|state-dir|state-save):/{f=1} f && /^[a-zA-Z0-9_-]+:/ && !/^(limits|allow-clients|allow-clients-file|max-mbps|fec|fec-on-loss|fec-off-loss|win-max|loss-ceiling|shape-data|noise|noise-bps|noise-window|state-dir|state-save):/{f=0; next} f{print}' "$CONF/$name.yml" 2>/dev/null
      fi
    } >"$CONF/$u.yml" || return 1
    chmod 600 "$CONF/$u.yml"
    ( umask 077; printf '%s\n' "$name" >"$CONF/$u.autoext" )
    [ -n "$p" ] && fw="$fw $p/udp"
  done
  [ -n "$fw" ] && fw_open "${fw# }"
  return 0
}
auto_ext_start() { # parent : (re)enable+restart every extended listener of an auto tunnel
  local parent=$1 n
  for n in $(auto_ext_names "$parent"); do systemctl enable "${WAT_PREFIX}@$n" >/dev/null 2>&1; done
  for n in $(auto_ext_names "$parent"); do
    systemctl restart "${WAT_PREFIX}@$n" >/dev/null 2>&1
  done
  return 0
}
auto_ext_live() { # parent -> AE_LIVE = child units with a live client; rc 1 when a running child's /stats cannot be read
  # H1 (2026-11-04): each shaped listener is a single-carrier server with its own metrics port, and the parent's /stats
  # cannot show which shape Iran picked. A stopped unit has no metrics server (expected, not unknown); an unreadable
  # one is treated as unknown so the caller keeps every shape instead of guessing.
  local n s live='' any=0 bad=0
  for n in $(auto_ext_names "$1"); do
    any=1
    systemctl is-active -q "${WAT_PREFIX}@$n" 2>/dev/null || continue
    if s=$(stats "$n") && grep -q '"clients"' <<<"$s"; then
      grep -q '"ip"' <<<"$(grep -o '"clients": *\[[^]]*\]' <<<"$s")" && live="$live${live:+ }$n"
    else
      bad=1
    fi
  done
  AE_LIVE=$live
  [ "$any" = 1 ] || return 2
  [ "$bad" = 0 ]
}
auto_ext_sig() { # parent -> the live hidden pick ("e:vxlan"), empty when no child is provably in use
  local n out=''
  auto_ext_live "$1" || return 0
  for n in $AE_LIVE; do out="$out${out:+,}e:${n#"$1"-e-}"; done
  printf '%s' "$out"
}
plan_entry_port() { # one plan entry -> its port, or empty for a port-less raw entry (B1)
  case "${1:-}" in *:*) echo "${1##*:}" ;; *) echo '' ;; esac
  return 0
}
plan_port() { # list carrier -> port (empty for a bare raw entry)
  local x p
  for x in ${1//,/ }; do
    [ "${x%%:*}" = "$2" ] || continue
    p=$(plan_entry_port "$x"); echo "$p"; return 0
  done
  return 0
}
ver_ge() { [ "$(printf '%s\n%s\n' "$2" "$1" | sort -V | head -1)" = "$2" ]; } # $1 >= $2
bin_ver_ok() { # min-version -> 1 when the installed wattun is new enough (empty output = not ok)
  ver_ge "$(bin_ver || true)" "$1" 2>/dev/null && echo 1
  return 0
}
declare -A AUTO_KH_C=() # is_auto_kharej answers cached for one heal pass only (HEAL_PASS=1): a token's carrier does not
                        # change under it, and the sed|base64 pair cost ~50 ms a call on a loaded 1-core host, ~100 calls
                        # per pass. The interactive menu lives long and may recreate a tunnel, so it never caches.
is_auto_kharej() { # name : does NAME.token carry carrier "auto"?
  local raw k="$CONF/$1.token"
  [ -f "$k" ] || return 1
  if [ "${HEAL_PASS:-0}" = 1 ] && [ -n "${AUTO_KH_C[$k]:-}" ]; then [ "${AUTO_KH_C[$k]}" = auto ]; return; fi
  raw=$(sed 's/^wat1://' "$k" | base64 -d 2>/dev/null) || return 1
  AUTO_KH_C[$k]=${raw%%|*}
  [ "${raw%%|*}" = auto ]
}
companion_of() { # name -> parent name when NAME is an auto reverse companion (NAME-r)
  local p=${1%-r}
  [ "$p" != "$1" ] && [ -f "$CONF/$p.yml" ] && is_auto_kharej "$p" && echo "$p"
  return 0
}
in_use() { # auto Kharej name -> the types Iran is connected through ("udp", "tcp+wss", "r:icmp", "vxlan"), empty before it connects
  local u='' c
  auto_live "$1"
  for c in $AN_D; do u+="${u:++}$c"; done
  for c in $AN_R; do u+="${u:++}r:$c"; done
  for c in $AN_E; do u+="${u:++}$c"; done
  echo "$u"
}
carrier_label() { # name -> short carrier text for lists
  if is_auto_kharej "$1"; then echo auto; elif [ -n "$(companion_of "$1")" ]; then echo auto-r; else cfg "$1" carrier; fi
}

# ---- Kharej side ----
AUTO_USED_PORTS=''
auto_pick_ports() { # [cdn_mode=0] -> AUTO_D "udp:P1,tcp:P2,...,gre,ipip", AUTO_USED_PORTS and AUTO_NOTE ; rc 1 when no free port is left
  # The plan is built from AUTO_VAR_DIRECT (order = test order): carriers with a listen port get `name:port`, raw
  # carriers (gre/ipip) get a bare `name` because they have no port. Direct mode always picks random open ports;
  # CDN mode (--cdn-domain) picks non-443/80 Cloudflare-proxyable ports for CDN carriers (with Origin-Rule fallback).
  local cdn_mode=${1:-} c proto pick used=' ' list=''
  [ -n "$cdn_mode" ] || { [ -n "${NI_CDN:-}" ] && cdn_mode=1 || cdn_mode=0; }
  AUTO_NOTE=''; AUTO_SKIP=''; AUTO_USED_PORTS=''
  for c in $AUTO_VAR_DIRECT; do
    [ "$c" = icmp ] && continue
    if ! carrier_ok_here "$c"; then
      AUTO_SKIP+="${AUTO_SKIP:+, }$c"
      AUTO_NOTE+="  $c needs wattun $(carrier_min_ver "$c"); this server runs ${VER:-an old version} - skipped."$'\n'
      continue
    fi
    if ! carrier_has_listen "$c"; then # B1: raw carrier, no port/listen line
      list="${list:+$list,}$c"; continue
    fi
    proto=$(rproto "$c")
    pick=''
    if [ "$cdn_mode" = 1 ] && is_cdn_carrier "$c"; then
      pick=$(pick_cf_cdn_port "$c" "$used") || pick=''
      if [ -n "$pick" ] && [ "${CF_ORIGIN_FALLBACK:-0}" = 1 ]; then
        AUTO_NOTE+="  $c: non-443/80 Cloudflare ports busy, using random port $pick (needs a Cloudflare Origin Rule)."$'\n'
      fi
    else
      pick=$(rand_open_port "$proto" "$used") || pick=''
    fi
    [ -n "$pick" ] || { AUTO_FAIL="$c ($proto)"; return 1; }
    used+="$pick "
    list="${list:+$list,}$c:$pick"
  done
  AUTO_D=$list
  AUTO_USED_PORTS=${used# }
}
ask_public_addr() { # -> AUTO_ADDR ; rc 1 when cancelled
  local addr
  if [ -n "$NI_ADDR" ]; then addr=$NI_ADDR
  else spin_start "Detecting this server's public IP"; addr=$(public_ip); spin_stop; fi
  if [ -z "$NI_ADDR" ] && [ -n "$addr" ] && ip_is_private "$addr"; then
    warn "$addr looks like a private address; the entry server cannot reach it."
    confirm "Use $addr anyway? (n = enter the public IP yourself)" n || addr=''
    [ -z "$addr" ] && hint "Behind NAT or a cloud 1:1 mapping? Enter the public IP shown in your provider's panel."
  elif [ -z "$addr" ]; then
    warn "Could not detect this server's public IP."
    [ "$NONINTERACTIVE" = 1 ] && hint "Give it with --addr HOST"
  fi
  if [ -z "$addr" ]; then
    ask_ok "Public IP or domain of this server" "" v_host || return 1; addr=$REPLY_V
  else
    ok "Public address: $addr"
  fi
  AUTO_ADDR=$addr
}
start_watcher() { # name : transient unit that waits for Iran's first connection, then writes NAME-r
  local u="${WAT_PREFIX}-autowatch-$1" m=$MGR renv
  mapfile -t renv < <(run_env_args)
  [ -x "$m" ] || m=$(readlink -f "$0")
  systemctl stop "$u.service" >/dev/null 2>&1; systemctl reset-failed "$u.service" >/dev/null 2>&1
  systemd-run --quiet --collect --unit "$u" --property=RuntimeMaxSec=3600 "${renv[@]}" \
    "$m" auto-watch "$1" >/dev/null 2>&1
}
wizard_kharej_auto() { # suggested-name : called from wizard_kharej when the carrier is "auto"
  local name=$1 n=1 cdn='' key m allow plan c p cars='' fwl='' ver line
  ver=$(bin_ver)
  if ! ver_ge "${ver:-0}" 2.1.0; then
    err "Auto needs wattun 2.1.0 or newer on this server (found ${ver:-none})."; hint "Update first: $SELF update"; return 1
  fi
  command -v systemd-run >/dev/null 2>&1 || { err "Auto needs systemd (systemd-run) on this server."; return 1; }
  if [ -n "$NI_NAME" ]; then
    { [ -e "$CONF/$name.yml" ] || [ -e "$CONF/$name-r.yml" ] || auto_ext_space_taken "$name"; } \
      && { err "A tunnel named '$name', '$name-r' or '$name-e-*' already exists."; return 1; }
  fi
  while { [ -e "$CONF/$name.yml" ] || [ -e "$CONF/$name-r.yml" ] || auto_ext_space_taken "$name"; } && [ "$n" -lt 99 ]; do n=$((n+1)); name="kharej-$n"; done
  cdn=$NI_CDN # --cdn-domain reserves Cloudflare-proxyable ports for wss/grpc/ws/h2c/h2; direct mode keeps random ports
  [ -n "$cdn" ] && { v_domain_opt "$cdn" || return 1; }
  local cdn_mode=0 used_all
  [ -n "$cdn" ] && cdn_mode=1
  auto_pick_ports "$cdn_mode" || { err "Could not find a free port for $AUTO_FAIL on this server."; hint "Check what listens there: ss -ltnup"; return 1; }

  MAPS=(); PE_ROLE=Kharej; PE_TUNNEL=$name; PE_ALLOW=(); PE_OWNED=(); PE_MSG=''
  allow='' # all ports allowed (unless --ports); edit later from the tunnel menu
  if [ -n "$NI_PORTS" ]; then ni_kharej_ports || return 1; allow=$(maps_allow_str); fi

  ask_public_addr || return 1
  # 3.6.0 (owner 2026-11-24): the 13 shaped carriers are always planned when this engine runs them; Iran picks
  # them with the Extended test preset. --extended stays the explicit form that fails loudly on an old engine.
  carrier_ok_here vxlan && AUTO_EXT=1
  if [ "${NI_EXTENDED:-0}" = 1 ]; then
    if ! carrier_ok_here vxlan; then
      err "--extended needs wattun 3.3.0 on this server (found ${ver:-none}); both ends must run 3.3.0. Run: $SELF update"
      return 1
    fi
    AUTO_EXT=1
  fi
  local rplan
  rplan=$(auto_pick_rplan "$AUTO_USED_PORTS") || { err "Could not find free reverse ports on this server."; return 1; }
  used_all=" $AUTO_USED_PORTS "
  for c in ${rplan//,/ }; do p=$(plan_entry_port "$c"); [ -n "$p" ] && used_all+="$p "; done
  AUTO_EXT_D=''
  if [ "$AUTO_EXT" = 1 ]; then
    AUTO_EXT_D=$(auto_ext_plan_entries "$used_all")
    [ -n "$AUTO_EXT_D" ] || { warn "No extended carrier could be planned; continuing with the standard set."; AUTO_EXT=0; }
  fi
  plan="d=$AUTO_D${AUTO_EXT_D:+,$AUTO_EXT_D};r=$rplan"
  [ "$AUTO_EXT" = 1 ] && plan="$plan;e=1"

  [ -n "$AUTO_NOTE" ] && printf '%s' "$AUTO_NOTE" | sed "s/^/  $GRY/; s/\$/$RST/"

  key=$(new_key); m=$(free_metrics_port); apath=$(rand_path)
  for c in ${AUTO_D//,/ }; do cars="$cars+${c%%:*}"; done
  # Owner directive (2026-11-22): the first mint embeds the token-bootstrap pairing
  # (field 10, pair=full unless an expert row preset a tier) and latch-port rides the
  # server config — no ask for either; collision-checked against every port this
  # wizard picked (plan, reverse plan, metrics). Field 10 is pair=<tier> verbatim
  # (ParsePairingTokenField is L5-strict; a bare tier arms nothing).
  T_PAIR=${T_PAIR:-pair=$SCEPTER_DEFAULT_TIER}
  local latch='' re ex
  ex=" $m "
  for re in $AUTO_USED_PORTS; do ex+="$re "; done
  for re in ${rplan//,/ }; do p=$(plan_entry_port "$re"); [ -n "$p" ] && ex+="$p "; done
  for re in ${AUTO_EXT_D//,/ }; do p=$(plan_entry_port "$re"); [ -n "$p" ] && ex+="$p "; done
  latch=$(pick_latch_port $ex) || latch=''
  write_auto_server() {
    local old; old=$(umask); umask 077
    printf '%s\n' "$key" >"$CONF/$name.key" || return 1
    {
      echo "# WatTunnel - the exit server (server), auto: every carrier at once. Created by wattun-manager."
      echo "mode: server"
      echo "key-file: $CONF/$name.key"
      echo "carrier: icmp$cars"
      for c in ${AUTO_D//,/ }; do p=$(plan_entry_port "$c"); [ -n "$p" ] && echo "listen-${c%%:*}: \":$p\""; done
      echo "path: $apath"
      [ -n "$latch" ] && echo "latch-port: $latch" # the scepter latch listener (3.5.0); picked collision-free
      [ -n "$m" ] && echo "metrics: 127.0.0.1:$m" # F25: free_metrics_port found no port; write no invalid line
      maps_yaml_block
    } >"$CONF/$name.yml"
    make_token auto "$AUTO_ADDR" "$key" "$apath" "$cdn" "" "$allow" "" "$plan" "$T_PAIR" >"$CONF/$name.token"
    umask "$old"
  }
  mkdir -p "$CONF"; chmod 700 "$CONF"
  step "Writing key, config and token" write_auto_server || return 1
  start_unit "$name" || return 1
  for c in ${AUTO_D//,/ }; do
    p=$(plan_entry_port "$c"); [ -n "$p" ] || continue # B1: raw carriers have no listen port/firewall rule
    if [ "${c%%:*}" = udp ] || is_shaped_udp "${c%%:*}"; then fwl="$fwl $p/udp"; else fwl="$fwl $p/tcp"; fi
  done
  fw_open "${fwl# }"
  if [ "$AUTO_EXT" = 1 ]; then # B3: one hidden single-carrier listener per extended shape
    if ! step "Writing extended listeners" auto_ext_write_units "$name" "$AUTO_EXT_D"; then
      # F16: this tunnel is fresh, so a child-write failure rolls it back instead of leaving a running parent whose
      # token promises `;e=1` shapes with no (or only partial) listeners.
      systemctl disable --now "${WAT_PREFIX}@$name" >/dev/null 2>&1 # stop before the state files: the engine saves on SIGTERM
      while IFS= read -r line; do rm -f "$line"; done < <(state_files "$name")
      rm -f "$CONF/$name"-e-*.yml "$CONF/$name"-e-*.autoext
      fw_close "${fwl# }"
      rm -f "$CONF/$name".yml "$CONF/$name".key "$CONF/$name".token
      err "Could not write the extended listeners; the new tunnel was removed and nothing is running."
      return 1
    fi
    auto_ext_start "$name" >/dev/null 2>&1 || warn "Could not start the extended listeners; heal will retry."
  fi
  start_watcher "$name" || warn "Could not start the watcher. After the entry server connects run: $SELF auto-ip $name IRAN_IP"
  ensure_heal_timer # heal() keeps NAME-r synced with Iran's IP and watches hidden helpers
  line=''; for c in ${AUTO_D//,/ }; do p=$(plan_entry_port "$c"); if [ -n "$p" ]; then line="$line · ${c%%:*} $p"; else line="$line · ${c%%:*}"; fi; done
  echo
  celebrate "Exit tunnel '$name' ready"
  hint "Firewall: allow ICMP$line"
  if [ "$AUTO_EXT" = 1 ]; then
    ok "Extended (hidden): $(auto_plan_extnames "$AUTO_EXT_D")"
    hint "Extended carriers require wattun 3.3.0 on the entry server + IP protocols 41/50/97/115 open."
  fi
  echo
  printf '  %s%s%s\n\n' "$BOLD$YEL" "$(cat "$CONF/$name.token")" "$RST"
  token_qr "$(cat "$CONF/$name.token")"
  step_diagram 2
  echo
  say "  Next on the entry server: run ${CYN}${SELF}${RST} → $(key_label n) → paste token"
  hint "Token contains secret key — share privately ($SELF token $name)"
  hint "Pairing rides this token (field 10, $T_PAIR): the entry server's wizard picks it up, no watp1: line needed."
  [ "$NONINTERACTIVE" = 1 ] && printf 'TUNNEL=%s\nTOKEN=%s\n' "$name" "$(cat "$CONF/$name.token")"
  return 0
}

# Reverse companion: written once Iran's IP is known and kept updated by heal() if Iran's IP changes.
# Prefer non-CDN carriers (icmp/udp/tcp/tls/...) because CDN carriers report Cloudflare's edge IP in clients[].
companion_create() { # name ip [no_start=0]
  local n=$1 ip=$2 no_start=${3:-0} r="$1-r" f="$CONF/$1-r.yml" m rp c cars='' old tmp
  ip=${ip#[}; ip=${ip%]}
  ( umask 077; printf '%s\n' "$ip" >"$CONF/$n.iranip" ) 2>/dev/null || true
  if [ -f "$f" ] && [ "$(cat "$CONF/$n.iranip" 2>/dev/null)" = "$ip" ] \
     && { [ "$(cfg "$r" peer-icmp)" = "$ip" ] || grep -qF "Entry server $ip)" "$f" 2>/dev/null; }; then
    return 0
  fi
  if ! { [ -f "$CONF/$n.token" ] && read_token "$(cat "$CONF/$n.token")" && [ -n "$T_AUTO" ]; }; then
    err "No auto token for '$n'."; return 1
  fi
  rp=$(plan_part "$T_AUTO" r)
  m=$(cfg "$r" metrics); m=${m##*:}; [ -n "$m" ] || m=$(free_metrics_port)
  ipv4_ok "$ip" && cars=icmp
  for c in ${rp//,/ }; do cars="${cars:+$cars+}${c%%:*}"; done
  load_maps "$n"
  old=$(umask); umask 077
  tmp=$(mktemp "$CONF/.tmp.XXXXXX") || { umask "$old"; return 1; }
  {
    echo "# WatTunnel - Kharej reverse side of auto tunnel '$n' (Iran $ip). Hidden; written by wattun-manager."
    echo "mode: server"
    echo "key-file: $CONF/$n.key"
    echo "carrier: $cars"
    echo "reverse: true"
    ipv4_ok "$ip" && echo "peer-icmp: $ip"
    for c in ${rp//,/ }; do echo "peer-${c%%:*}: $(join_hp "$ip" "${c##*:}")"; done
    echo "path: ${T_PATH:-/wat}"
    echo "pool-rotate: 30m"
    [ -n "$m" ] && echo "metrics: 127.0.0.1:$m" # F25: write no invalid metrics: line when the range is exhausted
    maps_yaml_block
  } >"$tmp"
  chmod 600 "$tmp"; wmv "$tmp" "$f"; umask "$old"
  auto_sync_helper_settings "$n" "$r"
  if [ "$no_start" != 1 ]; then
    ensure_template >/dev/null
    systemctl enable "${WAT_PREFIX}@$r" >/dev/null 2>&1
    systemctl restart "${WAT_PREFIX}@$r" >/dev/null 2>&1
  fi
  logger -t wattun-auto "learned entry IP $ip for $n; synced ${WAT_PREFIX}@$r (hidden reverse companion)"
  return 0
}
auto_detect_iran_ip() { # name [cdn] -> prints first usable Iran client IP (prefers non-CDN clients)
  local n=$1 cdn=${2:-} u s cl obj car ip='' cdn_ip=''
  # bash regexes, no grep/sed/cut per line: heal runs this for every helper of every auto tunnel, and the forks
  # cost a 1-core Kharej with 5 auto tunnels about 15 s of CPU per pass
  local re_cl='"clients": *\[([^]]*)\]' re_obj='\{[^{}]*\}' re_car='"carrier": *"([^"]*)"' re_ip='"ip": *"([^"]*)"'
  for u in "$n" $(auto_ext_names "$n"); do
    u_active "$u" || continue
    s=$(stats "$u") || continue
    [[ $s =~ $re_cl ]] || continue
    cl=${BASH_REMATCH[1]}
    while [[ $cl =~ $re_obj ]]; do
      obj=${BASH_REMATCH[0]}; cl=${cl#*"$obj"}
      car=''; ip=''
      [[ $obj =~ $re_car ]] && car=${BASH_REMATCH[1]}
      [[ $obj =~ $re_ip ]] && ip=${BASH_REMATCH[1]}
      { ipv4_ok "$ip" || ipv6_ok "$ip"; } || { ip=''; continue; }
      if is_cdn_carrier "$car"; then
        [ -z "$cdn" ] && [ -z "$cdn_ip" ] && cdn_ip=$ip
      else
        printf '%s' "$ip"; return 0
      fi
    done
  done
  [ -n "$cdn_ip" ] && printf '%s' "$cdn_ip"
  return 0
}
auto_watch() { # name : run by systemd-run; poll /stats clients, write the companion on the first usable Iran client
  local n=$1 ip='' cdn=''
  [ -f "$CONF/$n.token" ] && read_token "$(cat "$CONF/$n.token")" && cdn=$T_SNI
  logger -t wattun-auto "watching $n for the entry server's first connection"
  while [ -f "$CONF/$n.yml" ]; do
    ip=$(auto_detect_iran_ip "$n" "$cdn")
    if [ -n "$ip" ]; then companion_create "$n" "$ip"; return $?; fi
    sleep 2
  done
  return 0
}
auto_sync_companion() { # name : called by heal() on Kharej to create/update hidden NAME-r whenever Iran's IP appears or changes
  local n=$1 cdn='' ip cur_ip
  is_auto_kharej "$n" || return 0
  u_active "$n" || return 0
  [ -f "$CONF/$n.token" ] && read_token "$(cat "$CONF/$n.token")" && cdn=$T_SNI
  ip=$(auto_detect_iran_ip "$n" "$cdn")
  [ -n "$ip" ] || return 0
  cur_ip=$(head -1 "$CONF/$n.iranip" 2>/dev/null || true)
  if [ ! -f "$CONF/$n-r.yml" ] || [ "$cur_ip" != "$ip" ]; then
    companion_create "$n" "$ip" >/dev/null 2>&1 || return 0
    systemctl stop "${WAT_PREFIX}-autowatch-$n.service" >/dev/null 2>&1
    systemctl reset-failed "${WAT_PREFIX}-autowatch-$n.service" >/dev/null 2>&1
  fi
  return 0
}
auto_ip() { # name ip : manual fallback to set/update Iran's IP for hidden companion
  local n=$1 ip=${2:-}
  ip=${ip#[}; ip=${ip%]}
  is_auto_kharej "$n" || { err "'$n' is not an auto exit tunnel."; return 1; }
  if ! ipv4_ok "$ip" && ! ipv6_ok "$ip"; then err "Usage: $SELF auto-ip $n IRAN_IP"; return 1; fi
  companion_create "$n" "$ip" || return 1
  systemctl stop "${WAT_PREFIX}-autowatch-$n.service" >/dev/null 2>&1
  ensure_heal_timer
  ok "Reverse side for '$n' is set for the entry server $ip. Run the test again on the entry server."
}

# Read live carrier picks across all units of an auto Kharej tunnel (direct, reverse companion, extended shapes).
AN_D=''; AN_R=''; AN_E=''
auto_live() { # name -> AN_D, AN_R, AN_E (space separated)
  local n=$1 s live one u
  AN_D=''; AN_R=''; AN_E=''
  if s=$(stats "$n"); then
    # clients[] names one carrier per session (the last one heard); carriers[] has every leg of a bonded client
    live=$({ grep -o '"clients": *\[[^]]*\]' <<<"$s" | sed 's/},[[:space:]]*{/}\n{/g' | grep -o '"carrier": *"[^"]*"' | cut -d'"' -f4
      grep -o '"carriers": *\[[^]]*\]' <<<"$s" | sed 's/},[[:space:]]*{/}\n{/g' | grep '"alive": *true' | grep -o '"name": *"[^"]*"' | cut -d'"' -f4
    } | sed '/^$/d' | sort -u | tr '\n' ' ')
    # 3.3.8: a finalized single-carrier tunnel has empty carriers[] (and on reverse, empty clients[].carrier too)
    if [ -z "$live" ] && { [ "$(jget "$s" alive)" = true ] || { [ "${s#*\"sessions\":}" != "$s" ] && [ "$(jget "$s" sessions)" -gt 0 ] 2>/dev/null; }; }; then
      one=$(cfg "$n" carrier); case "$one" in *+*|'') ;; *) live="$one " ;; esac
    fi
    if is_reverse "$n"; then AN_R=$live; else AN_D=$live; fi
  fi
  if [ -f "$CONF/$n-r.yml" ] && s=$(stats "$n-r"); then
    AN_R=$(grep -o '"carriers": *\[[^]]*\]' <<<"$s" | sed 's/},[[:space:]]*{/}\n{/g' | grep '"alive": *true' | grep -o '"name": *"[^"]*"' | cut -d'"' -f4 | tr '\n' ' ')
    if [ -z "$AN_R" ] && [ "$(jget "$s" alive)" = true ]; then
      one=$(cfg "$n-r" carrier); case "$one" in *+*|'') ;; *) AN_R="$one " ;; esac
    fi
  fi
  if auto_ext_live "$n" >/dev/null 2>&1; then
    for u in $AE_LIVE; do AN_E+="${u#"$n"-e-} "; done
  fi
}
auto_set_carriers() { # name "direct carriers" "reverse carriers" : rewrite the carrier lists of NAME and NAME-r from the token's plan
  local n=$1 dl=$2 rl=$3 c p cars blk d r ip tmp old pv
  { [ -f "$CONF/$n.token" ] && read_token "$(cat "$CONF/$n.token")" && [ -n "$T_AUTO" ]; } || { err "No auto token for '$n'."; return 1; }
  d=$(plan_part "$T_AUTO" d); r=$(plan_part "$T_AUTO" r)
  old=$(umask); umask 077
  if [ -n "$dl" ]; then
    cars=''; blk=''
    for c in $dl; do
      cars="$cars+$c"
      p=$(plan_port "$d" "$c"); [ -n "$p" ] && blk="$blk"$'\n'"listen-$c: \":$p\""
    done
    tmp=$(mktemp "$CONF/.tmp.XXXXXX") || { umask "$old"; return 1; }
    awk -v blk="carrier: ${cars#+}$blk" '/^carrier:/ { if (!done) { print blk; done = 1 } next } /^listen-[a-z0-9-]+:/ { next } { print }' "$CONF/$n.yml" >"$tmp" \
      && chmod 600 "$tmp" && mv -f "$tmp" "$CONF/$n.yml"
  fi
  if [ -n "$rl" ] && [ -f "$CONF/$n-r.yml" ]; then
    ip=$(cfg "$n-r" peer-icmp)
    [ -n "$ip" ] || ip=$(head -1 "$CONF/$n.iranip" 2>/dev/null || true)
    if [ -z "$ip" ]; then
      pv=$(sed -n 's/^peer-[a-z0-9-]*:[[:space:]]*//p' "$CONF/$n-r.yml" 2>/dev/null | head -1 | tr -d "\"'")
      [ -n "$pv" ] && { split_hp "$pv"; ip=$HP_HOST; }
    fi
    cars=''; blk=''
    for c in $rl; do
      [ "$c" = icmp ] && ! ipv4_ok "$ip" && continue
      cars="$cars+$c"
      p=$(plan_port "$r" "$c"); [ -n "$p" ] && [ -n "$ip" ] && blk="$blk"$'\n'"peer-$c: $(join_hp "$ip" "$p")"
    done
    tmp=$(mktemp "$CONF/.tmp.XXXXXX") || { umask "$old"; return 1; }
    awk -v blk="carrier: ${cars#+}$blk" '/^carrier:/ { if (!done) { print blk; done = 1 } next } /^peer-icmp:/ { print; next } /^peer-[a-z0-9-]+:/ { next } { print }' "$CONF/$n-r.yml" >"$tmp" \
      && chmod 600 "$tmp" && mv -f "$tmp" "$CONF/$n-r.yml"
  fi
  umask "$old"
}
fw_port_list() { # "carrier ..." plan-d -> "4443/udp 4443/tcp ..." (the firewall rules the direct carriers need)
  local c p out=''
  for c in $1; do
    p=$(plan_port "$2" "$c"); [ -n "$p" ] || continue
    out="$out $p/$([ "$c" = udp ] && echo udp || echo tcp)"
  done
  echo "$out"
}
auto_plan_lists() { # plan -> AP_D, AP_R: the carriers of the token's plan; shaped entries are hidden units, not bond legs (B3)
  local c
  AP_D='icmp'; AP_R='icmp'
  for c in $(plan_part "$1" d | tr ',' ' '); do
    is_ext_carrier "${c%%:*}" && continue
    case "${c%%:*}" in icmp) ;; *) AP_D="$AP_D ${c%%:*}" ;; esac
  done
  for c in $(plan_part "$1" r | tr ',' ' '); do case "${c%%:*}" in icmp) ;; *) AP_R="$AP_R ${c%%:*}" ;; esac; done
}
auto_drop_unit() { # unit : stop, disable and delete one internal helper unit of an auto tunnel (config, state files, its UDP rule)
  local u=$1 p s
  systemctl disable --now "${WAT_PREFIX}@$u" >/dev/null 2>&1 # H8: stop before the state files go
  p=$(cfg "$u" listen); p=${p##*:}
  [ -n "$p" ] && is_auto_ext "$u" && is_shaped_udp "$(cfg "$u" carrier)" && [ -z "$(tunnel_using_listen "$p" "$u")" ] \
    && fw_close "$p/udp" # F17; a port another tunnel also owns keeps its rule
  while IFS= read -r s; do rm -f "$s"; done < <(state_files "$u")
  rm -f "$CONF/$u".yml "$CONF/$u".ech "$CONF/$u".autoext
}
auto_sync_helper_settings() { # parent [single_helper] : propagate shared server settings & limits from parent to hidden helpers
  local n=$1 only=${2:-} u blk tmp old
  [ -f "$CONF/$n.yml" ] || return 0
  blk=$(awk '/^(limits|max-mbps|fec|fec-on-loss|fec-off-loss|win-max|loss-ceiling|shape-data|noise|noise-bps|noise-window|state-dir|state-save|allow-clients|allow-clients-file):/{f=1} f && /^[a-zA-Z0-9_-]+:/ && !/^(limits|max-mbps|fec|fec-on-loss|fec-off-loss|win-max|loss-ceiling|shape-data|noise|noise-bps|noise-window|state-dir|state-save|allow-clients|allow-clients-file):/{f=0; next} f{print}' "$CONF/$n.yml" 2>/dev/null)
  local -a targets=()
  if [ -n "$only" ]; then targets=("$only")
  else while IFS= read -r u; do [ -n "$u" ] && targets+=("$u"); done < <(auto_helpers "$n"); fi
  old=$(umask); umask 077
  for u in "${targets[@]}"; do
    [ -f "$CONF/$u.yml" ] || continue
    tmp=$(mktemp "$CONF/.tmp.XXXXXX") || continue
    awk '/^(limits|max-mbps|fec|fec-on-loss|fec-off-loss|win-max|loss-ceiling|shape-data|noise|noise-bps|noise-window|state-dir|state-save|allow-clients|allow-clients-file):/{f=1; next} f && /^[[:space:]]+-/{next} f{f=0} {print}' "$CONF/$u.yml" >"$tmp"
    if [ -n "$blk" ]; then
      if [ "$u" = "$n-r" ]; then
        grep -vE '^allow-clients(-file)?:' <<<"$blk" >>"$tmp" || true
      else
        printf '%s\n' "$blk" >>"$tmp"
      fi
    fi
    chmod 600 "$tmp" && mv -f "$tmp" "$CONF/$u.yml" || rm -f "$tmp"
  done
  umask "$old"
  return 0
}
auto_needs_reopen() { # name -> 0 when an auto Kharej tunnel was narrowed/finalized or is missing planned carriers/helpers
  local n=$1 cur_d cur_r c exp_ext u
  is_auto_kharej "$n" || return 1
  if [ -f "$CONF/$n.finalized" ] || [ -f "$CONF/$n.keepopen" ] \
     || [ -f "$RUN/$n.autoprune.done" ] || [ -f "$RUN/$n.autoprune" ] \
     || [ -f "$RUN/$n.autowiden" ] || [ -f "$RUN/$n.autowiden.down" ] \
     || [ -f "$RUN/$n.abandoned" ]; then
    return 0
  fi
  if is_reverse "$n" || is_shaped_carrier "$(cfg "$n" carrier)" || [ -n "$(cfg "$n" listen)" ]; then
    return 0
  fi
  read_token "$(cat "$CONF/$n.token")" >/dev/null 2>&1 && [ -n "$T_AUTO" ] || return 1
  auto_plan_lists "$T_AUTO"
  cur_d=$(cfg "$n" carrier)
  # 4.0.2-4.0.4 bash reopened ptcp/spray into the main bond, which the engine refuses: repair it
  case "+$cur_d+" in *+ptcp+*|*+spray+*) return 0 ;; esac
  for c in $AP_D; do
    case "+$cur_d+" in *"+$c+"*) ;; *) return 0 ;; esac
  done
  if [ -f "$CONF/$n-r.yml" ]; then
    cur_r=$(cfg "$n-r" carrier)
    local rip=''; rip=$(head -1 "$CONF/$n.iranip" 2>/dev/null || true)
    for c in $AP_R; do
      [ "$c" = icmp ] && [ -n "$rip" ] && ! ipv4_ok "$rip" && continue
      case "+$cur_r+" in *"+$c+"*) ;; *) return 0 ;; esac
    done
  fi
  if [ "$(plan_part "$T_AUTO" e)" = 1 ]; then
    for c in $(plan_part "$T_AUTO" d | tr ',' ' '); do
      exp_ext=${c%%:*}
      is_shaped_carrier "$exp_ext" || continue
      u=$(auto_ext_child "$n" "$exp_ext")
      [ -f "$CONF/$u.yml" ] && [ "$(cat "$CONF/$u.autoext" 2>/dev/null)" = "$n" ] || return 0
    done
  fi
  return 1
}
auto_reopen() { # name : reopen all planned carriers of an auto Kharej tunnel (migration from 3.3.0-3.3.8 narrowed/finalized)
  local n=$1 d dl rl pip c ext_d='' was_on=0 tmp old u
  if [ ! -f "$CONF/$n.token" ] && head -1 "$CONF/$n.yml" 2>/dev/null | grep -qE 'Kept by wattun-manager from auto tunnel|auto: every carrier at once'; then
    rebuild_kharej_token "$n" >/dev/null 2>&1 || true
  fi
  is_auto_kharej "$n" || { err "'$n' is not an auto exit tunnel."; return 1; }
  read_token "$(cat "$CONF/$n.token")" && [ -n "$T_AUTO" ] || { err "No auto token for '$n'."; return 1; }
  if systemctl is-active -q "${WAT_PREFIX}@$n" 2>/dev/null || systemctl is-enabled -q "${WAT_PREFIX}@$n" 2>/dev/null; then
    was_on=1
  fi
  if is_reverse "$n" && [ ! -s "$CONF/$n.iranip" ]; then
    pip=$(cfg "$n" peer-icmp); [ -n "$pip" ] || { split_hp "$(cfg "$n" peer)"; pip=$HP_HOST; }
    if [ -z "$pip" ]; then
      local pv; pv=$(sed -n 's/^peer-[a-z0-9-]*:[[:space:]]*//p' "$CONF/$n.yml" 2>/dev/null | head -1 | tr -d "\"'")
      [ -n "$pv" ] && { split_hp "$pv"; pip=$HP_HOST; }
    fi
    [ -n "$pip" ] && ( umask 077; printf '%s\n' "$pip" >"$CONF/$n.iranip" ) 2>/dev/null || true
  fi
  if [ -f "$CONF/$n.finalized" ] || is_reverse "$n" || is_shaped_carrier "$(cfg "$n" carrier)" || [ -n "$(cfg "$n" listen)" ]; then
    old=$(umask); umask 077
    tmp=$(mktemp "$CONF/.tmp.XXXXXX") || { umask "$old"; return 1; }
    awk '/^(reverse|peer|peer-[a-z0-9-]+|listen|sni|host|pool-rotate(-bytes)?|fake-sni|fake-mode|fake-ttl|ech|ech-cache):/{next} {print}' "$CONF/$n.yml" >"$tmp" \
      && chmod 600 "$tmp" && mv -f "$tmp" "$CONF/$n.yml" || { rm -f "$tmp"; umask "$old"; return 1; }
    umask "$old"
    [ -n "$(cfg "$n" path)" ] || set_value "$n" path "${T_PATH:-/wat}"
  fi
  rm -f "$RUN/$n.autoprune" "$RUN/$n.autoprune.done" "$CONF/$n.finalized" "$CONF/$n.keepopen" \
        "$RUN/$n.autowiden" "$RUN/$n.autowiden.down" "$RUN/$n.abandoned"
  d=$(plan_part "$T_AUTO" d); auto_plan_lists "$T_AUTO"; dl=$AP_D; rl=$AP_R
  auto_set_carriers "$n" "$dl" "$rl" || return 1
  fw_open "$(fw_port_list "$dl" "$d")" >/dev/null 2>&1 || true
  if [ -f "$CONF/$n-r.yml" ]; then
    auto_sync_helper_settings "$n" "$n-r"
  elif [ -s "$CONF/$n.iranip" ]; then
    companion_create "$n" "$(head -1 "$CONF/$n.iranip")" "$([ "$was_on" = 1 ] && echo 0 || echo 1)" || true
  fi
  if [ "$(plan_part "$T_AUTO" e)" = 1 ]; then
    for c in ${d//,/ }; do is_shaped_carrier "${c%%:*}" && ext_d="${ext_d:+$ext_d,}$c"; done
    if [ -n "$ext_d" ]; then
      load_maps "$n"
      auto_ext_write_units "$n" "$ext_d" >/dev/null 2>&1 || true
    fi
  fi
  if [ "$was_on" = 1 ]; then
    ensure_template >/dev/null
    systemctl enable "${WAT_PREFIX}@$n" >/dev/null 2>&1
    systemctl restart "${WAT_PREFIX}@$n" >/dev/null 2>&1
    for u in $(auto_helpers "$n"); do
      systemctl enable "${WAT_PREFIX}@$u" >/dev/null 2>&1
      systemctl restart "${WAT_PREFIX}@$u" >/dev/null 2>&1
    done
    [ -f "$CONF/$n-r.yml" ] || start_watcher "$n" >/dev/null 2>&1 || true
  fi
  ensure_heal_timer
  logger -t wattun-auto "migrated auto tunnel $n to always-open carriers"
  return 0
}
auto_migrate_all() { # [announce=0] : migrate any legacy narrowed/finalized auto Kharej tunnels to always-open
  local announce=${1:-0} n locked=0
  for n in $(tunnels); do
    [ "$(role "$n")" = Kharej ] || continue
    if [ ! -f "$CONF/$n.token" ] && head -1 "$CONF/$n.yml" 2>/dev/null | grep -qE 'Kept by wattun-manager from auto tunnel|auto: every carrier at once'; then
      [ "$locked" = 1 ] || { mgr_lock >/dev/null 2>&1 || return 0; locked=1; }
      rebuild_kharej_token "$n" >/dev/null 2>&1 || true
    fi
    is_auto_kharej "$n" || continue
    auto_needs_reopen "$n" || continue
    [ "$locked" = 1 ] || { mgr_lock >/dev/null 2>&1 || return 0; locked=1; }
    if auto_reopen "$n" >/dev/null 2>&1 && [ "$announce" = 1 ]; then
      ok "Reopened all carriers on '$n' (always-open mode)."
    fi
  done
  return 0
}

heal_auto_helpers() { # parent : keep hidden auto helpers running whenever their parent is active and enabled
  local parent=$1 u
  is_auto_kharej "$parent" || return 0
  u_enabled "$parent" || return 0
  u_active "$parent" || return 0
  for u in $(auto_helpers "$parent"); do
    u_enabled "$u" || systemctl enable "${WAT_PREFIX}@$u" >/dev/null 2>&1
    if ! u_active "$u"; then
      logger -t wattun-heal "auto helper $u is down, restarting"
      systemctl restart "${WAT_PREFIX}@$u" >/dev/null 2>&1
    fi
  done
  return 0
}

# ---- Iran side: test runner ----
AV_LABEL=(); AV_CAR=(); AV_KIND=(); AV_PEER=(); AV_PORT=(); AV_SNI=(); AV_FP=(); AV_ECH=(); AV_FRAG=()
AV_FS=(); AV_FM=(); AV_X=() # fake-sni / fake-mode per variant (anti-censor matrix, 2.10.2)
AR_OK=(); AR_DOWN=(); AR_UP=(); AR_RTT=(); AR_WHY=()
AT_QUIET=0; AT_MB=2; AT_DIR=''; AT_PID=''; AT_FW=''; AT_ADDR=''; AT_SKIP=''; AT_DLINK=0; AT_SECS=0; AT_APPLIED=0
AT_PRESET=normal; AT_STTY=''; AT_KEYS=0; AT_ACT=''; AT_STOP=0; AT_GSKIP=''
AT_RANK=(); AT_SEL=(); AT_SEL_LABEL=''; AT_SEL_KEY=''; AT_EXTRA=''; AUTO_TOKEN=''
# /speedtest streams per session (2.4.18+; an older engine ignores the query value and uses its own default). The
# screening asks for 8 streams, the finalists for 16 to show what a busy tunnel does (methodology 2026-11-03).
AT_STREAMS=8; AT_PLAN=''; AT_TUNE_MB=0; AT_SKIPPED=''
# H2/H3/D8 (3.3.0 audit): measurement sizes are duration-based, not fixed. Screening starts at 8 MB each way and may
# grow x4 up to 16 MB once the first measured rate says 8 MB is under the 1.5 s floor (a traffic guard; the finalists
# carry the sustained measurement). Finalists need >=1.5 s at the measured rate, clamped to 20-40 MB. Tuning probes are
# fixed at 20 MB each way and only test sessions/conns (the reduced D8 grid). at_budget prints all three phases.
AT_SCREEN_MB_START=8; AT_SCREEN_CAP_MB=16
AT_FINAL_MB_MIN=20; AT_FINAL_MB_MAX=40
AT_TUNE_PROBE_MB=20
at_probe_mb() { # rate-MB/s [min-secs] [cap-MB] -> MB per direction: start 8, x4 until >= min-secs at that rate, capped
  local rate=${1:-0} min=${2:-1.5} cap=${3:-200} mb=$AT_SCREEN_MB_START
  case "$cap" in ''|*[!0-9]*) cap=200 ;; esac
  [ "$cap" -lt "$AT_SCREEN_MB_START" ] && cap=$AT_SCREEN_MB_START
  case "$rate" in ''|*[!0-9.]*|0|0.0|.) echo "$AT_SCREEN_MB_START"; return 0 ;; esac
  while [ "$mb" -lt "$cap" ] && awk -v m="$mb" -v r="$rate" -v s="$min" 'BEGIN{exit !(m/r < s)}'; do mb=$((mb*4)); done
  [ "$mb" -gt "$cap" ] && mb=$cap
  echo "$mb"
}
at_skipped_hint() { # B2: one clear sentence for carriers the Iran engine cannot run; empty when nothing was skipped
  [ -n "$AT_SKIPPED" ] || return 0
  printf 'Token includes %s; this server runs %s and cannot test them (both ends need newer wattun for these transports).' \
    "$AT_SKIPPED" "${VER:-an older wattun}"
}
at_budget() { # screening-variants screen-MB finalist-MB tuning-probes tuning-MB -> true worst case, MB + rough minutes
  # True worst case = in all 3 phases (H2): every variant gets both directions, so N variants = N*2*MB. The minutes
  # assume a conservative 8 MB/s aggregate (480 MB/min); a fast link finishes sooner, a slow one later, but the MB
  # figure (the part that costs money) is exact for the caps used.
  awk -v n="${1:-0}" -v s="${2:-8}" -v f="${3:-40}" -v p="${4:-0}" -v t="${5:-20}" \
    'BEGIN{mb=n*2*s+3*2*f+p*2*t; m=int((mb+479)/480); if(m<1)m=1; printf "up to %d MB, about %d min", mb, m}'
}
at_tune_probe_count() { # "sessions:1,2 conns:4,8" -> 1 baseline + one probe per value (pure, used by at_budget)
  local kv v out=1
  for kv in $1; do for v in $(tr ',' ' ' <<<"${kv#*:}"); do [ -n "$v" ] && out=$((out+1)); done; done
  echo "$out"
}
at_best_rate() { # current-best index... -> the fastest measured direction so far (MB/s; used to size the next probe)
  local best=${1:-0} i v
  shift || true
  for i in "$@"; do
    [ "${AR_OK[$i]:-0}" = 1 ] || continue
    v=$(awk -v a="${AR_DOWN[$i]:-0}" -v b="${AR_UP[$i]:-0}" 'BEGIN{m=(a>b)?a:b; printf "%g", m}')
    awk -v v="$v" -v b="$best" 'BEGIN{exit !(v > b)}' && best=$v
  done
  echo "$best"
}
AT_HOP=12 # Wraith packets per source port: field cut is ~30 per flow, 12-18 leaves a margin
av_hop() { sed -n 's/.*-udp-hop=\([0-9]*\).*/\1/p' <<<"${AV_X[$1]:-}"; } # variant -> its udp-hop value, empty = none
at_hop_line() { # AT_SEL -> "udp-hop: N" into AT_EXTRA when a chosen row hops
  local i h
  for i in "${AT_SEL[@]}"; do h=$(av_hop "$i"); [ -n "$h" ] && { AT_EXTRA+="${AT_EXTRA:+$'\n'}udp-hop: $h"; return 0; }; done
  return 0
}
av_add() { # label carrier kind(d|c|r) peer port sni [fp ech tls-frag [fake-sni fake-mode [extra flags]]] (fp..frag: CDN variants, wattun >= 2.2.0; fake-*: matrix; extra: auto tuning)
  AV_LABEL+=("$1"); AV_CAR+=("$2"); AV_KIND+=("$3"); AV_PEER+=("$4"); AV_PORT+=("$5"); AV_SNI+=("$6")
  AV_FP+=("${7:-}"); AV_ECH+=("${8:-}"); AV_FRAG+=("${9:-}")
  AV_FS+=("${10:-}"); AV_FM+=("${11:-}"); AV_X+=("${12:-}")
}
av_key() {
  case "${AV_CAR[$1]}" in *+*) [ "${AV_KIND[$1]}" = r ] && echo bond/r || echo bond; return ;; esac
  local k="${AV_CAR[$1]}/${AV_KIND[$1]}"; [ -n "$(av_hop "$1")" ] && k+=/hop; av_anti "$1" && k+="/${AV_FS[$1]}-${AV_FM[$1]}-${AV_FP[$1]}-${AV_ECH[$1]}-${AV_FRAG[$1]}"; echo "$k"
}
av_anti() { [ "${AV_KIND[$1]}" = d ] && [ -n "${AV_FS[$1]}${AV_FP[$1]}${AV_ECH[$1]}${AV_FRAG[$1]}" ]; } # a direct variant that carries desync / fingerprint / fragmentation (anti-censor preset)
# Anti-censor preset: every direct pool carrier of the plan with every desync mode (first curated SNI), the three modes that
# cleared a filter in the field (rst, synrst, paws) against the other curated SNIs and the Cloudflare edge name, the TLS
# ClientHello split and fingerprint variants, ECH. Reverse tunnels are not covered: the desync runs on the dialing side,
# which for a reverse tunnel is Kharej, and this test only controls this server. The mode list itself is AC_ALLMODES
# (defined once, near v_fake_mode, H6): the matrix and the validator cannot drift apart.
auto_variants_anti() { # direct plan part
  local d=$1 c p fs fm first=${AC_SNIS%%,*} others tls hp
  others="${AC_SNIS#*,},www.cloudflare.com"
  for c in $AUTO_VAR_ANTI; do
    p=$(plan_port "$d" "$c"); [ -n "$p" ] || continue
    hp=$(join_hp "$AT_ADDR" "$p")
    for fm in $AC_ALLMODES; do
      av_add "$c $fm $first" "$c" d "$hp" '' '' '' '' '' "$first" "$fm"
    done
    for fs in ${others//,/ }; do
      for fm in rst synrst paws; do av_add "$c $fm ${fs#www.}" "$c" d "$hp" '' '' '' '' '' "$fs" "$fm"; done
    done
    case "$c" in tls|wss|h2|grpc)
      av_add "$c tls-frag mid-SNI" "$c" d "$hp" '' '' '' '' -1
      av_add "$c tls-frag 40" "$c" d "$hp" '' '' '' '' 40
      for fm in chrome firefox safari; do av_add "$c fp $fm" "$c" d "$hp" '' '' "$fm"; done
      [ -n "$T_SNI" ] && av_add "$c chrome+ech" "$c" d "$hp" '' "$T_SNI" chrome auto ;;
    esac
  done
  return 0
}
# The fast preset's cut of the anti grid: every direct pool carrier x AT_FAST_MODES x AT_FAST_SNIS. The rows are
# ordinary anti variants (av_anti sees the fake-sni/fake-mode pair), so the ranked table, the 8 % rank margin and
# at_to_t's fake-sni/fake-mode lines all apply unchanged — no separate apply path.
auto_variants_fast() { # direct plan part
  local d=$1 c p fs fm hp
  for c in $AUTO_VAR_ANTI; do
    p=$(plan_port "$d" "$c"); [ -n "$p" ] || continue
    hp=$(join_hp "$AT_ADDR" "$p")
    for fs in $AT_FAST_SNIS; do
      for fm in $AT_FAST_MODES; do av_add "$c $fm $fs" "$c" d "$hp" '' '' '' '' '' "$fs" "$fm"; done
    done
  done
  return 0
}
auto_variants() { # T_* from the auto token -> AV_* (the token's plan is the source; B1/B2/B4)
  local d r c p name
  AV_LABEL=(); AV_CAR=(); AV_KIND=(); AV_PEER=(); AV_PORT=(); AV_SNI=(); AV_FP=(); AV_ECH=(); AV_FRAG=()
  AV_FS=(); AV_FM=(); AV_X=()
  split_hp "$T_PEER"; AT_ADDR=$HP_HOST; AT_PATH=${T_PATH:-/wat}; AT_SKIPPED=''
  d=$(plan_part "$T_AUTO" d); r=$(plan_part "$T_AUTO" r)
  # reverse preset: only the plan's r= variants — for routes where nothing but reverse passes
  if [ "$AT_PRESET" != reverse ]; then
  ipv4_ok "$AT_ADDR" && av_add icmp icmp d "$AT_ADDR" '' ''
  for c in ${d//,/ }; do # plan order = test order; a bare entry is a port-less raw carrier (gre/ipip/shaped raw)
    name=${c%%:*}; p=$(plan_entry_port "$c")
    [ "$name" = icmp ] && continue # the bare-IP icmp variant is the first row, added above
    is_raw_carrier "$name" && ! ipv4_ok "$AT_ADDR" && continue
    if ! carrier_ok_here "$name"; then AT_SKIPPED+="${AT_SKIPPED:+, }$name"; continue; fi # B2: Iran skips what it cannot run
    if { is_shaped_raw "$name" || is_shaped_udp "$name"; } && [ "$AT_PRESET" != extended ]; then continue # Extended preset rows (3.6.0)
    elif is_shaped_raw "$name"; then av_add "$name (shape only)" "$name" d "$AT_ADDR" '' ''
    elif is_shaped_udp "$name"; then av_add "$name (shape only)" "$name" d "$(join_hp "$AT_ADDR" "$p")" '' ''
    elif [ -n "$p" ]; then av_add "$name" "$name" d "$(join_hp "$AT_ADDR" "$p")" '' ''
    else av_add "$name" "$name" d "$AT_ADDR" '' ''; fi
    # Wraith (3.3.9, Iran side only): the same udp port from a new source port every 12-18 packets; any Kharej works
    [ "$name" = udp ] && [ -n "$p" ] && [ -n "$(bin_ver_ok 3.3.9)" ] \
      && av_add "udp hop" udp d "$(join_hp "$AT_ADDR" "$p")" '' '' '' '' '' '' '' "-udp-hop=$AT_HOP"
  done
  case "$AT_PRESET" in anti) auto_variants_anti "$d" ;; fast) auto_variants_fast "$d" ;; esac
  fi
  if [ -n "$T_SNI" ] && [ "$AT_PRESET" != reverse ]; then
    for c in $AUTO_VAR_CDN; do # h2 never connects through Cloudflare
      p=$(plan_port "$d" "$c"); [ -n "$p" ] || continue
      cf_port_ok "$c" "$p" || continue
      if cdn_ok; then # variant (a): chrome+ech on the best Cloudflare edges (CS_EDGES, filled by auto_test); b-d: cdn_auto_extras
        if [ "${#CS_EDGES[@]}" -gt 0 ]; then av_add "$c · chrome+ech · ${#CS_EDGES[@]} edges" "$c" c "$(cdn_peer_list "$p")" '' "$T_SNI" chrome auto
        else av_add "$c · chrome+ech" "$c" c "$T_SNI:$p" '' "$T_SNI" chrome auto; fi
      else av_add "$c via CDN" "$c" c "$T_SNI:$p" '' "$T_SNI"; fi
    done
  fi
  ipv4_ok "$AT_ADDR" && av_add "icmp reverse" icmp r "$AT_ADDR" '' ''
  for c in ${r//,/ }; do # reverse plan: icmp first, then pool legs (raw carriers have no reverse mode)
    name=${c%%:*}; p=$(plan_entry_port "$c")
    [ "$name" = icmp ] && continue # added above, like the direct icmp row
    [ -n "$p" ] || continue
    carrier_ok_here "$name" || { AT_SKIPPED+="${AT_SKIPPED:+, }$name"; continue; }
    av_add "$name reverse" "$name" r "$(join_hp "$AT_ADDR" "$p")" "$p" ''
  done
  return 0
}
at_free_port() { # [start=20500] [exclude_space_sep] -> free TCP port in 20500..20999
  local p=${1:-20500} excl=${2:-}
  [ "$p" -lt 20500 ] && p=20500
  while [ "$p" -lt 21000 ]; do
    case " $excl " in *" $p "*) p=$((p+1)); continue ;; esac
    if ! port_busy "$p" tcp bind \
       && ! tunnel_using_listen "$p" >/dev/null \
       && ! tunnel_using_public "$p" tcp >/dev/null \
       && ! tunnel_using_misc "$p" >/dev/null; then
      echo "$p"; return 0
    fi
    p=$((p+1))
  done
  return 1
}
at_alive() { [ "$(jget "$(curl -fs --noproxy '*' --max-time 2 "http://127.0.0.1:$1/stats" 2>/dev/null)" alive)" = true ]; }
at_key() { # non-blocking key poll during a test: s skip this variant, g skip this carrier's anti-censor variants, q stop. rc 0 = a key was taken (AT_ACT)
  [ "$AT_KEYS" = 1 ] || return 1
  local k=''
  IFS= read -rsn1 -t 0.05 k 2>/dev/null || return 1
  case "$k" in s|S) AT_ACT=skip ;; g|G) AT_ACT=group ;; q|Q) AT_ACT=stop ;; *) return 1 ;; esac
  return 0
}
at_wait() { # metrics-port seconds : wait for the link
  local end=$((SECONDS + $2))
  while :; do
    at_alive "$1" && return 0
    at_key && return 1
    [ "$SECONDS" -ge "$end" ] && return 1
    kill -0 "$AT_PID" 2>/dev/null || return 1
    sleep 0.5
  done
}
AT_PIDS=(); AT_MPS=()
at_kill() { # the single probe client and every client of the reverse batch
  local p
  if [ -n "$AT_PID" ]; then kill "$AT_PID" 2>/dev/null; { wait "$AT_PID"; } 2>/dev/null; AT_PID=''; fi
  for p in "${AT_PIDS[@]}"; do [ -n "$p" ] && kill "$p" 2>/dev/null; done
  for p in "${AT_PIDS[@]}"; do [ -n "$p" ] && { wait "$p"; } 2>/dev/null; done
  AT_PIDS=(); AT_MPS=()
  return 0
}
at_fw_open() { # port/tcp : temporary rule for a reverse test port (firewalld: runtime only)
  local fw p=$1; fw=$(fw_kind); [ -n "$fw" ] || return 0
  [ "$SANDBOX" = 1 ] && hint "Sandbox: test port $p is opened in $fw if not already allowed, and closed when the test ends."
  if [ "$fw" = ufw ]; then
    ufw status 2>/dev/null | grep -q "^$p[[:space:]]" && return 0
    ufw allow "$p" >/dev/null 2>&1 && AT_FW="$AT_FW $p"
  else
    firewall-cmd -q --query-port="$p" 2>/dev/null && return 0
    firewall-cmd -q --add-port="$p" 2>/dev/null && AT_FW="$AT_FW $p"
  fi
  return 0
}
at_fw_close() {
  local fw p; fw=$(fw_kind); [ -n "$AT_FW" ] && [ -n "$fw" ] || { AT_FW=''; return 0; }
  for p in $AT_FW; do
    if [ "$fw" = ufw ]; then ufw delete allow "$p" >/dev/null 2>&1; else firewall-cmd -q --remove-port="$p" 2>/dev/null; fi
  done
  AT_FW=''; return 0
}
at_cleanup() {
  local p
  [ -n "$AT_STTY" ] && { stty "$AT_STTY" 2>/dev/null; AT_STTY=''; }
  at_kill; at_fw_close
  for p in ${CS_PIDS[@]+"${CS_PIDS[@]}"}; do kill "$p" 2>/dev/null; done
  CS_PIDS=(); [ -n "${CS_DIR:-}" ] && rm -rf "$CS_DIR"; CS_DIR=''
  [ -n "$AT_DIR" ] && rm -rf "$AT_DIR"
  AT_DIR=''; return 0
}
at_start() { # i metrics-port [dummy-map-port] : start a throw-away client for variant i (no -map: nothing is published)
  local i=$1 mp=$2 dmap=${3:-} car=${AV_CAR[$1]} a x c hasws=0 hasicmp=0
  [ -n "$dmap" ] || dmap=$(at_free_port $((mp + 1)) "$mp") || return 1
  a=(-mode client -carrier "$car" -key-file "$AT_DIR/key" -peer "${AV_PEER[$i]}" -metrics "127.0.0.1:$mp")
  # a bond (auto tuning) needs the per-leg overrides of its carrier list too: path and icmp-type apply when any leg does
  for c in ${car//+/ }; do
    case "$c" in ws|wss|h2|h2c|grpc) hasws=1 ;; icmp) hasicmp=1 ;; esac
  done
  [ "$hasws" = 1 ] && a+=(-path "${T_PATH:-/wat}")
  [ "$hasicmp" = 1 ] && [ -n "$T_ICMP" ] && a+=(-icmp-type "$T_ICMP")
  if [ -n "${AV_SNI[$i]}" ]; then a+=(-sni "${AV_SNI[$i]}" -host "${AV_SNI[$i]}"); fi
  if [ -n "${AV_FP[$i]:-}" ]; then a+=(-fp "${AV_FP[$i]}"); fi
  if [ -n "${AV_ECH[$i]:-}" ]; then a+=(-ech "${AV_ECH[$i]}"); fi
  if [ -n "${AV_FRAG[$i]:-}" ] && [ "${AV_FRAG[$i]}" != 0 ]; then a+=(-tls-frag "${AV_FRAG[$i]}"); fi
  if [ -n "${AV_FS[$i]:-}" ]; then # anti-censor matrix variant (2.10.2): desync on the throwaway client
    a+=(-fake-sni "${AV_FS[$i]}")
    [ -n "${AV_FM[$i]:-}" ] && a+=(-fake-mode "${AV_FM[$i]}")
  fi
  if [ -n "${AV_X[$i]:-}" ]; then read -ra x <<<"${AV_X[$i]}"; a+=("${x[@]}"); fi # auto tuning: -key=value words
  # the engine refuses a client without any -map: a loopback-only dummy mapping publishes nothing
  a+=(-map "$dmap:1@127.0.0.1")
  if [ "${AV_KIND[$i]}" = r ]; then
    a+=(-reverse)
    if is_pool "$car"; then a+=(-listen ":${AV_PORT[$i]}"); fi
  fi
  timeout -k 2 "$AT_LIM" "$BIN" "${a[@]}" >"$AT_DIR/client.$i.log" 2>&1 &
  AT_PID=$!
}
at_curl() { # metrics-port dir -> AT_R (no subshell: AT_ACT must survive) ; a skip/stop key kills the transfer (rc 1)
  local cp f=${AT_DIR:-/tmp}/curl.$$
  AT_R=
  curl -fs --noproxy '*' --max-time $((AT_MB * 2 > 20 ? AT_MB * 2 : 20)) "http://127.0.0.1:$1/speedtest?dir=$2&mb=$AT_MB&streams=${AT_STREAMS:-8}" >"$f" 2>/dev/null &
  cp=$!
  if [ "$AT_KEYS" = 1 ]; then
    while kill -0 "$cp" 2>/dev/null; do
      if at_key; then kill "$cp" 2>/dev/null; { wait "$cp"; } 2>/dev/null; rm -f "$f"; return 1; fi
    done
  fi
  { wait "$cp"; } 2>/dev/null; AT_R=$(cat "$f" 2>/dev/null); rm -f "$f"
}
at_probe() { # i wait-seconds : fills AR_*[i]
  local i=$1 w=${2:-8} mp r
  AR_OK[$i]=0; AR_DOWN[$i]=0; AR_UP[$i]=0; AR_RTT[$i]=0; AR_WHY[$i]=''
  [ "$AT_ACT" = stop ] && AT_STOP=1
  AT_ACT=''
  [ "$AT_STOP" = 1 ] && { AR_WHY[$i]=skipped; return 0; }
  case " $AT_SKIP " in *" $(av_key "$i") "*) AR_WHY[$i]='in use by this tunnel'; return 0 ;; esac
  if [ "${AV_KIND[$i]}" = r ] && is_rpool "${AV_CAR[$i]}"; then
    local rp; rp=$(rproto "${AV_CAR[$i]}")
    if listen_blocked "$rp" "${AV_PORT[$i]}"; then
      AR_WHY[$i]="port ${AV_PORT[$i]}/$rp busy ($(listen_conflict_desc "$rp" "${AV_PORT[$i]}"))"; return 0
    fi
    at_fw_open "${AV_PORT[$i]}/$rp"
  fi
  mp=$(at_free_port) || { AR_WHY[$i]='no free test port'; return 0; }
  AT_LIM=$((w + 55 + AT_MB * 4))
  at_start "$i" "$mp" || { AR_WHY[$i]='no free test port'; return 0; }
  if ! at_wait "$mp" "$w"; then
    AR_WHY[$i]="no link in $w s"
    [ -n "$AT_ACT" ] && AR_WHY[$i]=skipped
  else
    [ "${AV_KIND[$i]}" = r ] || AT_DLINK=$((AT_DLINK+1))
    at_measure "$i" "$mp"
  fi
  at_kill; at_fw_close
  return 0
}
at_measure() { # i metrics-port : speed test on a running client, fills AR_*[i]
  local i=$1 mp=$2 r
  AR_OK[$i]=0; AR_DOWN[$i]=0; AR_UP[$i]=0; AR_RTT[$i]=0; AR_WHY[$i]=''
  at_curl "$mp" down; r=$AT_R
  if [ "$(jget "$r" ok)" = true ]; then
    AR_DOWN[$i]=$(jget "$r" mb_per_s)
    at_curl "$mp" up; r=$AT_R
    if [ "$(jget "$r" ok)" = true ]; then
      AR_UP[$i]=$(jget "$r" mb_per_s)
      AR_RTT[$i]=$(jget_flat "$(curl -fs --noproxy '*' --max-time 2 "http://127.0.0.1:$mp/stats" 2>/dev/null)" rtt_ms srtt_ms)
      : "${AR_DOWN[$i]:=0}" "${AR_UP[$i]:=0}" "${AR_RTT[$i]:=0}"
      AR_OK[$i]=1
    fi
  fi
  [ "${AR_OK[$i]}" = 1 ] || AR_WHY[$i]='speed test failed/stalled'
  [ -n "$AT_ACT" ] && { AR_OK[$i]=0; AR_WHY[$i]=skipped; }
  return 0
}
# Reverse pool carriers: Kharej's NAME-r companion starts dialing Iran's r-ports as soon as it knows Iran's IP, and its
# redial backoff grows while nothing listens. So all reverse clients (and their temporary firewall rules) are started at
# once, we wait for all of them together, then the speed tests run one at a time on the already-running clients.
at_pool_batch() { # indices... : probe every reverse pool variant given
  local i mp dmap base=20500 used_test='' end pend ks=0 started=() up=()
  for i in "$@"; do
    AR_OK[$i]=0; AR_DOWN[$i]=0; AR_UP[$i]=0; AR_RTT[$i]=0; AR_WHY[$i]=''
    case " $AT_SKIP " in *" $(av_key "$i") "*) AR_WHY[$i]='in use by this tunnel'; continue ;; esac
    local rp; rp=$(rproto "${AV_CAR[$i]}")
    if listen_blocked "$rp" "${AV_PORT[$i]}"; then AR_WHY[$i]="port ${AV_PORT[$i]}/$rp busy ($(listen_conflict_desc "$rp" "${AV_PORT[$i]}"))"; continue; fi
    at_fw_open "${AV_PORT[$i]}/$rp"
  done
  AT_LIM=$((45 + $# * (50 + AT_MB * 4) + 30))
  for i in "$@"; do
    [ -z "${AR_WHY[$i]}" ] || continue
    mp=$(at_free_port "$base" "$used_test") || { AR_WHY[$i]='no free test port'; continue; }
    used_test+=" $mp"
    dmap=$(at_free_port $((mp + 1)) "$used_test") || { AR_WHY[$i]='no free test port'; continue; }
    used_test+=" $dmap"
    base=$((dmap + 1))
    at_start "$i" "$mp" "$dmap" || { AR_WHY[$i]='no free test port'; continue; }
    AT_PIDS[$i]=$AT_PID; AT_PID=''; AT_MPS[$i]=$mp
    started+=("$i")
  done
  if [ "${#started[@]}" -gt 0 ]; then
    [ "$AT_QUIET" = 1 ] || at_busy "reverse links (all at once, up to 45 s)"
    end=$((SECONDS + 45)); ks=0
    while :; do
      if at_key; then [ "$AT_ACT" = stop ] && AT_STOP=1; AT_ACT=''; ks=1; break; fi
      pend=0
      for i in "${started[@]}"; do
        [ "${up[$i]:-0}" = 1 ] && continue
        if at_alive "${AT_MPS[$i]}"; then up[$i]=1
        elif kill -0 "${AT_PIDS[$i]}" 2>/dev/null; then pend=1; fi
      done
      [ "$pend" = 0 ] && break
      [ "$SECONDS" -ge "$end" ] && break
      sleep 0.5
    done
    [ "$AT_QUIET" = 1 ] || at_idle
  fi
  for i in "$@"; do
    if [ -z "${AR_WHY[$i]}" ]; then
      if [ "$AT_STOP" = 1 ]; then AR_WHY[$i]=skipped
      elif [ "${up[$i]:-0}" = 1 ]; then
        [ "$AT_QUIET" = 1 ] || at_busy "${AV_LABEL[$i]}"
        at_measure "$i" "${AT_MPS[$i]}"
        [ "$AT_QUIET" = 1 ] || at_idle
        [ "$AT_ACT" = stop ] && AT_STOP=1
        AT_ACT=''
      elif [ "$ks" = 1 ]; then AR_WHY[$i]=skipped
      else AR_WHY[$i]='no link in 45 s'; fi
    fi
    [ "$AT_QUIET" = 1 ] || at_print "$i"
  done
  at_kill; at_fw_close
  return 0
}
AT_IDX=0; AT_TOTAL=0; AT_PEAK=10; AT_MOVED_MB=0
at_lbl() { # text max -> truncated with .. when longer than max
  local s=$1 m=${2:-24}
  if [ "${#s}" -gt "$m" ]; then printf '%s..' "${s:0:$((m-2))}"; else printf '%s' "$s"; fi
}
at_peak_update() { # indices... -> updates AT_PEAK (floor 10)
  local i m
  for i in "$@"; do
    [ "${AR_OK[$i]:-0}" = 1 ] || continue
    m=$(awk -v a="${AR_DOWN[$i]:-0}" -v b="${AR_UP[$i]:-0}" -v p="$AT_PEAK" 'BEGIN{m=(a>b)?a:b; print (m>p)?m:p}')
    AT_PEAK=$m
  done
}
at_busy() {
  local lbl=$1
  if [ "$ANIM" = 1 ]; then
    if [ "${AT_TOTAL:-0}" -gt 0 ]; then
      cur_hide
      (
        local i=0 t0=$SECONDS el cols ts bar_s tag
        cols=$(term_cols)
        tag=$(printf '[%2d/%-2d] ' "$AT_IDX" "$AT_TOTAL")
        while :; do
          el=$((SECONDS - t0))
          ts=''; [ "$el" -ge 1 ] && ts=" ${GRY}· ${el}s${RST}"
          bar_s=''; [ "$cols" -ge 72 ] && bar_s="  $(bar "$AT_IDX" "$AT_TOTAL" 14)"
          printf '\r\e[K  %s%s%s %s%-24s%s%s' "$CYN" "${SPIN_FR[$i]}" "$RST" "$tag" "$(at_lbl "$lbl" 24)" "$ts" "$bar_s"
          i=$(( (i + 1) % 10 )); sleep 0.1
        done
      ) &
      SPIN_PID=$!
    else
      spin_start "Testing $lbl"
    fi
  elif [ "$NONINTERACTIVE" = 1 ]; then
    printf '  testing %s ...\n' "$lbl"
  elif [ "$IS_TTY" = 1 ]; then
    if [ "${AT_TOTAL:-0}" -gt 0 ]; then printf '  [%d/%d] Testing %s ...' "$AT_IDX" "$AT_TOTAL" "$lbl"
    else printf '  testing %s ...' "$lbl"; fi
  fi
  return 0
}
at_idle() { if [ "$ANIM" = 1 ]; then spin_stop; elif [ "$IS_TTY" = 1 ]; then printf '\r\e[K'; fi; return 0; }
at_print() {
  local i=$1 cols pk
  at_peak_update "$i"
  if [ "${AR_OK[$i]}" = 1 ]; then
    if [ "$NONINTERACTIVE" = 1 ]; then
      printf '  ✔ %-28s %6.1f MB/s down  %6.1f MB/s up  %4.0f ms\n' "${AV_LABEL[$i]}" "${AR_DOWN[$i]:-0}" "${AR_UP[$i]:-0}" "${AR_RTT[$i]:-0}"
    else
      cols=$(term_cols)
      pk=$(awk -v a="${AR_DOWN[$i]:-0}" -v b="${AR_UP[$i]:-0}" 'BEGIN{print (a>b)?a:b}')
      if [ "$cols" -ge 76 ]; then
        printf '  %s✔%s %-24s %s%6.1f%s ↓  %6.1f ↑  %4.0f ms  %s\n' \
          "$GRN" "$RST" "$(at_lbl "${AV_LABEL[$i]}" 24)" "$BOLD" "${AR_DOWN[$i]:-0}" "$RST" "${AR_UP[$i]:-0}" "${AR_RTT[$i]:-0}" "$(tbar "$pk" "$AT_PEAK" 10)"
      else
        printf '  %s✔%s %-20s %s%6.1f%s↓ %6.1f↑ %4.0fms\n' \
          "$GRN" "$RST" "$(at_lbl "${AV_LABEL[$i]}" 20)" "$BOLD" "${AR_DOWN[$i]:-0}" "$RST" "${AR_UP[$i]:-0}" "${AR_RTT[$i]:-0}"
      fi
    fi
  else
    printf '  %s✘%s %-24s %s%s%s\n' "$RED" "$RST" "$(at_lbl "${AV_LABEL[$i]}" 24)" "$GRY" "${AR_WHY[$i]}" "$RST"
  fi
}
AT_NOTE=''
auto_refine() { # AT_RANK from the screening -> re-measure the top 3 with 16 streams and a sustained run, re-rank
  # H3: slow start dominates a short transfer, so a finalist is sized by the duration floor, not a fixed MB: >=1.5 s
  # each way at its screening rate, clamped to 20-40 MB (the 40 MB cap keeps the worst case inside at_budget's number;
  # a variant that fails keeps its screening numbers).
  local i k=0 top=() pool=() save=$AT_MB save_streams=$AT_STREAMS w ok d u r t0=$SECONDS mb mb_pool=0 refined=0 rate
  local -A sv=()
  [ "${#AT_RANK[@]}" -gt 0 ] || return 0
  for i in "${AT_RANK[@]}"; do [ "$k" -ge 3 ] && break; top+=("$i"); k=$((k+1)); sv[$i]="${AR_OK[$i]}|${AR_DOWN[$i]}|${AR_UP[$i]}|${AR_RTT[$i]}"; done
  at_prep || return 0
  AT_STREAMS=16
  AT_IDX=0; AT_TOTAL=${#top[@]}
  [ "$AT_QUIET" = 1 ] || sec_hdr "Confirming top ${#top[@]}" "16 streams"
  for i in "${top[@]}"; do
    AT_IDX=$((AT_IDX+1))
    IFS='|' read -r ok d u r <<<"${sv[$i]}"
    rate=$(awk -v a="${d:-0}" -v b="${u:-0}" 'BEGIN{print (a>b)?a:b}')
    mb=$(at_probe_mb "$rate" 1.5 "$AT_FINAL_MB_MAX")
    [ "$mb" -lt "$AT_FINAL_MB_MIN" ] && mb=$AT_FINAL_MB_MIN
    if [ -n "${AT_TUNNEL:-}" ] && { [ "$(av_key "$i")" = bond/r ] || [[ " $AT_SKIP " == *" $(av_key "$i") "* ]]; }; then
      local lmp; lmp=$(cfg "$AT_TUNNEL" metrics); lmp=${lmp##*:}
      if [[ "$lmp" =~ ^[0-9]+$ ]]; then
        AT_MB=$mb; refined=$((refined + 2 * mb))
        [ "$AT_QUIET" = 1 ] || at_busy "${AV_LABEL[$i]} (live)"
        at_measure "$i" "$lmp"
        [ "$AT_QUIET" = 1 ] || { at_idle; at_print "$i"; }
        continue
      fi
    fi
    [ "${AV_KIND[$i]}" = r ] && is_pool "${AV_CAR[$i]}" && { pool+=("$i"); [ "$mb" -gt "$mb_pool" ] && mb_pool=$mb; continue; }
    w=8; [ "${AV_KIND[$i]}" = r ] && [ "${AV_CAR[$i]}" = icmp ] && w=30
    AT_MB=$mb; refined=$((refined + 2 * mb))
    [ "$AT_QUIET" = 1 ] || at_busy "${AV_LABEL[$i]}"
    at_probe "$i" "$w"
    [ "$AT_QUIET" = 1 ] || { at_idle; at_print "$i"; }
  done
  if [ "${#pool[@]}" -gt 0 ]; then
    [ "$mb_pool" -lt 20 ] && mb_pool=20
    AT_MB=$mb_pool; refined=$((refined + ${#pool[@]} * 2 * mb_pool))
    at_pool_batch "${pool[@]}"
  fi
  at_cleanup
  AT_IDX=0; AT_TOTAL=0
  AT_MB=$save; AT_STREAMS=$save_streams
  for i in "${top[@]}"; do # a variant that fails the longer test keeps its screening numbers
    [ "${AR_OK[$i]}" = 1 ] && continue
    IFS='|' read -r ok d u r <<<"${sv[$i]}"; AR_OK[$i]=$ok; AR_DOWN[$i]=$d; AR_UP[$i]=$u; AR_RTT[$i]=$r
  done
  AT_SECS=$((AT_SECS + SECONDS - t0))
  AT_MOVED_MB=$((AT_MOVED_MB + refined))
  AT_NOTE="${AT_MOVED_MB} MB moved"
  [ -n "$AT_PLAN" ] && AT_PLAN=$(at_budget "${#AV_LABEL[@]}" "$AT_SCREEN_CAP_MB" "$AT_FINAL_MB_MAX" "$AT_TUNE_PROBES_MAX" "$AT_TUNE_PROBE_MB")
  at_rank
  return 0
}
# Auto tuning: once the type is chosen, try the settings that actually moved speed in the field, one setting at a time,
# each value against the best so far. A value is kept only when it beats that by 10 % (one run is noisy), so a setting
# stays at the engine's auto value unless another value is clearly faster on this route. Measured on one 2 vCPU pair
# (2026-11-03): tcp sessions 1/2/4/8 gave 176/261/147/68 MB/s down, so no one value fits every route.
# D8 (3.3.0 audit): probes are fixed at AT_TUNE_PROBE_MB each way and the grid is sessions+conns only. mtu/win-max/batch/
# loss-ceiling were removed from tuning because their effect was inside the run-to-run noise; max-mbps and fec stay
# untuned (icmp keeps its 16 MB/s reroute guard; -fec auto needs the same setting on Kharej). A bond tests conns only:
# the engine refuses -sessions on any bond.
AUTO_TUNE_ICMP=''                       # no sessions/conns to tune on a raw-IP carrier
AUTO_TUNE_UDP='sessions:1,2,4'
AUTO_TUNE_POOL='sessions:1,2,4,8,16 conns:4,8,32,64'
AUTO_TUNE_REVERSE='conns:4,8,32'        # -sessions is refused in reverse mode
AUTO_TUNE_BOND_DGRAM='conns:4,8,32,64'
AUTO_TUNE_BOND_POOL='conns:4,8,32,64'
at_tune_knobs() { # carrier|bond|reverse -> "key:value,value ..." in test order (the data above)
  case "$1" in
    icmp) echo "$AUTO_TUNE_ICMP" ;;
    udp) echo "$AUTO_TUNE_UDP" ;;
    bond) if has_dgram "${T_CARRIER:-}"; then echo "$AUTO_TUNE_BOND_DGRAM"; else echo "$AUTO_TUNE_BOND_POOL"; fi ;;
    reverse) echo "$AUTO_TUNE_REVERSE" ;;
    tcp|tls|ws|wss|h2|h2c|grpc) echo "$AUTO_TUNE_POOL" ;;
  esac
}
AT_TUNE_PROBES_MAX=$(at_tune_probe_count "$AUTO_TUNE_POOL") # the widest reduced grid, used by at_budget (H2)
at_tune_knobs_avail() { printf '%s' "$(at_tune_knobs "$1")"; } # every remaining knob (sessions/conns) exists on every supported engine
AT_TUNE=''; AT_TUNE_KEYS=''
at_tune_bond_variant() { # AT_SEL (2+ direct or 2+ reverse variants) -> one AV entry that probes the whole selected bond; sets AT_TUNE_BASE
  local i c peers='' first='' sni='' fp='' ech='' frag=''
  if [ "${AV_KIND[${AT_SEL[0]}]}" = r ]; then
    for i in "${AT_SEL[@]}"; do
      c=${AV_CAR[$i]}
      [ -n "${AV_PORT[$i]}" ] && peers="${peers:+$peers }-listen-$c :${AV_PORT[$i]}"
    done
    av_add "reverse bond ${T_CARRIER:-}" "${T_CARRIER:-}" r "$AT_ADDR" '' '' '' '' '' '' '' "$peers"
    AT_TUNE_BASE=$((${#AV_LABEL[@]} - 1))
    return 0
  fi
  for i in "${AT_SEL[@]}"; do
    c=${AV_CAR[$i]}
    if [ "$c" = icmp ]; then peers="${peers:+$peers }-peer-icmp ${AV_PEER[$i]}"
    else peers="${peers:+$peers }-peer-$c ${AV_PEER[$i]}"; fi
    [ -n "$first" ] || first=${AV_PEER[$i]}
    if [ "${AV_KIND[$i]}" = c ]; then
      [ -n "$sni" ] || sni=${AV_SNI[$i]}; [ -n "$fp" ] || fp=${AV_FP[$i]}
      [ -n "$ech" ] || ech=${AV_ECH[$i]}; [ -n "$frag" ] || frag=${AV_FRAG[$i]}
    fi
  done
  [ -n "$sni" ] || sni=$T_SNI
  av_add "bond ${T_CARRIER:-}" "${T_CARRIER:-}" d "$first" '' "$sni" "$fp" "$ech" "$frag" '' '' "$peers"
  AT_TUNE_BASE=$((${#AV_LABEL[@]} - 1))
}
at_tune() { # AT_SEL -> AT_TUNE (config lines) and AT_TUNE_KEYS (the settings it tested).
  local target kind knobs kv k v best bs s i x='' save=$AT_MB w=8 rfw=''
  AT_TUNE=''; AT_TUNE_KEYS=''; AT_TUNE_MB=0
  [ "${#AT_SEL[@]}" -ge 1 ] || return 0
  if [ "${#AT_SEL[@]}" -eq 1 ]; then
    target=${AT_SEL[0]}
    if [ "${AV_KIND[$target]}" = r ]; then kind=reverse; else kind=${AV_CAR[$target]}; fi
  elif [ "${AV_KIND[${AT_SEL[0]}]}" = r ]; then
    kind=reverse; target=''
  else
    kind=bond; target=''
  fi
  knobs=$(at_tune_knobs_avail "$kind"); [ -n "$knobs" ] || return 0
  if [ "$kind" = reverse ] && [ -n "${AT_TUNNEL:-}" ]; then
    for i in "${AT_SEL[@]}"; do
      if { [ -n "${AV_PORT[$i]}" ] && [ "$(tunnel_using_listen "${AV_PORT[$i]}")" = "$AT_TUNNEL" ]; } \
         || { [ "${AV_CAR[$i]}" = icmp ] && is_reverse "$AT_TUNNEL" && [[ "+$(cfg "$AT_TUNNEL" carrier)+" == *+icmp+* ]]; }; then
        [ "$AT_QUIET" = 1 ] || hint "Keeping engine auto values (reverse port is held by '$AT_TUNNEL' until switch)."
        return 0
      fi
    done
  fi
  at_prep || return 0
  # AT_SKIP only skips the live variant during the screening; tuning must measure that very variant as its baseline
  AT_SKIP=''
  if [ -z "$target" ]; then
    at_tune_bond_variant; target=$AT_TUNE_BASE
    if [ "$kind" = reverse ]; then
      for i in "${AT_SEL[@]}"; do [ -n "${AV_PORT[$i]}" ] && at_fw_open "${AV_PORT[$i]}/$(rproto "${AV_CAR[$i]}")"; done
      rfw=$AT_FW; AT_FW='' # hold reverse bond ports open across all tuning probes; closed at cleanup below
    fi
  fi
  # D8: a fixed 20 MB each way per probe (the budget's number), not a size derived from the screening rate: the tuning
  # grid is short and its values are compared against each other, so every probe must cost the same.
  AT_MB=$AT_TUNE_PROBE_MB
  AT_STOP=0; AT_ACT=''; AT_IDX=0; AT_TOTAL=$(at_tune_probe_count "$knobs")
  [ "$kind" = reverse ] && w=45 # Kharej reverse dialer backoff is up to 30 s; match at_pool_batch
  [ "$AT_QUIET" = 1 ] || sec_hdr "Tuning ${AV_LABEL[$target]}" "$AT_MB MB/probe"
  at_tune_try() { # flags label -> i (the new variant) ; prints its row
    local extra="${AV_X[$target]:+${AV_X[$target]}}"
    AT_IDX=$((AT_IDX+1))
    [ -n "$1" ] && extra="${extra:+$extra }$1"
    av_add "$2" "${AV_CAR[$target]}" "${AV_KIND[$target]}" "${AV_PEER[$target]}" "${AV_PORT[$target]}" "${AV_SNI[$target]}" \
      "${AV_FP[$target]}" "${AV_ECH[$target]}" "${AV_FRAG[$target]}" "${AV_FS[$target]}" "${AV_FM[$target]}" "$extra"
    i=$((${#AV_LABEL[@]} - 1))
    [ "$AT_QUIET" = 1 ] || at_busy "$2"
    at_probe "$i" "$w"
    [ "$AT_QUIET" = 1 ] || { at_idle; at_print "$i"; }
  }
  [ "$AT_QUIET" = 1 ] || sec_hdr "Tuning"
  at_tune_try '' 'baseline (auto)'
  AT_TUNE_MB=$((AT_TUNE_MB + 2 * AT_MB))
  bs=0; [ "${AR_OK[$i]}" = 1 ] && bs=$(at_score "$i")
  if [ "$bs" = 0 ]; then # no baseline, no comparison: do not apply a value that was never measured against it
    [ "$AT_QUIET" = 1 ] || warn "Baseline did not come up — keeping engine auto values"
    AT_FW="$AT_FW $rfw"; at_cleanup; AT_IDX=0; AT_TOTAL=0; AT_MB=$save; return 0
  fi
  for kv in $knobs; do
    k=${kv%%:*}
    case "$k" in # a value given on the command line (--sessions, --conns) wins
      sessions) [ -n "$NI_SESSIONS" ] && continue ;;
      conns) [ -n "${NI_CONNS:-}" ] && continue ;;
    esac
    AT_TUNE_KEYS+=" $k"; best=''
    for v in $(tr ',' ' ' <<<"${kv#*:}"); do
      at_tune_try "${x:+$x }-$k=$v" "$k $v"
      AT_TUNE_MB=$((AT_TUNE_MB + 2 * AT_MB))
      [ "${AR_OK[$i]}" = 1 ] || continue
      s=$(at_score "$i")
      if awk -v s="$s" -v b="$bs" 'BEGIN{exit !(s > b * 1.1)}'; then bs=$s; best=$v; fi
    done
    if [ -n "$best" ]; then x="${x:+$x }-$k=$best"; AT_TUNE+="$k: $best"$'\n'; fi
  done
  AT_FW="$AT_FW $rfw"; at_cleanup
  AT_IDX=0; AT_TOTAL=0
  AT_MB=$save
  AT_TUNE=${AT_TUNE%$'\n'}
  if [ "$AT_QUIET" != 1 ]; then
    if [ -n "$AT_TUNE" ]; then ok "Tuned: $(tr '\n' ',' <<<"$AT_TUNE" | sed 's/,$//; s/,/, /g')${AT_TUNE_MB:+  (${AT_TUNE_MB} MB)}"
    else ok "Engine auto values are fastest${AT_TUNE_MB:+  (${AT_TUNE_MB} MB)}"; fi
  fi
  return 0
}
at_tune_extra() { [ -n "$AT_TUNE" ] && AT_EXTRA+="${AT_EXTRA:+$'\n'}$AT_TUNE"; return 0; } # after at_to_t: the tuned lines go into the config with the rest
auto_test() { # needs read_token of an auto token (T_*); sets AT_QUIET, AT_MB, AT_SKIP; fills AR_*, AT_SECS, AT_PLAN
  local i n t0=$SECONDS kind last='' w pool=() j sc best_rate
  at_prep || return 1
  AR_OK=(); AR_DOWN=(); AR_UP=(); AR_RTT=(); AR_WHY=()
  CS_EDGES=(); CS_TOTAL=0; CS_RAN=0; AT_TUNE=''; AT_TUNE_KEYS=''
  if [ -n "$T_SNI" ] && cdn_ok; then # one scan for all CDN carriers with a Cloudflare-proxyable port
    j=''; sc=''; for i in $AUTO_VAR_CDN; do
      j=$(plan_port "$(plan_part "$T_AUTO" d)" "$i")
      if [ -n "$j" ] && cf_port_ok "$i" "$j"; then sc=$i; break; fi
      j=''
    done
    if [ -n "$j" ]; then
      [ "$AT_QUIET" = 1 ] || at_busy "Cloudflare edges"
      CS_QUIET=1; cdn_scan "$T_SNI" "$j" "${T_PATH:-/wat}" "$sc"
      [ "$AT_QUIET" = 1 ] || at_idle
    fi
  fi
  auto_variants
  n=${#AV_LABEL[@]}; AT_DLINK=0; AT_STOP=0; AT_GSKIP=''; AT_ACT=''
  AT_IDX=0; AT_TOTAL=$n; AT_PEAK=10; AT_MOVED_MB=0
  # B2: a token from a newer Kharej can name carriers this engine cannot run. They are skipped (never written into a
  # config) and one hint explains why; they are not in the variant count, so at_budget stays truthful.
  [ -n "$AT_SKIPPED" ] && warn "Skipped (needs newer wattun): $AT_SKIPPED"
  AT_PLAN=$(at_budget "$n" "$AT_SCREEN_CAP_MB" "$AT_FINAL_MB_MAX" "$AT_TUNE_PROBES_MAX" "$AT_TUNE_PROBE_MB")
  AT_MB=$AT_SCREEN_MB_START; best_rate=0 # H3: screening starts at 8 MB and grows only if the measured rate says it is short
  AT_KEYS=0; [ "$IS_TTY" = 1 ] && [ "$AT_QUIET" != 1 ] && [ -t 0 ] && AT_KEYS=1
  if [ "$AT_KEYS" = 1 ]; then
    AT_STTY=$(stty -g 2>/dev/null); stty -echo 2>/dev/null # typed s/g/q must not print between polls; at_cleanup restores
    while IFS= read -rsn1 -t 0.01 _; do :; done # drop keys typed before the test
    if [ "$AT_PRESET" = anti ]; then hint "Keys: [s] skip  [g] skip group  [q] stop"
    else hint "Keys: [s] skip  [q] stop"; fi
  fi
  for ((i=0; i<n; i++)); do
    kind=${AV_KIND[$i]}
    if [ "$AT_STOP" = 1 ]; then at_truncate "$i"; break; fi
    if av_anti "$i" && [ -n "$AT_GSKIP" ] && [ "${AV_CAR[$i]}" = "$AT_GSKIP" ]; then
      AR_OK[$i]=0; AR_DOWN[$i]=0; AR_UP[$i]=0; AR_RTT[$i]=0; AR_WHY[$i]=skipped; continue
    fi
    if av_anti "$i" && [ "$last" != anti ] && [ "$AT_QUIET" != 1 ]; then sec_hdr "Anti-censor" "desync / fp / frag"; last=anti; fi
    if [ "$kind" != "$last" ] && [ "$last" != anti ] && [ "$AT_QUIET" != 1 ]; then
      case "$kind" in
        d) sec_hdr "Direct" ;;
        c) sec_hdr "CDN" "$T_SNI"; [ "$CS_RAN" = 1 ] && cdn_scan_say ;;
        r) sec_hdr "Reverse" ;;
      esac
    fi
    av_anti "$i" || last=$kind
    if [ "$kind" = r ] && is_pool "${AV_CAR[$i]}"; then
      pool=(); for ((j=i; j<n; j++)); do [ "${AV_KIND[$j]}" = r ] && is_pool "${AV_CAR[$j]}" && pool+=("$j"); done
      AT_IDX=$((i+1))
      AT_MB=$(at_probe_mb "$best_rate" 1.5 "$AT_SCREEN_CAP_MB")
      at_pool_batch "${pool[@]}"
      best_rate=$(at_best_rate "$best_rate" "${pool[@]}")
      break
    fi
    AT_IDX=$((i+1))
    w=8; [ "$kind" = r ] && [ "${AV_CAR[$i]}" = icmp ] && w=30 # Kharej's companion needs a few seconds to start
    AT_MB=$(at_probe_mb "$best_rate" 1.5 "$AT_SCREEN_CAP_MB") # H3: duration-based size, 8 -> x4 while under 1.5 s
    [ "$AT_QUIET" = 1 ] || at_busy "${AV_LABEL[$i]}"
    at_probe "$i" "$w"
    [ "${AR_OK[$i]}" = 1 ] && AT_MOVED_MB=$((AT_MOVED_MB + 2 * AT_MB))
    best_rate=$(at_best_rate "$best_rate" "$i")
    [ "$AT_QUIET" = 1 ] || { at_idle; [ "${AR_WHY[$i]}" = skipped ] && printf '  %s-%s %-24s %sskipped%s\n' "$GRY" "$RST" "$(at_lbl "${AV_LABEL[$i]}" 24)" "$GRY" "$RST" || at_print "$i"; }
    case "$AT_ACT" in group) av_anti "$i" && AT_GSKIP=${AV_CAR[$i]} ;; stop) AT_STOP=1; AR_WHY[$i]=skipped ;; esac
    AT_ACT=''
    if [ "$kind" = c ] && cdn_ok && [ "${AV_KIND[$((i+1))]:-}" != c ]; then cdn_auto_extras; fi
  done
  AT_KEYS=0; AT_IDX=0; AT_TOTAL=0
  at_cleanup
  AT_SECS=$((SECONDS-t0))
  return 0
}
at_truncate() { # k : keep only the first k variants (the test was stopped before the rest)
  local k=$1
  AV_LABEL=("${AV_LABEL[@]:0:$k}"); AV_CAR=("${AV_CAR[@]:0:$k}"); AV_KIND=("${AV_KIND[@]:0:$k}"); AV_PEER=("${AV_PEER[@]:0:$k}")
  AV_PORT=("${AV_PORT[@]:0:$k}"); AV_SNI=("${AV_SNI[@]:0:$k}"); AV_FP=("${AV_FP[@]:0:$k}"); AV_ECH=("${AV_ECH[@]:0:$k}")
  AV_FRAG=("${AV_FRAG[@]:0:$k}"); AV_FS=("${AV_FS[@]:0:$k}"); AV_FM=("${AV_FM[@]:0:$k}"); AV_X=("${AV_X[@]:0:$k}")
  AR_OK=("${AR_OK[@]:0:$k}"); AR_DOWN=("${AR_DOWN[@]:0:$k}"); AR_UP=("${AR_UP[@]:0:$k}"); AR_RTT=("${AR_RTT[@]:0:$k}"); AR_WHY=("${AR_WHY[@]:0:$k}")
}
at_rank() { # [policy] -> AT_RANK (working variants, best first: policy driven)
  local pol=${1:-${NI_POLICY:-}} i
  if [ -z "$pol" ] && [ -n "${AT_TUNNEL:-}" ] && [ -f "$CONF/$AT_TUNNEL.policy" ]; then
    pol=$(cat "$CONF/$AT_TUNNEL.policy" 2>/dev/null || echo speed)
  fi
  : "${pol:=speed}"
  AT_RANK=()
  case "$pol" in
    latency)
      while read -r _ _ i; do [ -n "$i" ] && AT_RANK+=("$i"); done < <(
        for ((i=0; i<${#AV_LABEL[@]}; i++)); do
          [ "${AR_OK[$i]}" = 1 ] && awk -v d="${AR_DOWN[$i]:-0}" -v u="${AR_UP[$i]:-0}" -v r="${AR_RTT[$i]:-0}" -v i="$i" 'BEGIN{printf "%.3f %.6f %d\n", r, d+u, i}'
        done | sort -k1,1g -k2,2gr)
      ;;
    direct)
      while read -r _ _ _ i; do [ -n "$i" ] && AT_RANK+=("$i"); done < <(
        for ((i=0; i<${#AV_LABEL[@]}; i++)); do
          local dir_p=0
          case "${AV_CAR[$i]}" in tcp|tls|udp|icmp) [ "${AV_KIND[$i]}" = d ] && dir_p=1 ;; esac
          [ "${AR_OK[$i]}" = 1 ] && awk -v dp="$dir_p" -v d="${AR_DOWN[$i]:-0}" -v u="${AR_UP[$i]:-0}" -v r="${AR_RTT[$i]:-0}" -v i="$i" 'BEGIN{printf "%d %.6f %.3f %d\n", dp, d+u, r, i}'
        done | sort -k1,1nr -k2,2gr -k3,3g)
      ;;
    bond|speed|*)
      while read -r _ _ i; do [ -n "$i" ] && AT_RANK+=("$i"); done < <(
        for ((i=0; i<${#AV_LABEL[@]}; i++)); do
          # an anti-censor variant must beat the plain type by 8 % to rank above it (noise, plus its startup cost)
          [ "${AR_OK[$i]}" = 1 ] && awk -v pen="$(av_anti "$i" && echo 0.92 || echo 1)" -v d="${AR_DOWN[$i]:-0}" -v u="${AR_UP[$i]:-0}" -v r="${AR_RTT[$i]:-0}" -v i="$i" 'BEGIN{printf "%.6f %.3f %d\n", (d+u)*pen, r, i}'
        done | sort -k1,1gr -k2,2g)
      ;;
  esac
}
at_table() {
  local i k=0 pk hdr title has_fail=0 bar_s star
  AT_PEAK=10
  for i in "${AT_RANK[@]}"; do at_peak_update "$i"; done
  if [ "$NONINTERACTIVE" = 1 ]; then
    echo
    printf '  %3s  %-28s %12s %12s %7s\n' '#' variant down up rtt
    for i in "${AT_RANK[@]}"; do
      k=$((k+1))
      printf '  %3s  %-28s %7.1f MB/s %7.1f MB/s %4.0f ms\n' "$k" "${AV_LABEL[$i]}" "${AR_DOWN[$i]:-0}" "${AR_UP[$i]:-0}" "${AR_RTT[$i]:-0}"
    done
    for ((i=0; i<${#AV_LABEL[@]}; i++)); do
      [ "${AR_OK[$i]}" = 1 ] || [ "${AR_WHY[$i]}" = skipped ] || printf '    ✘  %-28s %s\n' "${AV_LABEL[$i]}" "${AR_WHY[$i]}"
    done
    hint "${AT_NOTE:-${AT_MB} MB/probe} · ${AT_SECS} s"
    return 0
  fi
  [ "${UI_W:-0}" -gt 0 ] || ui_init_width
  echo
  title="Results · ${#AT_RANK[@]} working${AT_SECS:+ · ${AT_SECS} s}"
  [ "${AT_MOVED_MB:-0}" -gt 0 ] && title="Results · ${#AT_RANK[@]} working · ${AT_MOVED_MB} MB · ${AT_SECS} s"
  box_top "$title"
  if [ "${#AT_RANK[@]}" -gt 0 ]; then
    if [ "$BOXW" -ge 66 ]; then
      printf -v hdr '%s %2s  %-22s %6s %6s %6s  %-10s%s' "$GRY" '#' 'Carrier' 'Down' 'Up' 'RTT' 'Speed' "$RST"
    else
      printf -v hdr '%s %2s  %-18s %6s %6s %6s%s' "$GRY" '#' 'Carrier' 'Down' 'Up' 'RTT' "$RST"
    fi
    box_row "$hdr"
    for i in "${AT_RANK[@]}"; do
      k=$((k+1))
      pk=$(awk -v a="${AR_DOWN[$i]:-0}" -v b="${AR_UP[$i]:-0}" 'BEGIN{print (a>b)?a:b}')
      if [ "$BOXW" -ge 66 ]; then
        bar_s="  $(tbar "$pk" "$AT_PEAK" 10)"
        if [ "$k" -eq 1 ]; then
          star="  ${CYN}★${RST}"
          box_row "${BOLD}${CYN}▸$(printf '%2d  %-22s %6.1f %6.1f %4.0fms' "$k" "$(at_lbl "${AV_LABEL[$i]}" 22)" "${AR_DOWN[$i]:-0}" "${AR_UP[$i]:-0}" "${AR_RTT[$i]:-0}")${RST}${bar_s}${star}"
        else
          box_row " $(printf '%2d  %-22s %6.1f %6.1f %4.0fms' "$k" "$(at_lbl "${AV_LABEL[$i]}" 22)" "${AR_DOWN[$i]:-0}" "${AR_UP[$i]:-0}" "${AR_RTT[$i]:-0}")${bar_s}"
        fi
      else
        if [ "$k" -eq 1 ]; then
          box_row "${BOLD}${CYN}▸$(printf '%2d  %-18s %6.1f %6.1f %4.0fms ★' "$k" "$(at_lbl "${AV_LABEL[$i]}" 18)" "${AR_DOWN[$i]:-0}" "${AR_UP[$i]:-0}" "${AR_RTT[$i]:-0}")${RST}"
        else
          box_row " $(printf '%2d  %-18s %6.1f %6.1f %4.0fms' "$k" "$(at_lbl "${AV_LABEL[$i]}" 18)" "${AR_DOWN[$i]:-0}" "${AR_UP[$i]:-0}" "${AR_RTT[$i]:-0}")"
        fi
      fi
    done
  fi
  for ((i=0; i<${#AV_LABEL[@]}; i++)); do
    [ "${AR_OK[$i]}" = 1 ] || [ "${AR_WHY[$i]}" = skipped ] || { has_fail=1; break; }
  done
  if [ "$has_fail" = 1 ]; then
    [ "${#AT_RANK[@]}" -gt 0 ] && box_mid
    local maxw=$((BOXW - 30)); [ "$maxw" -lt 12 ] && maxw=12
    for ((i=0; i<${#AV_LABEL[@]}; i++)); do
      [ "${AR_OK[$i]}" = 1 ] || [ "${AR_WHY[$i]}" = skipped ] && continue
      box_row "  ${RED}✘${RST}  $(printf '%-22s' "$(at_lbl "${AV_LABEL[$i]}" 22)") ${GRY}$(at_lbl "${AR_WHY[$i]}" "$maxw")${RST}"
    done
  fi
  box_bot
}
at_to_t() { # AT_SEL (one index, or several = bond) -> T_CARRIER T_PEER T_PATH T_SNI T_REV AT_EXTRA + labels
  local i c cars='' cdn='' l
  AT_EXTRA=''; T_SNI=''; T_REV=''; T_PATH=''
  if [ "${#AT_SEL[@]}" -gt 1 ]; then
    if [ "${AV_KIND[${AT_SEL[0]}]}" = r ]; then
      for i in "${AT_SEL[@]}"; do
        c=${AV_CAR[$i]}; cars="${cars:+$cars+}$c"
        [ -n "${AV_PORT[$i]}" ] && AT_EXTRA+="listen-$c: \":${AV_PORT[$i]}\""$'\n'
      done
      v_carrier_list "$cars" || { err "Cannot join $cars: shaped carriers are single-carrier only."; return 1; }
      AT_EXTRA=${AT_EXTRA%$'\n'}
      T_CARRIER=$cars; T_PEER=$AT_ADDR; T_PATH=$AT_PATH; T_REV=1
      AT_SEL_LABEL="reverse bond $cars"; AT_SEL_KEY=bond/r
      return 0
    fi
    for i in "${AT_SEL[@]}"; do
      c=${AV_CAR[$i]}; cars="${cars:+$cars+}$c"; AT_EXTRA+="peer-$c: ${AV_PEER[$i]}"$'\n'
      # fp / ech / tls-frag are global flags, not per carrier: a bond uses the settings of its first (best) CDN variant
      if [ "${AV_KIND[$i]}" = c ] && [ -z "$cdn" ]; then cdn=$i; T_SNI=${AV_SNI[$i]}; fi
    done
    # B4/D7: a joined list must be a valid bond; the engine refuses a shaped leg in a '+'-bond, so never write one
    v_carrier_list "$cars" || { err "Cannot join $cars: shaped carriers are single-carrier only."; return 1; }
    AT_EXTRA=${AT_EXTRA%$'\n'}
    if [ -n "$cdn" ]; then while IFS= read -r l; do [ -n "$l" ] && AT_EXTRA+=$'\n'"$l"; done < <(at_cdn_lines "$cdn"); fi
    T_CARRIER=$cars; T_PEER=$AT_ADDR; T_PATH=$AT_PATH
    at_hop_line
    AT_SEL_LABEL="bond $cars"; AT_SEL_KEY=bond
    return 0
  fi
  i=${AT_SEL[0]}; c=${AV_CAR[$i]}
  T_CARRIER=$c; T_PEER=${AV_PEER[$i]}
  case "$c" in ws|wss|h2|h2c|grpc|*+*) T_PATH=$AT_PATH ;; esac
  if [ "${AV_KIND[$i]}" = c ]; then T_SNI=${AV_SNI[$i]}; AT_EXTRA=$(at_cdn_lines "$i"); fi
  if av_anti "$i"; then
    T_SNI=${AV_SNI[$i]}; AT_EXTRA=$(at_cdn_lines "$i")
    [ -n "${AV_FS[$i]}" ] && AT_EXTRA+="${AT_EXTRA:+$'\n'}fake-sni: ${AV_FS[$i]}"$'\n'"fake-mode: ${AV_FM[$i]:-seq}"
  fi
  [ "${AV_KIND[$i]}" = r ] && T_REV=1
  if [[ "$c" == *+* ]] && [ "${AV_KIND[$i]}" = r ] && [ -n "${AT_TUNNEL:-}" ]; then
    local rc rp
    for rc in ${c//+/ }; do
      rp=$(cfg "$AT_TUNNEL" "listen-$rc")
      [ -n "$rp" ] && AT_EXTRA+="${AT_EXTRA:+$'\n'}listen-$rc: $rp"
    done
  fi
  at_hop_line
  AT_SEL_LABEL=${AV_LABEL[$i]}; AT_SEL_KEY=$(av_key "$i")
}
AT_JD=''; AT_JR=''
at_joinable_summary() { # fills AT_JD (joinable direct/CDN row numbers) and AT_JR (joinable reverse row numbers)
  local k=0 i
  AT_JD=''; AT_JR=''
  for i in "${AT_RANK[@]}"; do
    k=$((k+1))
    case "${AV_CAR[$i]}" in *+*) continue ;; esac
    is_ext_carrier "${AV_CAR[$i]}" && continue
    av_anti "$i" && continue
    if [ "${AV_KIND[$i]}" = r ]; then AT_JR+="${AT_JR:+ }$k"; else AT_JD+="${AT_JD:+ }$k"; fi
  done
}
at_choose() { # rc 0 = chosen (T_* ready), 1 = cancelled
  local n=${#AT_RANK[@]} best=${AT_RANK[0]} bond=() rbond=() i num rest bd bu can_join=0 jd_n=0 jr_n=0
  for i in "${AT_RANK[@]}"; do
    case "${AV_CAR[$i]}" in *+*) continue ;; esac
    is_ext_carrier "${AV_CAR[$i]}" && continue # B4: shaped carriers are single-carrier only
    if [ "${AV_KIND[$i]}" = d ] && ! av_anti "$i"; then bond+=("$i")
    elif [ "${AV_KIND[$i]}" = r ]; then rbond+=("$i"); fi
  done
  at_joinable_summary
  jd_n=$(wc -w <<<"$AT_JD"); jr_n=$(wc -w <<<"$AT_JR")
  { [ "$jd_n" -ge 2 ] || [ "$jr_n" -ge 2 ]; } && can_join=1
  if [ "$NONINTERACTIVE" = 1 ]; then # --pick best (default) | bond | rbond | N | N,N...
    local def_pick="best"
    local cur_pol=${NI_POLICY:-}
    [ -z "$cur_pol" ] && [ -n "${AT_TUNNEL:-}" ] && cur_pol=$(cat "$CONF/$AT_TUNNEL.policy" 2>/dev/null || echo speed)
    [ "$cur_pol" = bond ] && def_pick="bond"
    case "${NI_PICK:-$def_pick}" in
      best) AT_SEL=("$best") ;;
      bond)
        if [ "${#bond[@]}" -ge 2 ]; then AT_SEL=("${bond[@]}")
        elif [ "${#rbond[@]}" -ge 2 ]; then AT_SEL=("${rbond[@]}")
        else AT_SEL=("$best"); fi ;;
      rbond)
        if [ "${#rbond[@]}" -ge 2 ]; then AT_SEL=("${rbond[@]}")
        else AT_SEL=("$best"); fi ;;
      *,*|*+*) at_rows "$NI_PICK" || return 1 ;;
      ''|*[!0-9]*) err "--pick must be best, bond, a row number of the table, or several joined with commas or + (1,3)"; return 1 ;;
      *) if [ "$NI_PICK" -ge 1 ] && [ "$NI_PICK" -le "$n" ]; then AT_SEL=("${AT_RANK[$((NI_PICK-1))]}")
         else err "--pick $NI_PICK: the table has $n working row(s)"; return 1; fi ;;
    esac
    at_to_t; return 0
  fi
  printf -v bd '%.1f' "${AR_DOWN[$best]:-0}"
  printf -v bu '%.1f' "${AR_UP[$best]:-0}"
  echo
  printf '  %s  Use #1 %s(%s · %s / %s MB/s)%s\n' "$(key_label Enter)" "$GRY" "${AV_LABEL[$best]}" "$bd" "$bu" "$RST"
  if [ "${#bond[@]}" -ge 2 ]; then
    printf '  %s      Bond all %d direct carriers %s(failover + aggregate)%s\n' "$(key_label b)" "${#bond[@]}" "$GRY" "$RST"
  elif [ "${#rbond[@]}" -ge 2 ]; then
    printf '  %s      Bond all %d reverse carriers %s(failover + aggregate)%s\n' "$(key_label b)" "${#rbond[@]}" "$GRY" "$RST"
  fi
  local opts=()
  [ "$n" -gt 1 ] && opts+=("1-$n" "pick row")
  [ "$n" -gt 1 ] && [ "$can_join" = 1 ] && opts+=("c" "custom join")
  at_failed >/dev/null && opts+=("f" "force failed")
  opts+=("q" "cancel")
  menu_line "${opts[@]}"
  while :; do
    printf '  %s?%s Choice %s[Enter]%s %s›%s ' "$CYN" "$RST" "$GRY" "$RST" "$GRY" "$RST"
    key_read
    case "$KEY" in
      enter) AT_SEL=("$best") ;;
      b|B)
        if [ "${#bond[@]}" -ge 2 ]; then AT_SEL=("${bond[@]}")
        elif [ "${#rbond[@]}" -ge 2 ]; then AT_SEL=("${rbond[@]}")
        else echo; warn "Bonding needs two or more working direct or reverse carriers."; continue; fi ;;
      c|C)
        if [ "$can_join" != 1 ]; then
          echo; warn "Joining needs at least two compatible direct rows or two reverse rows."; continue
        fi
        echo; at_custom || continue ;;
      f|F) echo; at_force || continue ;;
      [1-9]) num=$KEY
         if [ "$n" -gt 9 ]; then printf '%s' "$KEY"; IFS= read -r -t 5 rest || true; num="$KEY$rest"; fi
         if [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le "$n" ]; then AT_SEL=("${AT_RANK[$((num-1))]}")
         else echo; warn "No row $num."; continue; fi ;;
      q|Q|esc) echo; return 1 ;;
      *) echo; warn "Press Enter, b, c, f, a row number or q."; continue ;;
    esac
    case "$KEY" in c|C|f|F) ;; *) echo ;; esac
    at_to_t || continue
    return 0
  done
}
at_rows() { # "1 3 4", "1,3,4" or "1+3+4" (rows of the table) -> AT_SEL ; rc 1 with a message when a row is unusable
  local norm=${1//[,+;]/ } r i c seen=' ' cars=' ' has_r=0 has_d=0
  AT_SEL=()
  for r in $norm; do
    if ! [[ "$r" =~ ^[0-9]+$ ]] || [ "$r" -lt 1 ] || [ "$r" -gt "${#AT_RANK[@]}" ]; then err "No row $r in the table."; return 1; fi
    i=${AT_RANK[$((r-1))]}
    case "$seen" in *" $i "*) continue ;; esac
    seen+="$i "
    AT_SEL+=("$i")
  done
  [ "${#AT_SEL[@]}" -ge 1 ] || { err "Enter at least one row number."; return 1; }
  [ "${#AT_SEL[@]}" -eq 1 ] && return 0
  for i in "${AT_SEL[@]}"; do
    case "${AV_CAR[$i]}" in *+*) err "${AV_LABEL[$i]} is already a joined bond; pick individual rows to join."; return 1 ;; esac
    if av_anti "$i"; then err "${AV_LABEL[$i]} is an anti-censor variant; it cannot be joined with others. Pick it alone."; return 1; fi
    if [ "${AV_KIND[$i]}" = r ]; then has_r=1; else has_d=1; fi
    c=${AV_CAR[$i]}
    case "$cars" in *" $c "*) err "Two rows use $c; a joined tunnel can use each type once."; return 1 ;; esac
    cars+="$c "
  done
  if [ "$has_r" = 1 ] && [ "$has_d" = 1 ]; then
    at_joinable_summary
    err "Cannot mix direct and reverse rows in one tunnel.${AT_JD:+ Direct rows: $AT_JD.}${AT_JR:+ Reverse rows: $AT_JR.}"
    return 1
  fi
  v_carrier_list "$(printf '%s' "${cars# }" | tr ' ' '+')" || return 1 # B4: a shaped row cannot be joined
}
at_custom() { # interactive: choose rows to join -> AT_SEL
  at_joinable_summary
  local s=''
  [ "$(wc -w <<<"$AT_JD")" -ge 2 ] && s="Direct: $AT_JD"
  [ "$(wc -w <<<"$AT_JR")" -ge 2 ] && s="${s:+$s  ·  }Reverse: $AT_JR"
  [ -n "$s" ] && hint "$s (cannot mix)"
  ask "Join rows (e.g. 1+3, Enter = cancel)" ""
  [ -n "$REPLY_V" ] || return 1
  at_rows "$REPLY_V"
}
at_failed() { # prints the indices of variants that failed the test ; rc 1 when none did
  local i any=1
  for ((i=0; i<${#AV_LABEL[@]}; i++)); do [ "${AR_OK[$i]}" = 1 ] || { echo "$i"; any=0; }; done
  return $any
}
at_force() { # interactive: pick a variant that failed the test -> AT_SEL
  local f=() i k=0
  mapfile -t f < <(at_failed)
  [ "${#f[@]}" -gt 0 ] || { warn "Every type passed."; return 1; }
  warn "Failed variants (may not connect until route opens):"
  for i in "${f[@]}"; do k=$((k+1)); printf '    %s%d%s %-24s %s%s%s\n' "$CYN" "$k" "$RST" "$(at_lbl "${AV_LABEL[$i]}" 24)" "$GRY" "${AR_WHY[$i]}" "$RST"; done
  ask "Number (Enter = cancel)" ""
  [ -n "$REPLY_V" ] || return 1
  if ! [[ "$REPLY_V" =~ ^[0-9]+$ ]] || [ "$REPLY_V" -lt 1 ] || [ "$REPLY_V" -gt "$k" ]; then warn "No number $REPLY_V."; return 1; fi
  AT_SEL=("${f[$((REPLY_V-1))]}")
}
at_none() { # nothing worked
  err "No carrier reached ${AT_ADDR:-Kharej}"
  [ "$AT_QUIET" = 1 ] && return 0
  at_table
  echo
  if [ "$AT_DLINK" = 0 ]; then
    hint " · Reverse didn't start? On the exit server run:  $SELF auto-ip <name> $(public_ip)"
  fi
  hint " · the exit server updated to 3.3.8+? Its auto carriers moved to new ports: copy its token again (t) and paste it here"
  hint " · Check the exit server status, token currency, and cloud firewall"
  hint " · Retest after fixing:  ${AT_AGAIN:-paste token again}"
}
# Time estimates shown in the Test mode menu (one table so they can be tuned without touching the box rows):
# screening rows x ~20 s a row at the 8-16 MB probe sizes and the ~8 MB/s budget rate, rounded to a range.
#   normal  ~14 rows  -> ~1-3 min    fast    ~14 + 7x6 rows -> ~4-6 min
#   anti    ~200 rows -> ~15-40 min  reverse ~8 rows        -> ~1-2 min
at_preset_ask() { # -> AT_PRESET normal|anti|fast|reverse|extended (--test in unattended runs), T_SNI (CDN domain, d) ; rc 1 = cancelled
  AT_PRESET=${NI_TEST:-normal}
  [ "$NONINTERACTIVE" = 1 ] && return 0
  [ "${UI_W:-0}" -gt 0 ] || ui_init_width
  local t dom_lbl ext ext_n=0 meta
  ext=$(auto_plan_extnames "$(plan_part "${T_AUTO:-}" d)")
  for t in $ext; do ext_n=$((ext_n+1)); done
  meta="Exit server ${T_PEER%%[:,]*} · ${T_PORTS:-any port}"
  [ "$ext_n" -gt 0 ] && meta+=" · +${ext_n} shaped"
  echo
  hint "$meta"
  for t in 1 2 3 4 5 6; do
    dom_lbl="${T_SNI:-none (optional)}"
    echo
    box_top "Test mode"
    box_row "$(key_label Enter)  Standard carriers     ${GRY}Direct, CDN, Reverse        ~1-3 min${RST}"
    box_row "$(key_label f)      Anti-censor fast      ${GRY}rst/synrst x 3 SNIs,       ~4-6 min${RST}"
    box_row "                               ${GRY}best row applied${RST}"
    box_row "$(key_label a)      + Anti-censor         ${GRY}full grid, fake-SNI, fp   ~15-40 min${RST}"
    [ "$ext_n" -gt 0 ] && box_row "$(key_label x)      + Extended            ${GRY}13 shaped carriers         ~4-7 min${RST}"
    box_row "$(key_label r)      Reverse only          ${GRY}just the r= plan carriers ~1-2 min${RST}"
    box_row "$(key_label d)      Cloudflare domain     ${GRY}$dom_lbl${RST}"
    box_row "$(key_label q)      Cancel"
    box_bot
    printf '  %s?%s Choice %s[Enter]%s %s›%s ' "$CYN" "$RST" "$GRY" "$RST" "$GRY" "$RST"
    key_read
    case "$KEY" in
      enter) AT_PRESET=normal; echo; return 0 ;;
      f|F) AT_PRESET=fast; echo; return 0 ;;
      a|A) AT_PRESET=anti; echo; return 0 ;;
      x|X) if [ -z "$(auto_plan_extnames "$(plan_part "$T_AUTO" d)")" ]; then
             echo; hint "This token carries no extended carriers (a pairing token never does). Pick another test."; continue
           fi
           AT_PRESET=extended; echo; return 0 ;;
      r|R) AT_PRESET=reverse; echo; return 0 ;;
      d|D) echo; hint "Domain proxied to the exit server via Cloudflare (orange cloud, SSL Full)."
           ask_ok "Cloudflare domain" "$T_SNI" v_domain_opt || continue; T_SNI=$REPLY_V
           if [ -n "$T_SNI" ] && [ -n "${T_AUTO:-}" ]; then
             local _d _c _p _cf_any=0 _noncf=''
             _d=$(plan_part "$T_AUTO" d)
             for _c in $AUTO_VAR_CDN; do
               _p=$(plan_port "$_d" "$_c"); [ -n "$_p" ] || continue
               if cf_port_ok "$_c" "$_p"; then _cf_any=1; else _noncf+="${_noncf:+, }$_c:$_p"; fi
             done
             if [ "$_cf_any" = 0 ] && [ -n "$_noncf" ]; then
               warn "Token CDN ports ($_noncf) are not Cloudflare orange-cloud ports (443/2053/2083/2087/2096/8443)."
             fi
           fi ;;
      q|Q|esc) echo; return 1 ;;
      *) echo ;;
    esac
  done
  return 1
}
auto_iran_front() { # token : test everything, ranked table, choose. Leaves T_* ready for the normal flow
  AUTO_TOKEN=$1
  [ -n "$T_AUTO" ] || { err "This auto token has no test plan. Make a new token on the exit server (wattun 2.1.0 or newer)."; return 1; }
  at_preset_ask || { warn "Cancelled."; return 1; }
  AT_QUIET=0; AT_MB=8; AT_NOTE=""; AT_SKIP=''; AT_AGAIN=''
  auto_test || { err "Could not prepare the test (is $AUTO_RUN writable?)."; return 1; }
  at_rank; auto_refine
  if [ "${#AT_RANK[@]}" -eq 0 ]; then echo; at_none; return 1; fi
  at_table
  at_choose || { warn "Cancelled."; return 1; }
  ok "Selected: $AT_SEL_LABEL"
  at_tune; at_tune_extra
  return 0
}
auto_current_key() { # name -> carrier/kind of the running config (d direct, c CDN, r reverse) or bond / bond/r
  local c; c=$(cfg "$1" carrier)
  case "$c" in *+*) is_reverse "$1" && echo bond/r || echo bond; return ;; esac
  if is_reverse "$1"; then echo "$c/r"; elif [ -n "$(cfg "$1" sni)" ]; then echo "$c/c"; elif [ -n "$(cfg "$1" udp-hop)" ]; then echo "$c/d/hop"; else echo "$c/d"; fi
}
auto_apply() { # name : write the chosen variant (T_*, AT_EXTRA) into NAME.yml, restart, wait for the link
  local n=$1 f="$CONF/$1.yml" ol l k v rport='' curkey c bak tokbak='' lc lv p
  local -a old_rfw=() new_rfw=()
  # B2: the guard that makes "applying a skipped carrier" impossible even if a caller bypasses the variant builder
  for c in ${T_CARRIER//+/ }; do
    carrier_ok_here "$c" || { err "Carrier '$c' needs wattun $(carrier_min_ver "$c") on this server; not writing it into '$n'."; return 1; }
  done
  bak="$f.bak"
  cp -p "$f" "$bak" || { err "Could not back up $f; not applying."; return 1; } # F16: restore on a failed link check
  tokbak="$CONF/$n.token.bak"
  [ -f "$CONF/$n.token" ] && cp -p "$CONF/$n.token" "$tokbak" # the token is rewritten below; restore it too when the link fails
  AT_APPLIED=1
  curkey=$(auto_current_key "$n")
  if is_reverse "$n"; then
    ol=$(cfg "$n" listen); split_hp "$ol"
    [ -n "$HP_PORT" ] && is_rpool "$(cfg "$n" carrier)" && old_rfw+=("$HP_PORT/$(rproto "$(cfg "$n" carrier)")")
    while IFS= read -r l; do
      [ -n "$l" ] || continue
      lc=${l%%:*}; lc=${lc#listen-}; lv=${l#*:}; lv=${lv//\"/}; lv=${lv//[[:space:]]/}
      split_hp "$lv"
      [ -n "$HP_PORT" ] && old_rfw+=("$HP_PORT/$(rproto "$lc")")
    done < <(grep -E '^listen-[a-z0-9-]+:' "$f" 2>/dev/null)
  fi
  sed -i -E '/^(carrier|peer|path|sni|host|reverse|listen|fp|ech|ech-cache|tls-frag|udp-hop|peer-[a-z0-9-]+|listen-[a-z0-9-]+):/d' "$f"
  # settings the tuning tested: its result replaces them. On a switch to another type all of them go: a value tuned for one
  # type can break another (the engine refuses sessions with icmp, bonds and reverse)
  [ "$curkey" = "$(cut -d/ -f1,2 <<<"${AT_SEL_KEY:-}")" ] || AT_TUNE_KEYS='sessions conns mtu batch loss-ceiling win-max'
  for k in $AT_TUNE_KEYS; do sed -i "/^$k:/d" "$f"; done
  set_value "$n" carrier "$T_CARRIER"
  # a working fake-SNI/pool-rotate combination survives a type switch only while the new carrier set has
  # a pool leg and this side is the dialer (the desync layer attaches to every pool leg of a bond, nowhere
  # else); strip it otherwise, so switching to icmp/udp/reverse never leaves dead keys (or silently re-arms
  # them when the type is switched back later)
  local keepres=''
  if is_pool_list "$T_CARRIER"; then
    if [ "$T_REV" = 1 ]; then
      [ "$(role "$n")" = Kharej ] && keepres=1
    else
      [ "$(role "$n")" = Iran ] && keepres=1
    fi
  fi
  [ "$keepres" = 1 ] || sed -i -E '/^(fake-(sni|mode|ttl)|pool-rotate(-bytes)?):/d' "$f"
  set_value "$n" peer "$T_PEER"
  [ -n "$T_PATH" ] && set_value "$n" path "$T_PATH"
  if is_shaped_carrier "$T_CARRIER"; then # B4: shaped carriers are single-carrier only; raw tier has no listen port
    if [ "$(role "$n")" = Kharej ] && is_shaped_udp "$T_CARRIER"; then
      local sp; sp=$(shaped_udp_port "$T_CARRIER"); split_hp "$T_PEER"; [ -n "$HP_PORT" ] && sp=$HP_PORT
      set_value "$n" listen "\":$sp\""; fw_open "$sp/udp"
    fi
    if [ "$(role "$n")" = Iran ] && [ -n "${T_KEY:-}" ]; then # a reusable token describing the chosen shape
      # F11 (2026-11-22): T_PAIR is make_token's $10 (the pair capability); it sat in $9 (auto plan) here,
      # so a field-10 token was rewritten with its capability as a bogus plan. $9 stays empty on an apply.
      ( umask 077; make_token "$T_CARRIER" "$T_PEER" "$T_KEY" "${T_PATH:-}" "${T_SNI:-}" "${T_ICMP:-}" "${T_PORTS:-}" "" "" "${T_PAIR:-}" >"$CONF/$n.token" )
    fi
  fi
  if [ -n "$T_SNI" ]; then set_value "$n" sni "$T_SNI"; set_value "$n" host "$T_SNI"; fi
  [ "$T_REV" = 1 ] && set_value "$n" reverse true
  if [ "$T_REV" = 1 ] && [[ "$T_CARRIER" != *+* ]] && is_rpool "$T_CARRIER"; then
    split_hp "$T_PEER"; rport=$HP_PORT
    [ -n "$rport" ] && { set_value "$n" listen "\":$rport\""; new_rfw+=("$rport/$(rproto "$T_CARRIER")"); }
  fi
  while IFS= read -r l; do
    [ -n "$l" ] || continue
    k=${l%%: *}; v=${l#*: }; set_value "$n" "$k" "$v"
    if [ "$T_REV" = 1 ] && [[ "$k" == listen-* ]]; then
      lc=${k#listen-}; lv=${v//\"/}; lv=${lv//[[:space:]]/}
      split_hp "$lv"
      [ -n "$HP_PORT" ] && new_rfw+=("$HP_PORT/$(rproto "$lc")")
    fi
  done <<<"$AT_EXTRA"
  l=$(ech_cache_line "$n"); if [ -n "$l" ]; then set_value "$n" ech-cache "${l#*: }"; fi
  step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
  for p in ${new_rfw[@]+"${new_rfw[@]}"}; do fw_open "$p"; done
  for p in ${old_rfw[@]+"${old_rfw[@]}"}; do
    case " ${new_rfw[*]:-} " in *" $p "*) ;; *) fw_close "$p" ;; esac
  done
  if [ "$T_REV" = 1 ] && [[ "+$T_CARRIER+" == *+icmp+* ]]; then
    [ "$AT_QUIET" = 1 ] || kreply_offer
  else kreply_users_left || kreply_restore; fi
  # AT_QUIET=1 applies and restarts without waiting unless AT_VERIFY=1 (auto_retest verifies and rolls back on failure).
  [ "$AT_QUIET" = 1 ] && [ "${AT_VERIFY:-0}" != 1 ] && { rm -f "$bak" "$tokbak"; return 0; }
  if wait_link "$n" 25; then
    ok "CONNECTED — ${AT_SEL_LABEL:-$T_CARRIER} · RTT ${LINK_RTT} ms"; rm -f "$bak" "$tokbak"
  else
    warn "Not connected yet; restoring the previous config."
    if cp -p "$bak" "$f"; then
      [ -f "$tokbak" ] && cp -p "$tokbak" "$CONF/$n.token"
      rm -f "$bak" "$tokbak"
      AT_APPLIED=0 # the variant was rolled back; change_key must not treat its key as applied
      for p in ${new_rfw[@]+"${new_rfw[@]}"}; do
        case " ${old_rfw[*]:-} " in *" $p "*) ;; *) fw_close "$p" ;; esac
      done
      for p in ${old_rfw[@]+"${old_rfw[@]}"}; do fw_open "$p"; done
    else
      warn "Could not restore $f; the backup is kept at $bak (and $tokbak)."
      { [ "$NONINTERACTIVE" = 1 ] || [ "${AT_VERIFY:-0}" = 1 ]; } && return 1
      return 0
    fi
    systemctl restart "${WAT_PREFIX}@$n" >/dev/null 2>&1
    { [ "$NONINTERACTIVE" = 1 ] || [ "${AT_VERIFY:-0}" = 1 ]; } && return 1
  fi
  return 0
}
at_skip_reverse_keys() { # tunnel -> space-padded AT_SKIP of active reverse leg keys (" tls/r wss/r ")
  is_reverse "$1" || return 0
  local c out=' '
  for c in $(tr '+' ' ' <<<"$(cfg "$1" carrier)"); do [ -n "$c" ] && out+="$c/r "; done
  printf '%s' "$out"
}
at_probe_live_tunnel() { # tunnel : measure the running reverse tunnel via its own /speedtest when its port was skipped
  local n=$1 cur m mp s i idx='' save_mb=$AT_MB
  is_reverse "$n" || return 0
  m=$(cfg "$n" metrics); mp=${m##*:}
  [[ "$mp" =~ ^[0-9]+$ ]] || return 0
  s=$(stats "$n" 2>/dev/null) || return 0
  [ "$(jget "$s" alive)" = true ] || return 0
  cur=$(auto_current_key "$n")
  if [ "$cur" = bond/r ]; then
    av_add "reverse bond $(cfg "$n" carrier) (current)" "$(cfg "$n" carrier)" r "$AT_ADDR" '' ''
    idx=$((${#AV_LABEL[@]} - 1))
  else
    for ((i=0; i<${#AV_LABEL[@]}; i++)); do
      [ "$(av_key "$i")" = "$cur" ] && { idx=$i; break; }
    done
  fi
  [ -n "$idx" ] || return 0
  AR_OK[$idx]=0; AR_DOWN[$idx]=0; AR_UP[$idx]=0; AR_RTT[$idx]=0; AR_WHY[$idx]=''
  AT_MB=${AT_LIVE_MB:-8}
  [ "$AT_QUIET" = 1 ] || at_busy "${AV_LABEL[$idx]} (live tunnel)"
  at_measure "$idx" "$mp"
  [ "$AT_QUIET" = 1 ] || { at_idle; at_print "$idx"; }
  AT_MB=$save_mb
  return 0
}
auto_test_cmd() { # name : re-run the test for an existing auto Iran tunnel and offer to switch
  local n=$1 cur i nolink=0
  if [ "$(role "$n")" = Iran ] && [ ! -f "$CONF/$n.auto" ]; then
    # 4.1.1: a fixed-carrier tunnel is tested too: the Go manager has Kharej open every carrier through the pairing
    local a=(auto-test "$n"); [ "$NONINTERACTIVE" = 1 ] && a+=(--yes)
    [ -n "$NI_TEST" ] && a+=(--test "$NI_TEST"); [ -n "${NI_PICK:-}" ] && a+=(--pick "$NI_PICK")
    env -u WAT_BASH_MGR "$BIN" "${a[@]}"; return $?
  fi
  if [ "$(role "$n")" != Iran ]; then
    err "'$n' is not an entry tunnel: the carrier test runs on the entry side."; return 1
  fi
  if ! { read_token "$(cat "$CONF/$n.auto")" && [ -n "$T_AUTO" ]; }; then err "$CONF/$n.auto is not a valid auto token."; return 1; fi
  AT_TUNNEL=$n
  cur=$(auto_current_key "$n")
  AT_QUIET=0; AT_MB=8; AT_NOTE=""; AT_SKIP=$(at_skip_reverse_keys "$n"); AT_AGAIN="$SELF auto-test $n"
  page "Auto test" "$n"
  hint "Current: $cur ($(cfg "$n" carrier)) · live tunnel untouched"
  at_preset_ask || { warn "Cancelled."; return 0; }
  echo
  auto_test || { err "Could not prepare the test (is $AUTO_RUN writable?)."; return 1; }
  AT_LIVE_MB=8 at_probe_live_tunnel "$n"
  at_rank; auto_refine
  for ((i=0; i<${#AV_LABEL[@]}; i++)); do
    [ "${AR_OK[$i]:-0}" = 1 ] && continue
    [[ "${AR_WHY[$i]:-}" == "no link"* ]] && nolink=$((nolink+1))
  done
  if [ "${#AT_RANK[@]}" -eq 0 ]; then
    echo; at_none
    [ "$nolink" -ge 3 ] && hint "Several carriers did not answer. Make sure the exit tunnel is running and up to date (run 'wattun heal' on the exit server if upgraded)."
    { [ "$NONINTERACTIVE" != 1 ] && echo && confirm "Use one of the types that failed anyway?" n && at_force; } || return 1
    at_to_t
  else
    at_table
    [ "${#AT_RANK[@]}" -le 1 ] && [ "$nolink" -ge 3 ] && hint "Other carriers did not answer — check that exit server is running and not blocked by the firewall."
    at_choose || { warn "No change."; [ "$NONINTERACTIVE" = 1 ] && return 1; return 0; }
    if [ "$AT_SEL_KEY" = "$cur" ] && [ "$T_CARRIER" = "$(cfg "$n" carrier)" ] && is_reverse "$n"; then
      ok "'$n' already uses $AT_SEL_LABEL."
      return 0
    fi
    at_tune; at_tune_extra
  fi
  local k v curt=''
  for k in $AT_TUNE_KEYS; do v=$(cfg "$n" "$k"); [ -n "$v" ] && curt+="$k: $v"$'\n'; done
  if [ "$AT_SEL_KEY" = "$cur" ] && [ "$T_CARRIER" = "$(cfg "$n" carrier)" ] && [ "${curt%$'\n'}" = "$AT_TUNE" ]; then ok "'$n' already uses $AT_SEL_LABEL${AT_TUNE:+ with these settings}."; return 0; fi
  confirm "Switch '$n' to $AT_SEL_LABEL? (open connections drop)" y || { warn "No change."; return 0; }
  auto_apply "$n"
}
auto_retest() { # name : unattended (auto-heal or auto-optimize): same duration-based 8-16 MB screening probes
  local n=$1 cur best winner winner_key pol
  if ! { [ -f "$CONF/$n.auto" ] && read_token "$(cat "$CONF/$n.auto")" && [ -n "$T_AUTO" ]; }; then
    # not an auto tunnel: a plain CDN tunnel only gets a fresh edge scan (dead edge IPs replaced)
    cdn_tunnel_p "$n" && { cdn_refresh_edges "$n"; return 0; }
    return 1
  fi
  AT_TUNNEL=$n
  AT_QUIET=1; AT_MB=1; AT_NOTE=''; AT_SKIP=$(at_skip_reverse_keys "$n"); AT_AGAIN=''
  cur=$(auto_current_key "$n")
  AT_PRESET=normal
  auto_test || return 1
  AT_LIVE_MB=${AT_SCREEN_MB_START:-8} at_probe_live_tunnel "$n"
  at_rank
  if [ "${#AT_RANK[@]}" -eq 0 ]; then logger -t wattun-heal "retest of $n: no connection type works right now"; return 0; fi
  winner=${AT_RANK[0]}
  winner_key=$(av_key "$winner")
  if [ "$winner_key" = "$cur" ]; then
    logger -t wattun-heal "retest of $n: current variant $cur is already the top-ranked carrier, no switch"
    rm -f "$RUN/$n.sla_triggered"
    [ "$cur" = "$(cfg "$n" carrier)/c" ] && cdn_refresh_edges "$n" # same carrier through the CDN: replace dead edge IPs
    return 0
  fi
  # If off-peak optimization or SLA breach triggered this, always upgrade to the winner!
  # Otherwise (connection recovery), if current variant is still working, avoid flapping.
  if [ "${AUTO_OPTIMIZE:-0}" != 1 ] && [ ! -f "$RUN/$n.sla_triggered" ]; then
    for best in "${AT_RANK[@]}"; do
      if [ "$(av_key "$best")" = "$cur" ]; then
        logger -t wattun-heal "retest of $n: current variant $cur still works, no switch"
        [ "$cur" = "$(cfg "$n" carrier)/c" ] && cdn_refresh_edges "$n"
        return 0
      fi
    done
  fi
  pol=$(cat "$CONF/$n.policy" 2>/dev/null || echo speed)
  if [ "$pol" = bond ]; then
    local -a bond_cars=() rbond_cars=()
    for i in "${AT_RANK[@]}"; do
      case "${AV_CAR[$i]}" in *+*) continue ;; esac
      is_ext_carrier "${AV_CAR[$i]}" && continue # B4: shaped carriers never join a bond
      if [ "${AV_KIND[$i]}" = d ] && ! av_anti "$i"; then bond_cars+=("$i")
      elif [ "${AV_KIND[$i]}" = r ]; then rbond_cars+=("$i"); fi
    done
    if [ "${#bond_cars[@]}" -ge 2 ]; then
      AT_SEL=("${bond_cars[@]}")
    elif [ "${#rbond_cars[@]}" -ge 2 ]; then
      AT_SEL=("${rbond_cars[@]}")
    else
      AT_SEL=("$winner")
    fi
  else
    AT_SEL=("$winner")
  fi
  at_to_t
  if AT_VERIFY=1 auto_apply "$n" >/dev/null 2>&1; then
    logger -t wattun-heal "switched $n from $cur to $AT_SEL_KEY"
  else
    logger -t wattun-heal "switch of $n from $cur to $AT_SEL_KEY failed link check; restored previous config"
  fi
  rm -f "$RUN/$n.sla_triggered"
  return 0
}
heal_matrix() { # name : unattended matrix, apply the best only when the current config has no working link (called by heal)
  local n=$1 stamp="$RUN/$1.matrix" m=$MGR renv best
  [ "$(find "$stamp" -mmin -60 2>/dev/null)" ] && return 0 # at most once per hour
  command -v systemd-run >/dev/null 2>&1 || return 0
  touch "$stamp"
  logger -t wattun-heal "tunnel $n still down after 3 restart cycles, running the anti-censor matrix"
  mapfile -t renv < <(run_env_args)
  [ -x "$m" ] || m=$(readlink -f "$0")
  systemd-run --quiet --collect --unit "${WAT_PREFIX}-matrix-$n" "${renv[@]}" \
    --setenv=AC_FALLBACK=1 "$m" matrix "$n" --yes >/dev/null 2>&1
  return 0
}
heal_retest() { # name : at most once per 30 min, in a transient unit so it outlives the heal run
  local n=$1 stamp="$RUN/$1.retest" m=$MGR renv
  mapfile -t renv < <(run_env_args)
  [ -n "$(find "$stamp" -mmin -30 2>/dev/null)" ] && return 0
  command -v systemd-run >/dev/null 2>&1 || return 0
  [ -x "$m" ] || m=$(readlink -f "$0")
  touch "$stamp"
  logger -t wattun-heal "tunnel $n still down after restarts, testing the other connection types"
  systemd-run --quiet --collect --unit "${WAT_PREFIX}-autoretest-$n" "${renv[@]}" \
    "$m" auto-retest "$n" --yes >/dev/null 2>&1
  return 0
}

# ======================================================================================
#  Anti-censor matrix (2.10.2): test EVERY resilience combination from the Iran side,
#  apply the best that connects. All probes are throw-away clients on this server -
#  Kharej is never touched (under a blackout there is no SSH to it anyway).
#  Matrix on the tunnel's pool carrier (tcp/tls/ws/wss/h2/h2c/grpc):
#    base (current config, no desync) + desync seq/seqsum/sum/ttl/rst per allowlisted SNI
#    + ECH for TLS carriers + auto-mode (the binary's own startup probe).
#  Fills AV_*/AR_*/AT_RANK like auto_test; the winner is written with ac_matrix_apply.
# ======================================================================================
AC_SNIS='mci.ir,irancell.ir,tci.ir,divar.ir' # curated allowlisted SNIs, comma separated
AC_MODES='seq seqsum sum ttl rst synrst paws'
ac_mode_ok() { # mode -> 1 when the installed wattun knows it (an older binary silently falls back to seq)
  case "$1" in
    seq|sum|ttl) echo 1 ;;
    seqsum) bin_ver_ok 2.8.0 ;;
    rst) bin_ver_ok 2.9.0 ;;
    split|hlen0|fakeip|synrst|ff) bin_ver_ok 2.10.5 ;;
    paws) bin_ver_ok 3.0.2 ;;
  esac
}
ac_matrix() { # name : needs T_* loaded from the tunnel (ac_load); fills AV_*, AR_*, AT_RANK, AT_SECS
  local n=$1 i fs fm leg peer tag t0=$SECONDS w car=$T_CARRIER bond=0 tlsleg=''
  local -a legs=()
  AV_LABEL=(); AV_CAR=(); AV_KIND=(); AV_PEER=(); AV_PORT=(); AV_SNI=(); AV_FP=(); AV_ECH=(); AV_FRAG=()
  AV_FS=(); AV_FM=(); AV_X=()
  AR_OK=(); AR_DOWN=(); AR_UP=(); AR_RTT=(); AR_WHY=()
  at_prep || return 1
  if [[ "$car" == *+* ]]; then # a bond: the desync kit attaches to its pool legs, so each leg is probed as its own client
    bond=1
    for leg in ${car//+/ }; do is_pool "$leg" && legs+=("$leg"); done
  else
    legs=("$car")
  fi
  for leg in "${legs[@]}"; do
    tag=''; [ "$bond" = 1 ] && tag="$leg "
    peer=$T_PEER
    [ "$bond" = 1 ] && [ -n "$(cfg "$n" "peer-$leg")" ] && peer=$(cfg "$n" "peer-$leg")
    [ -n "$peer" ] || continue
    # 0. baseline: this leg as the tunnel runs now (no desync) -> tells whether the censor even needs the kit
    av_add "${tag}base (no desync)" "$leg" d "$peer" '' "$T_SNI"
    # 1. every fake-mode for the first curated SNI
    for fm in $AC_MODES; do
      [ -n "$(ac_mode_ok "$fm")" ] || continue
      av_add "${tag}desync ${AC_SNIS%%,*} → $fm" "$leg" d "$peer" '' "$T_SNI" '' '' '' "${AC_SNIS%%,*}" "$fm"
    done
    # 2. the mode that passed the cut-after-first-bytes route (rst, field 2.11.0) against every other curated SNI
    local rest=${AC_SNIS#*,}
    [ -n "$(ac_mode_ok rst)" ] && for fs in ${rest//,/ }; do
      [ -n "$fs" ] || continue
      av_add "${tag}desync $fs → rst" "$leg" d "$peer" '' "$T_SNI" '' '' '' "$fs" rst
    done
    # 2b. the Cloudflare edge name with the two modes that passed a real CDN whitelist (2.10.12 field test)
    for fm in rst synrst; do
      [ -n "$(ac_mode_ok "$fm")" ] || continue
      av_add "${tag}desync www.cloudflare.com → $fm" "$leg" d "$peer" '' "$T_SNI" '' '' '' www.cloudflare.com "$fm"
    done
    case "$leg" in tls|wss|h2|grpc) [ -n "$tlsleg" ] || tlsleg=$leg ;; esac
  done
  # 3. ECH ladder (TLS carriers only): hides the real SNI from the DPI, works when SNIs are filtered
  if [ -n "$tlsleg" ] && [ -z "$(cfg "$n" ech)" ] && [ -n "$(bin_ver_ok 2.9.0)" ]; then
    tag=''; peer=$T_PEER
    [ "$bond" = 1 ] && { tag="$tlsleg "; peer=$(cfg "$n" "peer-$tlsleg"); }
    [ -n "$peer" ] && av_add "${tag}ech ladder (no desync)" "$tlsleg" d "$peer" '' "$T_SNI" chrome auto
  fi
  # 4. auto mode: the binary's own startup probe picks seq/sum/seqsum/rst by itself
  if [ "${#legs[@]}" -gt 0 ] && [ -n "$(bin_ver_ok 2.9.0)" ]; then
    leg=${legs[0]}; tag=''; peer=$T_PEER
    [ "$bond" = 1 ] && { tag="$leg "; peer=$(cfg "$n" "peer-$leg"); }
    [ -n "$peer" ] && av_add "${tag}desync auto-probe" "$leg" d "$peer" '' "$T_SNI" '' '' '' "${AC_SNIS%%,*}" auto
  fi
  # 5. Native ICMP echo fallback (activated when emergency ladder AC_FALLBACK=1 is set)
  if [ "${AC_FALLBACK:-0}" = 1 ] && [ "$car" != icmp ] && [ -n "$T_PEER" ]; then
    local icmp_peer="${T_PEER%:*}"
    av_add "fallback ICMP echo" icmp d "$icmp_peer" '' '' '' '' '' '' ''
  fi
  AT_SKIP=''; AT_NOTE=''; AT_IDX=0; AT_TOTAL=${#AV_LABEL[@]}; AT_PEAK=10; AT_MOVED_MB=0
  [ "$AT_QUIET" = 1 ] || sec_hdr "Matrix" "${#AV_LABEL[@]} combinations"
  for ((i=0; i<${#AV_LABEL[@]}; i++)); do
    AT_IDX=$((i+1))
    w=8
    [ "$AT_QUIET" = 1 ] || at_busy "${AV_LABEL[$i]}"
    at_probe "$i" "$w"
    [ "${AR_OK[$i]}" = 1 ] && AT_MOVED_MB=$((AT_MOVED_MB + 2 * AT_MB))
    [ "$AT_QUIET" = 1 ] || { at_idle; at_print "$i"; }
  done
  AT_IDX=0; AT_TOTAL=0
  at_cleanup
  at_rank
  auto_refine # an 8 MB sample ranks desync variants that differ by a few percent; the top 3 are re-measured at 20 MB
  AT_SECS=$((SECONDS-t0))
  return 0
}
ac_matrix_apply() { # name : write the chosen variant (AT_SEL[0]) into NAME.yml and restart
  local n=$1 i=${AT_SEL[0]}
  v_fake_mode "${AV_FM[$i]:-seq}" || return 1 # H6: matrix picks pass the same validator, never a raw set_value
  if [[ "$(cfg "$n" carrier)" == *+* ]]; then # a bond keeps its carriers and peers; only the shared desync keys change
    if [ -n "${AV_FS[$i]:-}" ]; then
      set_value "$n" fake-sni "${AV_FS[$i]}"
      set_value "$n" fake-mode "${AV_FM[$i]:-seq}"
      unset_value "$n" fake-ttl
    else
      sed -i -E '/^(fake-(sni|mode|ttl)):/d' "$CONF/$n.yml"
    fi
    [ -n "${AV_ECH[$i]:-}" ] && set_value "$n" ech "${AV_ECH[$i]}"
    if step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"; then
      wait_link "$n" 20 && ok "CONNECTED (RTT ${LINK_RTT} ms)" || warn "Not connected yet."
    fi
    return 0
  fi
  T_PEER=${AV_PEER[$i]}; T_SNI=${AV_SNI[$i]}
  T_CARRIER=${AV_CAR[$i]}
  AT_EXTRA=''
  [ -n "${AV_FP[$i]:-}" ] && AT_EXTRA+="fp: ${AV_FP[$i]}"$'\n'
  [ -n "${AV_ECH[$i]:-}" ] && AT_EXTRA+="ech: ${AV_ECH[$i]}"$'\n'
  if [ -n "${AV_FS[$i]:-}" ]; then
    set_value "$n" fake-sni "${AV_FS[$i]}"
    set_value "$n" fake-mode "${AV_FM[$i]:-seq}"
    unset_value "$n" fake-ttl # matrix probes always run ttl auto-calibration
  else
    sed -i -E '/^(fake-(sni|mode|ttl)):/d' "$CONF/$n.yml"
  fi
  auto_apply "$n"
}
ac_load() { # name -> T_* from the running tunnel's config (matrix runs on the same carrier+peer)
  local n=$1 kf
  kf=$(cfg "$n" key-file); [ -r "$kf" ] || kf="$CONF/$n.key"
  T_CARRIER=$(cfg "$n" carrier); T_PEER=$(cfg "$n" peer); T_PATH=$(cfg "$n" path)
  T_SNI=$(cfg "$n" sni); [ -n "$T_SNI" ] || T_SNI=$(cfg "$n" host)
  T_KEY=''; { IFS= read -r T_KEY <"$kf"; } 2>/dev/null
  [ -n "$T_KEY" ] && [ -n "$T_PEER" ]
}
ac_matrix_cmd() { # name : test every anti-censor combination, apply the best that connects
  local n=$1
  [ "$(role "$n")" = Iran ] || { err "'$n' is not an entry tunnel (the matrix runs client-side)."; return 1; }
  is_reverse "$n" && { err "'$n' is a reverse tunnel; the desync matrix needs a normal entry tunnel."; return 1; }
  local cr; cr=$(cfg "$n" carrier)
  if ! is_pool_list "$cr"; then
    if [ "$cr" = icmp ]; then
      err "The desync kit does not attach to the icmp carrier (its camouflage is the ICMP shape itself)."
      hint "For icmp the resilience knob is the volume governor: $SELF blackout $n  # or tunnel page -> o -> k"
      [ "$(cfg "$n" governor)" = true ] && hint "The governor is already ON for '$n'."
    else
      err "Carrier '$cr' has no anti-censorship layer (only tcp, tls, ws, wss, h2, h2c, grpc, alone or bonded)."
    fi
    return 1
  fi
  [ "$(uname -s)" = Linux ] || { err "The desync kit is a Linux feature (fake-sni needs CAP_NET_RAW)."; return 1; }
  ac_load "$n" || { err "Cannot read the key/peer of '$n'."; return 1; }
  [ "$(bin_ver_ok 2.7.0)" = 1 ] || { err "The desync matrix needs wattun 2.7.0 or newer (run: $SELF update)."; return 1; }
  page "Anti-censor matrix" "$n ($cr)"
  hint "Probing local desync/ECH combinations · live tunnel untouched"
  echo
  AT_QUIET=0; AT_MB=8
  ac_matrix "$n" || { err "Could not prepare the test."; return 1; }
  at_table
  if [ "${#AT_RANK[@]}" -eq 0 ]; then
    echo
    err "Nothing connects (even baseline failed — likely L3/IP block)"
    hint " · Switch carrier ([m]), use CDN (cdn-tune), or wait out blackout"
    return 1
  fi
  local best=${AT_RANK[0]} cur
  echo
  ok "Best: ${AV_LABEL[$best]} ($(printf '%.1f/%.1f MB/s' "${AR_DOWN[$best]:-0}" "${AR_UP[$best]:-0}"))"
  cur="fs=$(cfg "$n" fake-sni) fm=$(cfg "$n" fake-mode)"
  local want="fs=${AV_FS[$best]:-} fm=${AV_FM[$best]:-}"
  [ -n "$(cfg "$n" fake-ttl)" ] && cur+=" ttl=$(cfg "$n" fake-ttl)" # a manual fake-ttl differs from the matrix's auto
  if [ -n "${AV_ECH[$best]:-}" ]; then cur+=" ech=$(cfg "$n" ech)"; want+=" ech=${AV_ECH[$best]}"; fi
  if [ "$cur" = "$want" ]; then
    ok "The running tunnel already uses this combination; nothing to change."
    return 0
  fi
  if confirm "Apply '${AV_LABEL[$best]}' to '$n'? (restarts the tunnel, open connections drop)" y; then
    AT_SEL=("$best")
    ac_matrix_apply "$n"
    [[ "$cr" == *+* ]] && hint "The fake-SNI and mode now apply to every pool leg of '$cr'."
  else
    warn "No change."
  fi
  return 0
}

# ======================================================================================
#  CDN tuning (wattun >= 2.2.0 on Iran): find the fastest Cloudflare edges and TLS settings, no questions
#    cdn_scan   finds the edges that serve the domain over ECH: TCP pre-filter, then one throw-away client over all candidates, /stats edges (CS_*)
#    cdn_tune   tests chrome+ech, chrome, go (frag last resort) variants with the same throw-away clients as Auto (AV_*, AR_*) -> CT_IDX
#    Config keys written: peer (several edges, comma separated), fp, ech, tls-frag. sni/host stay the domain.
# ======================================================================================
CDN_MINVER=2.2.0
CDN_OK=''
CS_DIR=''; CS_PIDS=(); CS_EDGES=(); CS_REACH_IPS=(); CS_REACH=0; CS_TOTAL=0; CS_BEST_IP=''; CS_BEST_MS=0; CS_QUIET=0
CS_VERBOSE=${WAT_VERBOSE:-0}
CS_FALLBACK=0; CS_RAN=0
CS_V4='162.159.140.220 162.159.141.1 162.159.141.100 162.159.135.1 162.159.135.100 162.159.136.1 162.159.136.100 162.159.128.1 162.159.128.100 104.16.0.1 104.17.0.1 104.18.0.1 104.19.0.1 104.21.0.1 104.24.0.1 172.64.0.1 172.64.80.1 172.65.0.1 172.66.0.1 172.67.0.1 172.67.74.1 188.114.96.1 188.114.97.6'
CS_V6='2a06:98c1:3121::7 2a06:98c1:3120::7 2606:4700:3030::1 2606:4700:3033::1 2606:4700::6810:1 2606:4700:20::1'
CT_IDX=''; CT_I=''; CT_DESC=''; CT_W=8; AT_FULL=0
is_cdn_carrier() { case "$1" in ws|wss|h2|h2c|grpc) return 0 ;; esac; return 1; }
cdn_ok() { # is the installed binary new enough for fp / ech / tls-frag / several peers ?
  [ -n "$CDN_OK" ] || { ver_ge "$(bin_ver || true)" "$CDN_MINVER" 2>/dev/null && CDN_OK=1 || CDN_OK=0; }
  [ "$CDN_OK" = 1 ]
}
ech_cache_line() { # name : the "ech-cache:" config line for a tunnel that uses ech: auto (wattun >= 2.2.3 only; older engines reject unknown keys)
  grep -qx 'ech: auto' <<<"$AT_EXTRA" || return 0
  ver_ge "$(bin_ver || true)" 2.2.3 2>/dev/null && echo "ech-cache: $CONF/$1.ech"
  return 0
}
cdn_tunnel_p() { # name : an Iran client on a CDN carrier with a domain (not reverse, not an auto companion)
  [ "$(role "$1")" = Iran ] && ! is_reverse "$1" && is_cdn_carrier "$(cfg "$1" carrier)" || return 1
  [ -n "$(cfg "$1" sni)$(cfg "$1" host)" ]
}
cdn_domain() { # T_SNI, else the host of T_PEER when that is a domain -> prints it (nothing when the peer is an IP)
  local h
  if [ -n "$T_SNI" ]; then echo "$T_SNI"; return 0; fi
  h=${T_PEER%%,*}; h=${h%:*}
  [[ "$h" == *[A-Za-z]* ]] && [[ "$h" != *:* ]] && echo "$h"
  return 0
}
cdn_peer_list() { # port -> "ip:port,[v6]:port" from CS_EDGES
  local ip out=''
  for ip in ${CS_EDGES[@]+"${CS_EDGES[@]}"}; do
    [[ "$ip" == *:* ]] && ip="[$ip]"
    out="${out:+$out,}$ip:$1"
  done
  echo "$out"
}
cdn_scan_say() { # one summary line for the last cdn_scan
  if [ "$CS_REACH" -gt 0 ]; then ok "CF edges: $CS_REACH ECH / $CS_TOTAL reachable"
  elif [ "$CS_TOTAL" -gt 0 ]; then warn "CF edges: 0/$CS_TOTAL served ECH — using domain addresses"
  else warn "CF edges: 0 addresses accepted TCP"; fi
}
cdn_up_edges() { # metrics-port : the edge addresses the engine reports as up (/stats "edges": [{"addr":"ip:port","up":true}]), one per line
  curl -fs --noproxy '*' --max-time 3 "http://127.0.0.1:$1/stats" 2>/dev/null | grep -oE '"addr":"[^"]+","up":true' \
    | sed -E 's/^"addr":"//; s/","up":true$//; s/:[0-9]+$//; s/^\[//; s/\]$//'
}
cdn_ipv4hints() { # domain : the IPv4 addresses of its HTTPS record's ipv4hint, one per line (dig, else DoH JSON); silent on any failure
  local d=$1 s=''
  if command -v dig >/dev/null 2>&1; then
    s=$(timeout 4 dig +short +time=2 +tries=1 HTTPS "$d" 2>/dev/null | grep -io 'ipv4hint=[0-9.,]*')
  fi
  if [ -z "$s" ] && command -v curl >/dev/null 2>&1; then
    s=$(curl -fs --noproxy '*' --connect-timeout 2 --max-time 4 -k -H 'accept: application/dns-json' \
      "https://8.8.8.8/resolve?name=$d&type=HTTPS" 2>/dev/null | grep -io 'ipv4hint=[0-9.,]*')
  fi
  [ -n "$s" ] || return 0
  sed -E 's/^[^=]*=//' <<<"$s" | tr ',' '\n' | grep -E '^[0-9]{1,3}(\.[0-9]{1,3}){3}$' || true
  return 0
}
now_us() { if [ -n "${EPOCHREALTIME:-}" ]; then local t=${EPOCHREALTIME/[.,]/}; echo "$t"; else echo $(( $(date +%s%N) / 1000 )); fi; }
cdn_pick_edges() { # up to 3 of the ips given (already fastest first): one per /24 (v6: /48) when there are alternatives, then fill up
  local ip k out=() rest=(); local -A pf=()
  for ip in "$@"; do
    if [[ "$ip" == *:* ]]; then k=$(cut -d: -f1-3 <<<"$ip"); else k=${ip%.*}; fi
    if [ -z "${pf[$k]:-}" ] && [ "${#out[@]}" -lt 3 ]; then pf[$k]=1; out+=("$ip"); else rest+=("$ip"); fi
  done
  for ip in ${rest[@]+"${rest[@]}"}; do [ "${#out[@]}" -ge 3 ] && break; out+=("$ip"); done
  CS_EDGES=("${out[@]}")
}
cdn_scan() { # domain port path carrier : pick the Cloudflare edges that serve this domain, judged by the tunnel engine itself
  # -> CS_EDGES (best 3), CS_REACH_IPS (every edge that is up), CS_REACH (up) / CS_TOTAL (TCP-reachable) ; CS_FALLBACK=1 when none was
  # verified (CS_EDGES is then the domain's own addresses) ; rc 1 when there is nothing to choose from at all.
  # curl cannot do ECH, so it only pre-filters plain TCP reachability. A throw-away client with -fp chrome -ech auto and one pool
  # connection per candidate spreads over all of them; /stats then says which candidates really carried a connection.
  local dom=$1 port=$2 path=${3:-/} car=${4:-wss} ip n=0 v6=0 i own=() cand=() reach=() peers='' up='' mp pid t end a N
  local -A seen=() isup=() tcpms=()
  CS_EDGES=(); CS_REACH_IPS=(); CS_REACH=0; CS_TOTAL=0; CS_BEST_IP=''; CS_BEST_MS=0; CS_FALLBACK=0; CS_RAN=0
  [[ "$path" == /* ]] || path=/$path
  ipv4_ok "$dom" && return 1 # an IP address has no Cloudflare edges to choose from
  ip -6 route get 2606:4700::1 >/dev/null 2>&1 && v6=1 # DNS may return AAAA on a server without any v6 route
  # the HTTPS record's ipv4hint addresses come first: they are the edges the zone itself advertises to browsers
  for ip in $(cdn_ipv4hints "$dom"); do
    [ -n "${seen[$ip]:-}" ] || { seen[$ip]=1; own+=("$ip"); cand+=("$ip"); }
  done
  # then the domain's own A records: they are what Cloudflare hands out for this very zone
  for ip in $(getent ahostsv4 "$dom" 2>/dev/null | awk '{print $1}' | sort -u); do
    [ -n "${seen[$ip]:-}" ] || { seen[$ip]=1; own+=("$ip"); cand+=("$ip"); }
  done
  if [ "$v6" = 1 ]; then
    for ip in $(getent ahostsv6 "$dom" 2>/dev/null | awk '{print $1}' | grep -v -i '^::ffff:' | sort -u); do
      [ -n "${seen[$ip]:-}" ] || { seen[$ip]=1; own+=("$ip"); cand+=("$ip"); }
    done
  fi
  for ip in $CS_V4 $( [ "$v6" = 1 ] && echo "$CS_V6" ); do
    [ -n "${seen[$ip]:-}" ] || { seen[$ip]=1; cand+=("$ip"); }
  done
  CS_RAN=1
  CS_DIR=$(mktemp -d "${TMPDIR:-/tmp}/wattun-cdn.XXXXXX") || { CS_DIR=''; return 1; }
  # fast pre-filter: drop what cannot even open a TCP connection (any TLS / HTTP outcome is fine here)
  CS_PIDS=()
  for ip in "${cand[@]}"; do
    n=$((n+1))
    local hip=$ip
    [[ "$hip" == *:* ]] && hip="[$hip]" # bash /dev/tcp needs brackets for v6, else every AAAA fails the filter
    ( t0=$(now_us); timeout 2 bash -c "exec 3<>/dev/tcp/$hip/$port" 2>/dev/null && echo $(( $(now_us) - t0 )) >"$CS_DIR/$n" ) &
    CS_PIDS+=($!)
  done
  wait "${CS_PIDS[@]}" 2>/dev/null
  CS_PIDS=()
  n=0
  # fastest TCP connect first: that order decides which edges are kept
  for ip in "${cand[@]}"; do n=$((n+1)); [ -s "$CS_DIR/$n" ] && tcpms[$ip]=$(< "$CS_DIR/$n"); done
  while read -r _ ip; do [ -n "$ip" ] && reach+=("$ip"); done < <(for ip in "${!tcpms[@]}"; do echo "${tcpms[$ip]} $ip"; done | sort -n)
  rm -rf "$CS_DIR"; CS_DIR=''
  CS_TOTAL=${#reach[@]}
  if [ "$CS_TOTAL" -eq 0 ]; then # nothing answers on TCP (or the check itself is unreliable here): the domain's own addresses are the only guess
    [ "${#own[@]}" -gt 0 ] || return 1
    CS_FALLBACK=1; CS_EDGES=("${own[@]:0:3}"); [ "$CS_QUIET" = 1 ] || cdn_scan_say
    return 0
  fi
  [ "${#reach[@]}" -gt 24 ] && reach=("${reach[@]:0:24}")
  N=${#reach[@]}
  for ip in "${reach[@]}"; do
    [[ "$ip" == *:* ]] && ip="[$ip]"
    peers="${peers:+$peers,}$ip:$port"
  done
  if [ -n "${AT_DIR:-}" ] && [ -r "$AT_DIR/key" ] || { [ -n "${T_KEY:-}" ] && at_prep; }; then
    local dmap
    mp=$(at_free_port) || mp=''
    [ -n "$mp" ] && dmap=$(at_free_port $((mp + 1)) "$mp") || dmap=''
    if [ -n "$mp" ] && [ -n "$dmap" ]; then
    a=(-mode client -carrier "$car" -key-file "$AT_DIR/key" -peer "$peers" -metrics "127.0.0.1:$mp" -conns "$N"
       -path "$path" -sni "$dom" -host "$dom" -map "$dmap:1@127.0.0.1")
    case "$car" in wss|grpc|h2) a+=(-fp chrome -ech auto) ;; esac
    timeout -k 2 40 "$BIN" "${a[@]}" >"$AT_DIR/scan.log" 2>&1 &
    AT_PID=$!
    end=$((SECONDS + 12))
    while [ "$SECONDS" -lt "$end" ]; do
      sleep 1
      up=$(cdn_up_edges "$mp"); [ -n "$up" ] && [ "$(wc -l <<<"$up")" -ge "$N" ] && break
    done
    up=$(cdn_up_edges "$mp")
    at_kill
    for ip in $up; do isup[$ip]=1; done
    for ip in "${reach[@]}"; do [ -n "${isup[$ip]:-}" ] && CS_REACH_IPS+=("$ip"); done
    fi
  fi
  CS_REACH=${#CS_REACH_IPS[@]}
  if [ "$CS_REACH" -gt 0 ]; then
    cdn_pick_edges "${CS_REACH_IPS[@]}"; CS_BEST_IP=${CS_EDGES[0]}; CS_BEST_MS=$(( ${tcpms[$CS_BEST_IP]:-0} / 1000 ))
  else
    CS_FALLBACK=1
    if [ "${#own[@]}" -gt 0 ]; then CS_EDGES=("${own[@]:0:3}"); else CS_EDGES=("${reach[@]:0:3}"); fi
  fi
  [ "$CS_QUIET" = 1 ] || cdn_scan_say
  return 0
}

at_prep() { # temp dir and key file for the throw-away clients (needs T_KEY)
  AT_DIR=$AUTO_RUN/t.$$
  mkdir -p "$AUTO_RUN" && chmod 700 "$AUTO_RUN" && rm -rf "$AT_DIR" && mkdir -p "$AT_DIR" || return 1
  ( umask 077; printf '%s\n' "$T_KEY" >"$AT_DIR/key" )
}
at_score() { awk -v d="${AR_DOWN[$1]:-0}" -v u="${AR_UP[$1]:-0}" 'BEGIN{printf "%.6f", d+u}'; } # i -> down+up
at_best_score() { # best down+up of everything tested so far
  local i b=0
  for ((i=0; i<${#AV_LABEL[@]}; i++)); do
    [ "${AR_OK[$i]:-0}" = 1 ] || continue
    b=$(awk -v a="$b" -v c="$(at_score "$i")" 'BEGIN{print (c>a)?c:a}')
  done
  echo "$b"
}
at_near_best() { awk -v s="$(at_score "$1")" -v b="$(at_best_score)" 'BEGIN{exit !(s>=b*0.9)}'; } # i within 10% of the best seen
at_cdn_lines() { # i -> the fp / ech / tls-frag config lines of variant i
  local i=$1
  [ -n "${AV_FP[$i]:-}" ] && [ "${AV_FP[$i]}" != go ] && echo "fp: ${AV_FP[$i]}"
  [ -n "${AV_ECH[$i]:-}" ] && [ "${AV_ECH[$i]}" != off ] && echo "ech: ${AV_ECH[$i]}"
  [ -n "${AV_FRAG[$i]:-}" ] && [ "${AV_FRAG[$i]}" != 0 ] && echo "tls-frag: ${AV_FRAG[$i]}"
  return 0
}
cdn_desc() { # i -> "chrome fingerprint, 3 Cloudflare edges"
  local i=$1 out='' n h=${AV_PEER[$1]%%,*}
  add() { out="${out:+$out, }$1"; }
  [ -n "${AV_FP[$i]:-}" ] && [ "${AV_FP[$i]}" != go ] && add "${AV_FP[$i]} fingerprint"
  [ -n "${AV_ECH[$i]:-}" ] && [ "${AV_ECH[$i]}" != off ] && add "ECH (hidden domain)"
  [ -n "${AV_FRAG[$i]:-}" ] && [ "${AV_FRAG[$i]}" != 0 ] && add "${AV_FRAG[$i]}-byte TLS fragments"
  if [[ "$h" == \[* ]] || [[ "${h%%:*}" =~ ^[0-9.]+$ ]]; then
    n=$(awk -F, '{print NF}' <<<"${AV_PEER[$i]}"); add "$n Cloudflare edge$([ "$n" -gt 1 ] && echo s)"
  fi
  echo "${out:-default settings}"
}
cdn_try() { # carrier label peer fp ech tls-frag : add a CDN variant, test it, print the result ; its index -> CT_I
  local i
  av_add "$2" "$1" c "$3" '' "$T_SNI" "$4" "$5" "$6"
  i=$((${#AV_LABEL[@]}-1)); CT_I=$i
  [ "$AT_QUIET" = 1 ] || at_busy "$2"
  at_probe "$i" "$CT_W"
  [ "$AT_QUIET" = 1 ] || { at_idle; at_print "$i"; }
  return 0
}
cdn_variants() { # carrier edge-peer default-peer [skip-ech] : TLS variants in preference order: chrome+ech, chrome, go; frag only when all failed
  local car=$1 pa=$2 pd=$3 skip=${4:-0} any=0 eok=0 i
  if [ "$skip" = 1 ]; then eok=${AR_OK[$CT_I]:-0}
  else
    # ECH is the variant that works against an SNI filter (field result: every non-ECH variant failed through Cloudflare from Iran)
    CT_W=12; cdn_try "$car" "$car · chrome+ech" "$pa" chrome auto ''; CT_W=8
    eok=${AR_OK[$CT_I]}
  fi
  [ "$eok" = 1 ] && any=1
  # chrome+ech works: nothing further to test, unless "full"
  [ "$eok" = 1 ] && [ "$AT_FULL" != 1 ] && return 0
  cdn_try "$car" "$car · chrome" "$pa" chrome '' ''; [ "${AR_OK[$CT_I]}" = 1 ] && any=1
  cdn_try "$car" "$car · go" "$pd" '' '' '';          [ "${AR_OK[$CT_I]}" = 1 ] && any=1
  # the ClientHello cut comes after the handshake, so it rarely helps against an SNI filter: last resort only
  if [ "$any" != 1 ]; then cdn_try "$car" "$car · frag" "$pa" chrome '' 100
  elif [ "$AT_FULL" = 1 ]; then cdn_try "$car" "$car · frag (diagnostic)" "$pa" chrome '' 100; fi
  return 0
}
cdn_auto_extras() { # Auto: after (a) chrome+ech of each CDN carrier: the remaining variants only when (a) failed (or full)
  local i car port list=()
  for ((i=0; i<${#AV_LABEL[@]}; i++)); do [ "${AV_KIND[$i]}" = c ] && list+=("$i"); done
  for i in "${list[@]}"; do
    [ "$AT_FULL" = 1 ] || [ "${AR_OK[$i]}" != 1 ] || continue
    car=${AV_CAR[$i]}; port=${AV_PEER[$i]%%,*}; port=${port##*:}
    CT_I=$i
    cdn_variants "$car" "${AV_PEER[$i]}" "$T_SNI:$port" 1
  done
  return 0
}
cdn_tune() { # [full] : needs T_CARRIER T_PEER T_KEY T_PATH T_SNI (the domain), AT_QUIET, AT_MB ; fills AV_*, AR_*, CT_IDX ; rc 1 = could not start
  local car=$T_CARRIER port pa pd label a t0=$SECONDS i
  AT_FULL=${1:-0}
  AV_LABEL=(); AV_CAR=(); AV_KIND=(); AV_PEER=(); AV_PORT=(); AV_SNI=(); AV_FP=(); AV_ECH=(); AV_FRAG=()
  AV_FS=(); AV_FM=(); AV_X=()
  AR_OK=(); AR_DOWN=(); AR_UP=(); AR_RTT=(); AR_WHY=(); CT_IDX=''
  port=${T_PEER%%,*}; port=${port##*:}
  pd=$T_PEER; case "$pd" in *,*) pd="$T_SNI:$port" ;; esac
  [ "$car" = h2 ] && [ "$AT_QUIET" != 1 ] && hint "h2 does not work through Cloudflare; use grpc or wss"
  if [ "$AT_FULL" = 1 ] && [ "$AT_QUIET" != 1 ]; then # the Kharej tunnel runs one carrier; say what the other CDN carrier would have been
    case "$car" in wss) hint "grpc: not offered by this exit tunnel" ;; grpc) hint "wss: not offered by this exit tunnel" ;; esac
  fi
  at_prep || return 1
  [ "$AT_QUIET" = 1 ] || at_busy "Cloudflare edges"
  CS_QUIET=1; cdn_scan "$T_SNI" "$port" "${T_PATH:-/wat}" "$car"
  [ "$AT_QUIET" = 1 ] || { at_idle; [ "$CS_RAN" = 1 ] && cdn_scan_say; echo; }
  pa=$pd; label=$car
  if [ "${#CS_EDGES[@]}" -gt 0 ]; then pa=$(cdn_peer_list "$port"); label="$car · ${#CS_EDGES[@]} edges"; fi
  case "$car" in
    wss|grpc|h2) cdn_variants "$car" "$pa" "$pd" 0 ;;
    *) # plain ws / h2c only get the edge choice; the default is tried only when that failed
      cdn_try "$car" "$label" "$pa" '' '' ''
      [ "${AR_OK[$CT_I]}" = 1 ] || cdn_try "$car" "$car · default" "$pd" '' '' '' ;;
  esac
  at_cleanup
  at_rank; AT_SECS=$((SECONDS-t0))
  for i in ${AT_RANK[@]+"${AT_RANK[@]}"}; do [[ "${AV_LABEL[$i]}" == *"(diagnostic)" ]] && continue; CT_IDX=$i; break; done # the diagnostic row is never chosen
  return 0
}
cdn_take() { # the best variant (CT_IDX) -> T_PEER, T_SNI, AT_EXTRA, CT_DESC
  T_PEER=${AV_PEER[$CT_IDX]}; T_SNI=${AV_SNI[$CT_IDX]}
  AT_EXTRA=$(at_cdn_lines "$CT_IDX"); CT_DESC=$(cdn_desc "$CT_IDX")
}
cdn_result_line() { printf 'Best: %s, %.1f/%.1f MB/s' "$(cdn_desc "$CT_IDX")" "${AR_DOWN[$CT_IDX]:-0}" "${AR_UP[$CT_IDX]:-0}"; }
cdn_wizard_tune() { # Iran wizard, token accepted: CDN carrier + domain + wattun >= 2.2.0 -> best edges and TLS settings, no questions
  local dom sni0=$T_SNI
  [ "$T_REV" = 1 ] && return 0
  is_cdn_carrier "$T_CARRIER" && cdn_ok || return 0
  dom=$(cdn_domain); [ -n "$dom" ] || return 0
  T_SNI=$dom
  echo
  [ "$T_CARRIER" = h2 ] && hint "h2 does not work through Cloudflare — use grpc or wss"
  AT_QUIET=1; AT_MB=20; AT_NOTE=''; AT_SKIP=''
  at_busy "Cloudflare edges ($dom)"
  cdn_tune 0
  at_idle
  if [ -n "$CT_IDX" ]; then
    [ "$CS_RAN" = 1 ] && cdn_scan_say
    [ "$NONINTERACTIVE" = 1 ] && at_table
    cdn_take; ok "$(cdn_result_line)"
  else
    T_SNI=$sni0
    warn "CDN tuning found no working edge — keeping token settings"
  fi
  return 0
}
cdn_apply() { # name : write T_PEER, T_SNI and AT_EXTRA (fp / ech / tls-frag) into NAME.yml and restart
  local n=$1 l k v
  sed -i -E '/^(peer|fp|ech|ech-cache|tls-frag):/d' "$CONF/$n.yml"
  set_value "$n" peer "$T_PEER"
  [ -n "$(cfg "$n" sni)" ] || set_value "$n" sni "$T_SNI"
  [ -n "$(cfg "$n" host)" ] || set_value "$n" host "$T_SNI"
  while IFS= read -r l; do
    [ -n "$l" ] || continue
    k=${l%%: *}; v=${l#*: }; set_value "$n" "$k" "$v"
  done <<<"$AT_EXTRA"
  l=$(ech_cache_line "$n"); if [ -n "$l" ]; then set_value "$n" ech-cache "${l#*: }"; fi
  if [ "$AT_QUIET" = 1 ]; then systemctl restart "${WAT_PREFIX}@$n" >/dev/null 2>&1; return 0; fi
  step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
  if wait_link "$n" 25; then ok "CONNECTED (RTT ${LINK_RTT} ms)"; else warn "Not connected yet."; [ "$NONINTERACTIVE" = 1 ] && return 1; fi
  return 0
}
cdn_load_t() { # name -> T_CARRIER T_PEER T_KEY T_PATH T_SNI from NAME.yml ; rc 1 when it is not a CDN tunnel
  local n=$1 kf
  cdn_tunnel_p "$n" || return 1
  kf=$(cfg "$n" key-file); [ -r "$kf" ] || kf="$CONF/$n.key"
  T_CARRIER=$(cfg "$n" carrier); T_PEER=$(cfg "$n" peer); T_PATH=$(cfg "$n" path); T_REV=''; T_ICMP=''
  T_SNI=$(cfg "$n" sni); [ -n "$T_SNI" ] || T_SNI=$(cfg "$n" host)
  T_KEY=''; { IFS= read -r T_KEY <"$kf"; } 2>/dev/null
  [ -n "$T_KEY" ]
}
cdn_tune_cmd() { # name [full] : re-run the CDN tuning for an Iran CDN tunnel, show the table, apply the best
  local n=$1 full=0 cur new
  [ "${2:-}" = full ] && full=1
  cdn_ok || { err "CDN tuning needs wattun $CDN_MINVER or newer (this is $(bin_ver)). Run: $SELF update"; return 1; }
  cdn_load_t "$n" || { err "'$n' is not an entry tunnel on a CDN carrier (ws, wss, h2, h2c, grpc) with a domain."; return 1; }
  cur=$(cfg "$n" peer)/$(cfg "$n" fp)/$(cfg "$n" ech)/$(cfg "$n" tls-frag)
  page "CDN tune" "$n"
  hint "Testing from this server. The running tunnel is not touched until you confirm."
  echo
  AT_QUIET=0; AT_MB=20; AT_NOTE=''; AT_SKIP=''; AT_AGAIN=''
  cdn_tune "$full" || { err "Could not prepare the test (is $AUTO_RUN writable?)."; return 1; }
  if [ -z "$CT_IDX" ]; then
    echo; err "No CDN variant got a working link from this server. Nothing was changed."
    hint "Check that the exit tunnel is running and the domain is proxied by Cloudflare."
    return 1
  fi
  at_table
  echo
  ok "$(cdn_result_line)"
  cdn_take
  new=$T_PEER/$(sed -n 's/^fp: //p' <<<"$AT_EXTRA")/$(sed -n 's/^ech: //p' <<<"$AT_EXTRA")/$(sed -n 's/^tls-frag: //p' <<<"$AT_EXTRA")
  if [ "$new" = "$cur" ]; then ok "'$n' already uses these settings."; return 0; fi
  # same TLS settings and only the edge list differs: keep the running tunnel if every edge it uses is still up
  # (a restart drops every open connection; edge order varies between scans)
  if [ "${new#*/}" = "${cur#*/}" ]; then
    local st; st=$(stats "$n" 2>/dev/null)
    if grep -q '"edges"' <<<"$st" && ! grep -q '"up": *false' <<<"$st"; then
      ok "'$n' already uses these settings and all its Cloudflare edges are up; not restarting."; return 0
    fi
  fi
  confirm "Apply to '$n'? (restarts the tunnel, open connections drop)" y || { warn "No change."; return 0; }
  cdn_apply "$n"
}
cdn_refresh_edges() { # name : unattended (auto-heal): same scan as cdn-tune (the engine tells which edges serve the domain over ECH), replace dead edge IPs, restart
  local n=$1 peer port dom c cur h bad=0 new
  cdn_ok && cdn_tunnel_p "$n" || return 0
  peer=$(cfg "$n" peer); c=$(cfg "$n" carrier)
  h=${peer%%,*}; h=${h%:*}; h=${h#[}; h=${h%]}
  [[ "$h" == *[A-Za-z]* ]] && [[ "$h" != *:* ]] && return 0 # plain domain: Cloudflare DNS already hands out live edges
  cdn_load_t "$n" || return 0
  dom=$T_SNI
  port=${peer%%,*}; port=${port##*:}
  AT_QUIET=1; CS_QUIET=1
  at_prep || return 0
  if ! cdn_scan "$dom" "$port" "$(cfg "$n" path)" "$c"; then
    at_cleanup; logger -t wattun-heal "cdn scan for $n: no Cloudflare edge to choose from"; return 0
  fi
  at_cleanup
  if [ "$CS_FALLBACK" = 1 ]; then logger -t wattun-heal "cdn scan for $n: no edge served the domain over ECH right now, peer left as is"; return 0; fi
  for cur in ${peer//,/ }; do
    h=${cur%:*}; h=${h#[}; h=${h%]}
    [[ " ${CS_REACH_IPS[*]} " == *" $h "* ]] || bad=1
  done
  [ "$bad" = 1 ] || { logger -t wattun-heal "cdn scan for $n: all edges still serve the domain"; return 0; }
  new=$(cdn_peer_list "$port")
  logger -t wattun-heal "cdn scan for $n: replacing dead edges, peer is now $new"
  set_value "$n" peer "$new" 2>/dev/null
  systemctl restart "${WAT_PREFIX}@$n" >/dev/null 2>&1
  return 0
}
# short CDN settings of an Iran tunnel: "wss · chrome · 3 edges" (second argument "short": "chrome · 3 edges"); nothing when default
cdn_summary() { # name [short]
  local n=$1 c fp ech fr peer cnt out=''
  cdn_tunnel_p "$n" || return 0
  c=$(cfg "$n" carrier); fp=$(cfg "$n" fp); ech=$(cfg "$n" ech); fr=$(cfg "$n" tls-frag); peer=$(cfg "$n" peer)
  cnt=$(awk -F, '{print NF}' <<<"$peer")
  [ -n "$fp" ] && [ "$fp" != go ] && out="$fp"
  [ -n "$ech" ] && [ "$ech" != off ] && out="${out:+$out · }ech"
  [ -n "$fr" ] && [ "$fr" != 0 ] && out="${out:+$out · }frag $fr"
  [ "$cnt" -gt 1 ] && out="${out:+$out · }$cnt edges"
  [ -n "$out" ] || return 0
  if [ "${2:-}" = short ]; then echo "$out"; else echo "$c · $out"; fi
}

server_side() { # -> kharej | iran | nothing: saved at install (or the first tunnel), else read from the tunnels here
  local s n k=0 i=0
  s=$(conf_get side '')
  case "$s" in kharej|iran) echo "$s"; return 0 ;; esac
  for n in $(tunnels); do [ -n "$(companion_of "$n")" ] && continue; [ "$(role "$n")" = Kharej ] && k=1 || i=1; done
  [ "$k$i" = 10 ] && echo kharej
  [ "$k$i" = 01 ] && echo iran
  return 0
}
ask_side() { # -> SIDE kharej|iran, saved ; rc 1 = back
  page "Server role"
  printf '  %s Kharej  %soutside server (runs service, makes token)%s\n' "$(key_label 1)" "$GRY" "$RST"
  printf '  %s Iran    %sinside server (users connect here)%s\n' "$(key_label 2)" "$GRY" "$RST"
  echo
  printf '  %s?%s Role %s[1/2, b back]%s ' "$CYN" "$RST" "$GRY" "$RST"
  key_read; echo
  case "$KEY" in 1|k|K) SIDE=kharej ;; 2|i|I) SIDE=iran ;; *) return 1 ;; esac
  conf_set side "$SIDE"
}
new_tunnel() { # [kharej|iran]
  local pick=${1:-}
  [ -z "$pick" ] && pick=$(server_side)
  if [ -z "$pick" ]; then ask_side || return 0; pick=$SIDE; fi
  local rc=0
  case "$pick" in
    kharej) run_flow wizard_kharej; rc=$? ;;
    iran) run_flow wizard_iran; rc=$? ;;
    *) err "Unknown role '$pick' (use kharej or iran)."; return 1 ;;
  esac
  [ "$rc" -eq 130 ] || pause
  return 0
}

# ======================================================================================
#  Diagnosis, speed test, logs
# ======================================================================================
# ICMP path check (Iran side, icmp carrier): ping the Kharej at four packet sizes and read the tunnel's own packet
# counters, then say which cause fits. Uses plain ping, so it needs nothing installed on Kharej.
# Does this server itself block ICMP? Looks at the kernel switch and the local firewall rules (iptables, nftables).
# It cannot see a firewall in the provider's cloud panel. Prints one warning per finding; returns 0 when it found one.
# Does this iptables/nft rule line touch ICMP the tunnel uses? $1 = rule, $2 = space-padded list of type numbers in use.
# True when the rule has no type restriction or names a type in use; false for icmpv6 and unrelated types (time-exceeded...).
icmp_rule_hits() {
  local l=$1 used=$2 toks tok n
  case "$l" in *icmpv6*|*ipv6-icmp*) return 1 ;; esac
  case "$l" in *'! --icmp-type'*|*'icmp type !='*) return 0 ;; esac
  if [[ "$l" =~ --icmp-type[[:space:]]+([^[:space:]]+) ]]; then toks=${BASH_REMATCH[1]}
  elif [[ "$l" =~ icmp[[:space:]]+type[[:space:]]+(\{[^}]*\}|[^[:space:]]+) ]]; then toks=${BASH_REMATCH[1]}
  else return 0; fi
  toks=${toks//[\{\},]/ }
  for tok in $toks; do
    tok=${tok%%/*}
    case "$tok" in
      echo-reply|pong) n=0 ;; echo-request|ping) n=8 ;;
      timestamp-request) n=13 ;; timestamp-reply) n=14 ;;
      info-request) n=15 ;; info-reply) n=16 ;;
      address-mask-request) n=17 ;; address-mask-reply) n=18 ;;
      any) return 0 ;;
      *[!0-9]*) n=x ;; *) n=$tok ;;
    esac
    case "$used" in *" $n "*) return 0 ;; esac
  done
  return 1
}
local_icmp_check() { # [reverse-iran|-] [icmp-type] : icmp_echo_ignore_all does not stop the tunnel itself, only ping checks
  local found=1 rules hits l used=' 0 8 '
  case "${2:-echo}" in timestamp) used=' 0 8 13 14 ' ;; info) used=' 0 8 15 16 ' ;; mask) used=' 0 8 17 18 ' ;; esac
  if [ "${1:-}" != reverse-iran ] && [ "$(sysctl -n net.ipv4.icmp_echo_ignore_all 2>/dev/null)" = 1 ]; then
    hint "This server ignores plain ping (icmp_echo_ignore_all=1). The tunnel still works; only ping-based checks go unanswered."
  fi
  if command -v iptables >/dev/null 2>&1; then
    rules=$(iptables -S 2>/dev/null | grep -i icmp | grep -E -- '-j (DROP|REJECT)'); hits=''
    while IFS= read -r l; do [ -n "$l" ] && icmp_rule_hits "$l" "$used" && hits+="$l"$'\n'; done <<<"$rules"
    if [ -n "$hits" ]; then warn "iptables has ICMP rules that drop or reject:"; printf '%s' "$hits" | sed "s/^/        $GRY/; s/\$/$RST/"; found=0; fi
    if iptables -S INPUT 2>/dev/null | grep -q -- '-P INPUT DROP' && ! iptables -S INPUT 2>/dev/null | grep -qi icmp; then
      warn "iptables INPUT drops everything not allowed, and no ICMP rule exists."; found=0
    fi
  fi
  if command -v nft >/dev/null 2>&1; then
    rules=$(nft list ruleset 2>/dev/null | grep -i icmp | grep -Ei 'drop|reject'); hits=''
    while IFS= read -r l; do [ -n "$l" ] && icmp_rule_hits "$l" "$used" && hits+="$l"$'\n'; done <<<"$rules"
    if [ -n "$hits" ]; then warn "nftables has ICMP rules that drop or reject:"; printf '%s' "$hits" | sed "s/^/        $GRY/; s/\$/$RST/"; found=0; fi
  fi
  return $found
}

icmp_path_report() { # name host
  local n=$1 host=$2 s sz loss ok_sizes='' bad_sizes='' maxok=0 pin pout ign fw
  sec_hdr "ICMP path" "$host"
  for sz in 56 200 400 640; do
    spin_start "ping $sz bytes"
    loss=$(ping -c 4 -i 0.3 -W 2 -q -M do -s "$sz" "$host" 2>/dev/null | grep -o '[0-9]*% packet loss' | grep -o '^[0-9]*')
    spin_stop
    [ -n "$loss" ] || loss=100
    if [ "$loss" -le 25 ]; then ok_sizes="$ok_sizes $sz"; maxok=$sz; ok "$sz B   loss ${loss}%"
    else bad_sizes="$bad_sizes $sz"; err "$sz B   no answer (${loss}% loss)"; fi
  done
  s=$(stats_flat "$n"); pin=$(jget "$s" pkts_in); pout=$(jget "$s" pkts_out); pin=${pin:-0}; pout=${pout:-0}
  local_icmp_check - "$(cfg "$n" icmp-type)"
  sec_hdr "Diagnosis"
  if [ -z "$ok_sizes" ]; then
    err "The exit server drops ping at every size"
    hint " · Allow ICMP in the exit server's cloud firewall (or wait if route blocks ICMP)"
    hint " · One-way block? Test from the exit server; switch both sides to reverse ICMP (Adv -> d)"
  elif [ -n "$bad_sizes" ] && [ "$maxok" -lt 256 ]; then
    err "Max ICMP size ~$maxok B (below tunnel 256 B minimum)"
    hint " · Switch both sides to another carrier (udp, tcp, wss)"
  elif [ -n "$bad_sizes" ] && [ "$maxok" -lt 640 ]; then
    err "Path drops ICMP > ~$maxok B"
    hint " · Set  mtu: $maxok  in $CONF/<name>.yml on both sides and restart"
  elif [ "$pout" -gt 0 ] && [ "$pin" -eq 0 ]; then
    err "Ping passes, tunnel packets get no reply"
    hint " · Re-paste the exit token (key/icmp-type check) or try icmp-type: timestamp"
    hint " · Otherwise switch carrier (udp, tcp, wss)"
  elif [ "$pin" -gt 0 ]; then
    warn "Ping passes; tunnel went silent recently (auto-heal retries)"
  else
    ok "ICMP path is open — verify key and carrier match on both ends"
  fi
}

test_tunnel() {
  local n=$1 cr peer host port s p r it e pl
  cr=$(cfg "$n" carrier); peer=$(cfg "$n" peer); r=$(role "$n")
  page "Doctor" "$n ($r · $cr)"
  sec_hdr "Checks"
  # ptcp leftover rules (P4, 2026-11-21): every rule the ptcp carrier inserts is comment-tagged wattun-ptcp;
  # a live ptcp unit owns them, anything else means orphans from a crash. Report only — never auto-delete.
  if [ "$cr" != ptcp ] || ! systemctl is-active -q "${WAT_PREFIX}@$n"; then
    pl=$(iptables -w -S OUTPUT 2>/dev/null | grep wattun-ptcp || true)
    if [ -n "$pl" ]; then
      warn "iptables has leftover wattun-ptcp rule(s) (a crashed/stopped ptcp tunnel):"
      printf '        %s%s%s\n' "$GRY" "$pl" "$RST"
      hint " · Restart a ptcp tunnel (the next start re-owns and refreshes them) or delete each by re-running it with -D"
    fi
  fi
  if systemctl is-active -q "${WAT_PREFIX}@$n"; then ok "Service     running (${WAT_PREFIX}@$n)"
  else err "Service     stopped"; journalctl -u "${WAT_PREFIX}@$n" -n 10 --no-pager -o cat 2>/dev/null; return; fi
  if [ "$r" = Iran ]; then
    host=${peer%:*}; port=${peer##*:}; [ "$host" = "$peer" ] && port=''
    if [ "$cr" = icmp ] && is_reverse "$n"; then
      hint " · Reverse ICMP: the exit server pings this server — run Doctor on the exit server"
    elif [ "$cr" = icmp ]; then
      spin_start "Pinging $host"
      ping -c 3 -W 2 -q "$host" >/dev/null 2>&1; e=$?
      spin_stop
      if [ "$e" -eq 0 ]; then ok "Ping        $host reachable"
      else err "Ping        $host unreachable (ICMP blocked or dropped)"; fi
    elif is_rpool "$cr" && is_reverse "$n"; then
      port=$(cfg "$n" listen); port=${port##*:}
      if [ -n "$port" ] && port_busy "$port" "$(rproto "$cr")"; then ok "Listen      :$port/$(rproto "$cr") open"
      else err "Listen      :${port:--}/$(rproto "$cr") not listening"; fi
    elif is_pool "$cr" && [ -n "$port" ]; then
      spin_start "Probing $host:$port"
      timeout 4 bash -c "</dev/tcp/$host/$port" 2>/dev/null; e=$?
      spin_stop
      if [ "$e" -eq 0 ]; then ok "TCP         $host:$port open"
      else err "TCP         $host:$port closed or filtered"; fi
    elif is_shaped_udp "$cr" && [ -n "$port" ]; then
      hint " · $cr (UDP shape): verify $port/udp firewall & logs on both ends"
    fi
  fi
  if [[ "$cr" == *"+"* ]]; then
    local -a car_list
    IFS='+' read -ra car_list <<<"$cr"
    local c_idx=0 cp cpeer chost cport
    for cp in "${car_list[@]}"; do
      c_idx=$((c_idx+1))
      cpeer=$(cfg "$n" "peer-$cp")
      [ -z "$cpeer" ] && cpeer=$peer
      chost=${cpeer%:*}; cport=${cpeer##*:}
      printf '    %s%d%s %-6s ' "$GRY" "$c_idx" "$RST" "$cp"
      if [ "$r" = Iran ]; then
        if [ "$cp" = icmp ]; then
          if ping -c 1 -W 2 -q "$chost" >/dev/null 2>&1; then printf '%s✔ ping ok%s\n' "$GRN" "$RST"
          else printf '%s✘ ping fails%s\n' "$RED" "$RST"; fi
        elif is_pool "$cp" && [ -n "$cport" ]; then
          if timeout 3 bash -c "</dev/tcp/$chost/$cport" 2>/dev/null; then printf '%s✔ tcp %s:%s open%s\n' "$GRN" "$chost" "$cport" "$RST"
          else printf '%s✘ tcp %s:%s closed/filtered%s\n' "$RED" "$chost" "$cport" "$RST"; fi
        else
          printf '%sconfigured%s\n' "$GRY" "$RST"
        fi
      else
        printf '%sactive%s\n' "$GRY" "$RST"
      fi
    done
  fi
  s=$(stats "$n")
  if [ "$(jget "$s" alive)" = true ]; then
    ok "Link        CONNECTED · RTT $(ms "$(jget_flat "$s" rtt_ms srtt_ms)") ms"
    parse_carriers "$s"
    if [ "$CAR_COUNT" -gt 0 ]; then
      sec_hdr "Live paths"
      local ci ccol cdot ctxt c_pct
      for ((ci=0; ci<CAR_COUNT; ci++)); do
        [ "${CAR_ALIVE[$ci]}" = true ] && { ccol=$GRN; cdot='●'; ctxt="up"; } || { ccol=$RED; cdot='○'; ctxt="down"; }
        [ "${CAR_MUTED[$ci]}" = true ] && { ccol=$GRY; cdot='◌'; ctxt="muted"; }
        c_pct=$(awk -v sh="${CAR_SHARE[$ci]:-0}" 'BEGIN{printf "%.0f", sh*100}')
        printf '  %s%s %-6s%s %-8s %4.0f ms  loss %4.1f%%  share %3s%%  %s\n' \
          "$ccol" "$cdot" "$ctxt" "$RST" "${CAR_NAME[$ci]}" "${CAR_RTT[$ci]}" "$(awk -v l="${CAR_LOSS[$ci]:-0}" 'BEGIN{printf "%.1f", l*100}')" "$c_pct" "$(tbar "$c_pct" 100 10)"
      done
    fi
  else
    if [ "$r" = Kharej ]; then err "Link        no entry server client connected"; else err "Link        DISCONNECTED"; fi
    hint " · Key/carrier mismatch -> re-paste the exit token"
    hint " · Peer down or port blocked -> check the exit server status & firewall"
    hint " · Route filtered -> run auto-test or blackout"
    if [ "$r" = Iran ] && is_pool "$cr" && ! is_reverse "$n" && [ -n "$host" ] && [ -n "$port" ] \
       && timeout 4 bash -c "</dev/tcp/$host/$port" 2>/dev/null; then
      echo
      warn "TCP open but handshake fails (likely SNI allowlist)"
      hint " · Fix: $SELF blackout $n mci.ir  (or tunnel page -> z)"
    fi
  fi
  if [ "$r" = Iran ] && [ "$cr" = icmp ] && [ "$(jget "$s" alive)" != true ]; then
    if is_reverse "$n"; then
      sec_hdr "Local ICMP"
      if local_icmp_check reverse-iran "$(cfg "$n" icmp-type)"; then hint " · Fix rule above so the exit server pings reach this host"
      else ok "Local firewall allows ICMP"; fi
    else icmp_path_report "$n" "${peer%:*}"; fi
  fi
  if [ "$r" = Kharej ] && [ "$(jget "$s" alive)" != true ]; then
    local seen idle
    seen=$(journalctl -u "${WAT_PREFIX}@$n" --since "-6 hours" --no-pager -o cat 2>/dev/null | grep -c 'new client session')
    idle=$(journalctl -u "${WAT_PREFIX}@$n" --since "-6 hours" --no-pager -o cat 2>/dev/null | grep -c 'idle, closing')
    echo
    if [ "$seen" -gt 0 ]; then
      warn "Entry server connected $seen time(s) in 6h, went idle $idle time(s) (return path blocked?)"
    else
      warn "No entry server connection in the last 6h"
      if is_rpool "$cr" && is_reverse "$n"; then
        hint " · Verify the entry server listens on :${peer##*:}/$(rproto "$cr") and firewall allows it"
      else
        hint " · Verify key, carrier, and open port/ICMP in cloud firewall"
      fi
    fi
    if is_pool "$cr" && is_reverse "$n" && [ "$peer" != "${peer%:*}" ]; then
      host=${peer%:*}; port=${peer##*:}
      echo
      spin_start "Probing $host:$port"
      timeout 4 bash -c "</dev/tcp/$host/$port" 2>/dev/null; e=$?
      spin_stop
      if [ "$e" -eq 0 ]; then ok "Reverse TCP $host:$port reachable"
      else err "Reverse TCP $host:$port unreachable from exit server"; fi
    fi
    if [ "$cr" = icmp ]; then
      sec_hdr "Local ICMP"
      if local_icmp_check - "$(cfg "$n" icmp-type)"; then
        hint " · Fix rule above and retest"
      else
        ok "Local firewall allows ICMP (check cloud panel too)"
      fi
      REPLY_V=''
      if is_reverse "$n"; then REPLY_V=$peer
      elif [ -t 0 ]; then echo; ask "The entry IP to ping (Enter = skip)" ""; fi
      if [ -n "$REPLY_V" ]; then
        spin_start "Pinging $REPLY_V"
        ping -c 3 -W 2 -q "$REPLY_V" >/dev/null 2>&1; e=$?
        spin_stop
        if [ "$e" -eq 0 ]; then ok "Exit server -> the entry server ping ok ($REPLY_V)"
        else err "Exit server -> the entry server ping failed ($REPLY_V)"; fi
        if is_reverse "$n"; then
          [ "$e" -eq 0 ] && hint " · Check reverse: true, key, and icmp-type on the entry server"
          [ "$e" -ne 0 ] && hint " · Reverse requires the exit server -> the entry server ping (check the entry firewall)"
        else
          [ "$e" -eq 0 ] && hint " · If the entry server -> the exit server fails while this passes, use reverse ICMP (Adv -> d)"
        fi
      fi
    fi
  fi
  if kreply_wanted "$n" && kreply_needed; then
    echo; warn "Kernel replies to every ICMP echo (wasted upload)"
    if [ -t 0 ]; then kreply_offer; else hint " · Run $SELF on this server to suppress kernel ICMP replies"; fi
  fi
  while IFS= read -r it; do
    [ -n "$it" ] || continue
    if [ "$r" = Iran ]; then
      p=$(spec_L "$it")
      if port_busy "$p" "$(spec_P "$it")"; then ok "Port :$p/$(spec_P "$it")  listening"
      else warn "Port :$p/$(spec_P "$it")  not listening"; fi
    else
      p=$(spec_T "$it"); [ "$(spec_P "$it")" = udp ] && continue
      if timeout 2 bash -c "</dev/tcp/127.0.0.1/$p" 2>/dev/null; then ok "Target 127.0.0.1:$p  answers"
      else warn "Target 127.0.0.1:$p  not answering"; fi
    fi
  done < <(yml_maps "$n")
  if [ "$r" = Iran ] && [ "$(jget "$s" alive)" = true ]; then speed_test "$n"
  elif [ "$r" = Kharej ]; then hint " · Speed test runs on the entry server (press [v] there)"; fi
  e=$(journalctl -u "${WAT_PREFIX}@$n" -n 200 --no-pager -o cat 2>/dev/null | grep -iE "error|fail|denied|refused|restart needed" | tail -5)
  [ -n "$e" ] && { sec_hdr "Recent log errors"; printf '%s\n' "$e" | sed "s/^/  $GRY/; s/\$/$RST/"; }
  return 0
}

# 10 MB each way through the live tunnel (wattun >= 1.8.1 on both sides; uses /speedtest on the local metrics address).
# Only the client process registers /speedtest (it opens the test streams), so this runs on Iran only: on Kharej
# (the server, reverse included) there is nothing to call, and an empty answer there is not an old-version problem.
speed_test() { # name [mb]
  local n=$1 mb=${2:-10} m d label secs mbs mbit er s v cols sp_peak=200
  local -a sp_dir=() sp_ok=() sp_mbs=() sp_mbit=() sp_secs=() sp_err=()
  if [ "$(role "$n")" = Kharej ]; then
    err "Speed test runs on the entry server only (press [m] here for live monitor)"
    return
  fi
  m=$(cfg "$n" metrics); [ -n "$m" ] || { warn "Speed test needs metrics: in $n.yml"; return; }
  sec_hdr "Speed test" "${mb} MB"
  for d in down up; do
    [ "$d" = down ] && label="Download" || label="Upload  "
    spin_start "$label"
    r=$(curl -fs --noproxy '*' --max-time 200 "http://$m/speedtest?dir=$d&mb=$mb")
    spin_stop
    if [ -z "$r" ]; then
      s=$(stats_flat "$n")
      if [ -z "$s" ]; then err "$label: tunnel '$n' is not running"
      else
        v=$(jget "$s" version)
        if [ -n "$v" ] && ver_ge "$v" 1.8.1; then
          warn "Speed test unavailable (wattun $v did not answer on http://$m/speedtest)"
        else
          warn "Speed test requires wattun >= 1.8.1 on both sides (running ${v:-old})"
        fi
      fi
      return
    fi
    sp_dir+=("$d")
    if [ "$(jget "$r" ok)" = true ]; then
      secs=$(jget "$r" seconds); mbs=$(jget "$r" mb_per_s); mbit=$(jget "$r" mbit_per_s)
      sp_ok+=(1); sp_mbs+=("${mbs:-0}"); sp_mbit+=("${mbit:-0}"); sp_secs+=("${secs:-0}"); sp_err+=("")
      sp_peak=$(awk -v a="$mbs" -v b="$sp_peak" 'BEGIN{print (a>b)?a:b}')
    else
      er=$(grep -o '"error":"[^"]*"' <<<"$r" | cut -d'"' -f4)
      sp_ok+=(0); sp_mbs+=(0); sp_mbit+=(0); sp_secs+=(0); sp_err+=("${er:-unknown error}")
    fi
  done
  cols=$(term_cols)
  local idx
  for idx in 0 1; do
    [ "${sp_dir[$idx]}" = down ] && label="Download" || label="Upload  "
    if [ "${sp_ok[$idx]}" = 1 ]; then
      if [ "$cols" -ge 74 ]; then
        printf '  %s✔%s %-9s %s%6.1f MB/s%s  %5.0f Mbps  %5.2f s  %s\n' \
          "$GRN" "$RST" "$label" "$BOLD" "${sp_mbs[$idx]}" "$RST" "${sp_mbit[$idx]}" "${sp_secs[$idx]}" "$(tbar "${sp_mbs[$idx]}" "$sp_peak" 10)"
      else
        printf '  %s✔%s %-9s %s%6.1f MB/s%s  %5.0f Mbps  %5.2f s\n' \
          "$GRN" "$RST" "$label" "$BOLD" "${sp_mbs[$idx]}" "$RST" "${sp_mbit[$idx]}" "${sp_secs[$idx]}"
      fi
    else
      printf '  %s✘%s %-9s %sfailed%s  %s\n' "$RED" "$RST" "$label" "$RED" "$RST" "${sp_err[$idx]}"
      [[ "${sp_err[$idx]}" == *"1.8.1"* ]] && warn "The exit server runs older wattun — run: $SELF update"
    fi
  done
}

logs_menu() {
  local n=$1
  menu_line 1 'last 100' 2 'follow live' 3 'errors only' 4 'since boot' 0 back
  printf '  %s▸%s %s[1]%s ' "$CYN" "$RST" "$GRY" "$RST"
  key_read; echo; echo
  case "$KEY" in
    1|enter) journalctl -u "${WAT_PREFIX}@$n" -n 100 --no-pager -o short-iso ;;
    2) journalctl -u "${WAT_PREFIX}@$n" -f -o short-iso ;;
    3) journalctl -u "${WAT_PREFIX}@$n" -n 2000 --no-pager -o short-iso | grep -iE "error|fail|denied|refused|lost|restart" | tail -50 ;;
    4) journalctl -u "${WAT_PREFIX}@$n" -b --no-pager -o short-iso | tail -200 ;;
    *) return 0 ;;
  esac
}

# ======================================================================================
#  Live monitor (all tunnels, 2 s refresh, sparkline of the rate)
# ======================================================================================
declare -A HIST
hist_push() { # name value
  local arr v=${2%%.*}; [[ "$v" =~ ^[0-9]+$ ]] || v=0
  read -ra arr <<<"${HIST[$1]:-}"
  arr+=("$v")
  [ "${#arr[@]}" -gt 16 ] && arr=("${arr[@]:1}")
  HIST[$1]="${arr[*]}"
}
spark() { # "v1 v2 ..." [width=16] -> ····▁▂▃▅▇
  local w=${2:-16}
  local -a vals chars=(▁ ▂ ▃ ▄ ▅ ▆ ▇ █)
  local max=0 v res='' pad
  read -ra vals <<<"$1"
  if [ "${#vals[@]}" -gt "$w" ]; then
    vals=("${vals[@]:$((${#vals[@]}-w))}")
  fi
  for v in "${vals[@]}"; do [ "$v" -gt "$max" ] && max=$v; done
  for v in "${vals[@]}"; do
    if [ "$max" -eq 0 ]; then res+=${chars[0]}; else res+=${chars[$((v*7/max))]}; fi
  done
  pad=$((w - ${#vals[@]})); [ "$pad" -lt 0 ] && pad=0
  printf '%s%s%s%s%s' "$GRY" "$(rep '·' "$pad")" "$CYN" "$res" "$RST"
}
mon_frame() {
  local n r any=0 sp rate cols rtt_str load_str spw=16 left right pad
  ui_init_width; cols=$(term_cols)
  [ "$cols" -lt 78 ] && spw=10
  left="${GRY}WatTunnel ·${RST} ${BOLD}Live monitor${RST}"
  right="${GRY}$(date '+%H:%M:%S') · 2 s · any key${RST}"
  vlen "$left"; local lw=$VLEN; vlen "$right"; local rw=$VLEN
  pad=$((UI_W - lw - rw)); [ "$pad" -lt 2 ] && pad=2
  printf '\n  %s%*s%s\e[K\n' "$left" "$pad" '' "$right"
  printf '  %s%s%s\e[K\n\e[K\n' "$GRY" "$(rep ─ "$UI_W")" "$RST"
  if [ "$cols" -lt 68 ]; then
    printf '  %s%-12s %-10s %6s  %s%s\e[K\n' "$GRY" NAME STATE RTT RATE "$RST"
  else
    printf '  %s%-13s %-10s %6s  %-10s %-'"$spw"'s  %s%s\e[K\n' "$GRY" NAME STATE RTT RATE HISTORY LOAD "$RST"
  fi
  for n in $(listed_tunnels); do
    any=1; r=$(role "$n"); tinfo "$n"; state_cell "$r" "$TI_STATE"
    hist_push "$n" "$TI_RATE"; sp=$(spark "${HIST[$n]}" "$spw")
    rtt_str='-'; { [ "$TI_STATE" = up ] || [ "$TI_STATE" = degraded ]; } && rtt_str="$(printf '%.0f ms' "$TI_RTT")"
    rate='-'; [ "$TI_STATE" != stopped ] && rate="$(human "$TI_RATE")/s"
    load_str='-'; [ "$TI_STATE" != stopped ] && { [ "$r" = Kharej ] && load_str="${TI_SESS}c" || load_str="${TI_STREAMS}s"; }
    if [ "$cols" -lt 68 ]; then
      printf '  %-12s %s%s %-8s%s %6s  %s\e[K\n' "${n:0:12}" "$SC_COL" "$SC_DOT" "$SC_TXT" "$RST" "$rtt_str" "$rate"
    else
      printf '  %-13s %s%s %-8s%s %6s  %-10s %s  %s\e[K\n' "${n:0:13}" "$SC_COL" "$SC_DOT" "$SC_TXT" "$RST" \
        "$rtt_str" "$rate" "$sp" "$load_str"
    fi
  done
  [ "$any" = 0 ] && printf '  %sNo tunnels configured.%s\e[K\n' "$GRY" "$RST"
  printf '\e[K\n'
}
live_monitor() {
  local rc
  if [ "$IS_TTY" != 1 ]; then mon_frame | sed 's/\x1b\[K//g'; return 0; fi
  cur_hide; printf '\e[2J'
  while :; do
    printf '\e[H'; mon_frame; printf '\e[J'
    IFS= read -rsn1 -t 2 KEY; rc=$?
    [ "$rc" -le 128 ] && break
  done
  cur_show
}

# ======================================================================================
#  Path mute (Phoenix, 3.3.8): mute NAME PATH / unmute NAME PATH flip the bond's manual
#  per-path mute over the engine's existing POST /carrier/toggle metrics endpoint
#  (cmd/wattun main.go: ?path=N or ?carrier=NAME, NAME = the leg name exactly as /stats
#  lists it, e.g. udp or the suffixed leg udp:up; answer {"path":N,"carrier":"..","muted":b}).
#  It only reads the config for the metrics address and talks HTTP to the loopback
#  metrics server, so it works without root (main() exempts it from the root gate).
# ======================================================================================
carrier_toggle_cmd() { # want(mute|unmute) NAME PATH
  local want=$1 n=${2:-} p=${3:-} m i idx=-1 aligned=0 res muted
  [ -n "$n" ] && [ -n "$p" ] || { err "Usage: $SELF $want NAME PATH (PATH = a bonded path as /stats names it, e.g. udp or udp:up)."; return 1; }
  need_tunnel "$n" || return 1
  m=$(cfg "$n" metrics)
  [ -n "$m" ] || { err "Tunnel '$n' has no metrics endpoint in $n.yml (muting talks to the metrics server)."; return 1; }
  tinfo "$n" # fills CAR_* from /stats when the tunnel answers
  if [[ "$p" =~ ^[0-9]+$ ]]; then
    if [ "$TI_AUTO" = 0 ] && [ "$CAR_COUNT" -gt 0 ]; then # an auto Iran /stats hides dead legs: its indexes shift
      if [ "$((10#$p))" -ge "$CAR_COUNT" ]; then err "Tunnel '$n' has paths 0-$((CAR_COUNT-1)), not '$p'."; return 1; fi
      idx=$((10#$p)); aligned=1
    fi
  else
    for ((i=0; i<CAR_COUNT; i++)); do [ "${CAR_NAME[$i]}" = "$p" ] && { idx=$i; aligned=1; break; }; done
    if [ "$idx" -lt 0 ]; then # a dead auto leg is filtered out of /stats; the engine still knows it by name
      [[ "+$(cfg "$n" carrier)+" == *"+$p+"* ]] || { err "No path '$p' on tunnel '$n' (paths: $(cfg "$n" carrier))."; return 1; }
    fi
  fi
  if [ "$aligned" = 1 ]; then # already in the wanted state: no flip needed (the endpoint toggles)
    case "$want:${CAR_MUTED[$idx]}" in
      mute:true) ok "Path '$p' is already muted."; status_row "$n"; return 0 ;;
      unmute:false) ok "Path '$p' is already unmuted."; status_row "$n"; return 0 ;;
    esac
  fi
  if [[ "$p" =~ ^[0-9]+$ ]]; then
    res=$(curl -fs -X POST --noproxy '*' --max-time 3 "http://$m/carrier/toggle?path=$((10#$p))" 2>/dev/null)
  else
    res=$(curl -fs -X POST --noproxy '*' --max-time 3 "http://$m/carrier/toggle?carrier=$p" 2>/dev/null)
  fi
  [ -n "$res" ] || { err "Tunnel '$n' did not answer http://$m/carrier/toggle (is it running? does path '$p' exist?)."; return 1; }
  muted=$(jget "$res" muted)
  # interpret the answer against what was ASKED (2026-11-20 review F2): the engine's ToggleMute is a no-op that
  # answers {"muted":false} on a single-carrier server (wat.Server.ToggleMute only handles a bond), so a mute
  # request answered with muted:false is a REFUSAL, not a success
  case "$want:$muted" in
    mute:true) ok "Path '$p' is now muted." ;;
    mute:false) err "The engine refused (muted:false): muting needs a bonded tunnel — a single carrier cannot be muted."; return 1 ;;
    unmute:false) ok "Path '$p' is now unmuted." ;;
    unmute:true) err "The engine answered muted:true to an unmute request: $res"; return 1 ;;
    *) err "Unexpected answer from http://$m/carrier/toggle: $res"; return 1 ;;
  esac
  status_row "$n" # the refreshed one-line status
}
mute_cmd()   { carrier_toggle_cmd mute "$@"; }
unmute_cmd() { carrier_toggle_cmd unmute "$@"; }

# ======================================================================================
#  Tunnel actions
# ======================================================================================
status_all() { # plain, scriptable list
  local n any=0
  for n in $(listed_tunnels); do any=1; status_row "$n"; done
  [ "$any" = 1 ] || { warn "No tunnels yet. Start with the exit server: run $SELF and press n."; return 1; }
}
status_row() {
  local n=$1 r cr load
  r=$(role "$n"); cr=$(carrier_label "$n"); tinfo "$n"; state_cell "$r" "$TI_STATE"
  load=''; [ "$TI_STATE" != stopped ] && { [ "$r" = Kharej ] && load="clients $TI_SESS" || load="streams $TI_STREAMS"; }
  printf '  %-12s %-6s %-5s %s%s %-12s%s %-6s %-11s %s\n' "${n:0:12}" "$(role_label "$r")" "$cr" "$SC_COL" "$SC_DOT" "${SC_TXT^^}" "$RST" \
    "$([ "$TI_STATE" = up ] && printf '%.0fms' "$TI_RTT" || echo -)" "$load" "$(ports_summary "$n" 17)"
}
tunnel_card() {
  local n=$1 r cr peer lis par sub='' srv_act srv_up srv_en routing_txt c k x
  r=$(role "$n"); cr=$(cfg "$n" carrier); peer=$(cfg "$n" peer); lis=$(cfg "$n" listen)
  par=$(companion_of "$n")
  tinfo "$n"; state_cell "$r" "$TI_STATE"
  srv_act=$(systemctl is-active "${WAT_PREFIX}@$n" 2>/dev/null || echo inactive)
  [ -n "$srv_act" ] || srv_act=inactive
  srv_up=$(uptime_of "$n")
  srv_en=$(systemctl is-enabled "${WAT_PREFIX}@$n" 2>/dev/null | head -1)

  if [ "$r" = Kharej ]; then routing_txt="$(kv allows "$(ports_summary "$n" 26)")"; else routing_txt="$(kv ports "$(ports_summary "$n" 26)")"; fi
  box_top "${par:+reverse side of $par}"

  local boot='boot off'; [ "$srv_en" = enabled ] && boot='boot on'
  [ -n "$TI_WHY" ] && box_row "${SC_COL}${TI_WHY}${RST}"
  [ -f "$CONF/$n.repaste" ] && box_row "${YEL}new token: press t and paste it on the entry server${RST}"
  if [ "$srv_act" = active ]; then box_row "${GRY}active${srv_up:+ $srv_up} · $boot${RST}"
  else box_row "${GRY}$srv_act · $boot${RST}"; fi
  if is_auto_kharej "$n"; then
    auto_live "$n"; c=$(echo $AN_D $AN_E ${AN_R:+r:$AN_R}); c=${c// /+}; [ -n "$c" ] || c=$TI_LIVE_PICK
    x=$(cfg "$n" carrier | tr '+' ' ' | wc -w)
    if [ -n "$c" ]; then k="active"; else k="$x ready"; fi
    row_2col "$(kv carrier "${c:-auto} ${GRY}($k)${RST}")" "$routing_txt"
  elif [ -n "$par" ] && [ "$TI_STATE" = up ] && [ -n "$TI_LIVE" ]; then row_2col "$(kv carrier "$TI_LIVE")" "$routing_txt"
  elif [ -n "$par" ]; then row_2col "$(kv carrier "auto ${GRY}($(wc -w <<<"${cr//+/ }") ready)${RST}")" "$routing_txt"
  else row_2col "$(kv carrier "$cr")" "$routing_txt"; fi

  # Sub-role details
  if [ -n "$par" ]; then
    box_row "$(kv reverse "to Iran $(cfg "$n" peer-icmp)")"
  elif is_auto_kharej "$n"; then
    if [ -f "$CONF/$n.iranip" ]; then sub="Entry server $(head -1 "$CONF/$n.iranip" 2>/dev/null)"
    elif [ -f "$CONF/$n-r.yml" ]; then sub="Entry server $(cfg "$n-r" peer-icmp)"
    elif systemctl is-active -q "${WAT_PREFIX}-autowatch-$n.service" 2>/dev/null; then sub="waiting for entry server"
    else sub="The entry IP pending ($SELF auto-ip $n IP)"; fi
    [ -n "$AN_D$AN_R$AN_E" ] || box_row "$(kv auto "$sub")"
  elif [ "$cr" = icmp ] && is_reverse "$n"; then
    if [ "$r" = Iran ]; then box_row "$(kv reverse "pinged by ${peer:--}")"; else box_row "$(kv reverse "pings ${peer:--}")"; fi
  elif is_rpool "$cr" && is_reverse "$n"; then
    if [ "$r" = Iran ]; then box_row "$(kv reverse "listen ${lis:-:-}")"; else box_row "$(kv reverse "dials ${peer:--}")"; fi
  elif [ "$r" = Iran ]; then
    box_row "$(kv Kharej "${peer:--}")"
  else
    [ -n "$lis" ] && box_row "$(kv listen "$lis")"
  fi
  if [ "$r" = Iran ] && [ "$(uname -s)" = Linux ] && ! { is_rpool "$cr" && is_reverse "$n"; }; then
    local oip; oip=$(cfg "$n" src-ip)
    if [ -n "$oip" ]; then box_row "$(kv source "$oip ${GRY}(src-ip)${RST}")"
    elif [ -n "$(out_ip "${peer%%[:,]*}")" ]; then
      box_row "$(kv source "$(out_ip "${peer%%[:,]*}")")"
    fi
  fi

  sub=$(cdn_summary "$n"); [ -n "$sub" ] && box_row "$(kv cdn "$sub")"
  if ac_dialer "$n"; then
    local fks=$(cfg "$n" fake-sni) gov=$(cfg "$n" governor) rot=$(cfg "$n" pool-rotate) dl=$(cfg "$n" dns-listen)
    if [ -n "$fks" ] || [ "$gov" = true ] || [ -n "$rot" ] || [ -n "$dl" ]; then
      box_row "$(kv anti-censor "${GRN}on${RST} · $(detect_preset "$n")${fks:+ · fake-sni $fks}${dl:+ · dns $dl}")"
    else
      box_row "$(kv anti-censor "${GRY}off${RST}")"
    fi
  elif [ "$(uname -s)" = Linux ] && is_pool_list "$(cfg "$n" carrier)" && is_reverse "$n"; then
    box_row "$(kv anti-censor "${GRY}kharej-side${RST}")"
  fi
  local bmode=$(cfg "$n" bond-mode)
  [ -n "$bmode" ] && box_row "$(kv bond "$bmode")"
  if [ -f "$CONF/$n.sla" ]; then
    local min_r=$(grep '^sla_min_rate_kbps=' "$CONF/$n.sla" 2>/dev/null | cut -d= -f2)
    local max_rtt=$(grep '^sla_max_rtt_ms=' "$CONF/$n.sla" 2>/dev/null | cut -d= -f2)
    local max_l=$(grep '^sla_max_loss_pct=' "$CONF/$n.sla" 2>/dev/null | cut -d= -f2)
    box_row "$(kv sla "≥${min_r:-0} kbps · ≤${max_rtt:-0} ms · ≤${max_l:-0}%")"
  fi

  # Section 2: Real-time telemetry (when not stopped)
  if [ "$TI_STATE" != stopped ]; then
    box_mid
    local uf=${TI_DGRAM_FLOWS:-0}
    if [ "$TI_STATE" = up ] || [ "$TI_STATE" = degraded ]; then
      local rt mr; printf -v rt '%.0f' "${TI_RTT:-0}"; printf -v mr '%.0f' "${TI_MIN_RTT:-0}"
      if [ "$rt" = "$mr" ]; then rt="$rt ms"; else rt="$rt ms ${GRY}min $mr${RST}"; fi
      row_2col "$(kv rtt "$rt")" "$(kv streams "$TI_STREAMS")"
      row_2col "$(kv total "↓$(human "$TI_IN")  ↑$(human "$TI_OUT")")" "$(kv sessions "$TI_SESS")"
      if has_dgram "$TI_LIVE"; then row_2col "$(kv loss "$(printf '%.1f' "${TI_LOSS:-0}") %")" "$([ "${uf:-0}" -gt 0 ] 2>/dev/null && kv 'udp flows' "$uf")"
      elif [ "${uf:-0}" -gt 0 ] 2>/dev/null; then box_row "$(kv 'udp flows' "$uf")"; fi
    else
      [ "${TI_IN%.*}" -gt 0 ] 2>/dev/null && box_row "$(kv total "↓$(human "$TI_IN")  ↑$(human "$TI_OUT")")"
    fi
    # one row per carrier of a bond; an auto side lists only what Iran uses, and nothing when that is one type
    if [ "$TI_CAR_COUNT" -gt 1 ] && { [ "$TI_AUTO" = 0 ] || [ "$TI_LIVE" != "${TI_LIVE//+/}" ]; }; then
      box_mid
      local ci ccol cdot ctxt det
      for ((ci=0; ci<TI_CAR_COUNT; ci++)); do
        det=''
        if [ "${CAR_MUTED[$ci]}" = true ]; then ccol=$GRY; cdot='◌'; ctxt=muted
        elif [ "${CAR_ALIVE[$ci]}" = true ]; then
          ccol=$GRN; cdot='●'; ctxt=up
          det="$(printf '%.0f' "${CAR_RTT[$ci]:-0}") ms · $(awk -v sh="${CAR_SHARE[$ci]:-0}" 'BEGIN{printf "%.0f", sh*100}')% traffic"
          has_dgram "${CAR_NAME[$ci]}" && det+=" · loss $(awk -v l="${CAR_LOSS[$ci]:-0}" 'BEGIN{printf "%.1f", l*100}')%"
        else
          [ "$TI_AUTO" = 1 ] && continue
          ccol=$RED; cdot='○'; ctxt=down
        fi
        box_row "$(printf '%s%s %-5s%s %-6s %s%s%s' "$ccol" "$cdot" "$ctxt" "$RST" "${CAR_NAME[$ci]}" "$GRY" "$det" "$RST")"
      done
    fi
  fi
  box_bot
}
token_qr() { # token : the token as a terminal QR code too, on a tty when qrencode is installed (nothing otherwise)
  if [ "$IS_TTY" = 1 ] && command -v qrencode >/dev/null 2>&1; then qrencode -t ANSIUTF8 -- "$1"; fi
  return 0
}
# 3.3.8: recover NAME.token when an older 3.3.3-3.3.7 finalize (or manual rm) removed it, so show_token, change_key
# and main-menu o work on existing Kharej tunnels without deleting and recreating them.
rebuild_kharej_token() { # name -> rc 0 when NAME.token exists or was rebuilt
  local n=$1 key allow apath sni itype addr='' tf cr rev='' lis lp='' pip rplan dplan
  [ "$(role "$n")" = Kharej ] || return 1
  [ -f "$CONF/$n.token" ] && return 0
  key=$(head -1 "$CONF/$n.key" 2>/dev/null || true); [ -n "$key" ] || return 1
  load_maps "$n"; allow=$(maps_allow_str)
  apath=$(cfg "$n" path); sni=$(cfg "$n" sni); itype=$(cfg "$n" icmp-type)
  for tf in "$CONF"/*.token; do
    [ -e "$tf" ] || continue
    if read_token "$(cat "$tf")" && [ -n "$T_PEER" ]; then split_hp "${T_PEER%%,*}"; addr=$HP_HOST; break; fi # M1: a bond token's first entry carries the host
  done
  [ -n "$addr" ] || addr=$(public_ip)
  [ -n "$addr" ] || addr=$(out_ip 8.8.8.8)
  if [ -z "$addr" ] && [ "$NONINTERACTIVE" != 1 ] && [ -t 0 ]; then
    ask_ok "Public IP or domain of this server" "" v_host && { split_hp "$REPLY_V"; addr=$HP_HOST; }
  fi
  [ -n "$addr" ] || return 1
  cr=$(cfg "$n" carrier); is_reverse "$n" && rev=1
  if head -1 "$CONF/$n.yml" 2>/dev/null | grep -Eq 'Kept by wattun-manager from auto tunnel|auto: every carrier at once'; then
    if [ "$rev" = 1 ]; then
      pip=$(cfg "$n" peer-icmp); [ -n "$pip" ] || { split_hp "$(cfg "$n" peer)"; pip=$HP_HOST; lp=$HP_PORT; }
      [ -n "$pip" ] && ( umask 077; printf '%s\n' "$pip" >"$CONF/$n.iranip" ) 2>/dev/null || true
    else
      lis=$(cfg "$n" listen); split_hp "$lis"; lp=$HP_PORT
    fi
    auto_pick_ports "$([ -n "$sni" ] && echo 1 || echo 0)" || return 1
    dplan=$AUTO_D; rplan=$(auto_pick_rplan "$AUTO_USED_PORTS") || return 1
    if [ -n "$lp" ] && [[ "$cr" != *+* ]]; then
      if [ "$rev" = 1 ]; then rplan=$(sed -E "s/(^|,)$cr:[0-9]+/\1$cr:$lp/" <<<"$rplan")
      elif ! is_shaped_carrier "$cr"; then dplan=$(sed -E "s/(^|,)$cr:[0-9]+/\1$cr:$lp/" <<<"$dplan"); fi
    fi
    ( umask 077
      make_token auto "$addr" "$key" "${apath:-/wat}" "$sni" "" "$allow" "" "d=$dplan;r=$rplan" >"$CONF/$n.token"
      : >"$CONF/$n.repaste" ) # new ports: Iran's saved plan is stale until this token is pasted there (cleared by show_token)
    return 0
  fi
  lis=$(cfg "$n" listen); split_hp "$lis"; lp=$HP_PORT
  if [ -z "$lp" ] && [ "$rev" = 1 ]; then split_hp "$(cfg "$n" peer)"; lp=$HP_PORT; fi
  [ "$(cfg "$n" udp-dns)" = true ] && apath=dns
  ( umask 077; make_token "$cr" "$(join_hp "$addr" "$lp")" "$key" "$apath" "$sni" "$itype" "$allow" "$rev" >"$CONF/$n.token" )
}
show_token() {
  local n=$1
  [ "$(role "$n")" = Kharej ] && [ ! -f "$CONF/$n.token" ] && { rebuild_kharej_token "$n" || true; }
  if [ ! -f "$CONF/$n.token" ]; then
    err "No token stored for '$n' (tokens exist only on the exit tunnels)."; return 1
  fi
  refresh_token "$n"
  if is_auto_kharej "$n" && auto_needs_reopen "$n"; then
    auto_reopen "$n" >/dev/null 2>&1 || true
  fi
  printf '  %s%s%s\n' "$BOLD$YEL" "$(cat "$CONF/$n.token")" "$RST"; token_qr "$(cat "$CONF/$n.token")"
  hint "Contains secret key — share privately."
  if [ -f "$CONF/$n.repaste" ]; then
    warn "This token is new: paste it on the entry server (the entry tunnel page, key t) or the entry server's auto test keeps failing."
    rm -f "$CONF/$n.repaste"
  fi
}
edit_ports() { # name
  local n=$1 r old=() it i pub=() before par hu
  par=$(companion_of "$n"); [ -n "$par" ] && n=$par
  r=$(role "$n")
  load_maps "$n"; old=("${MAPS[@]+"${MAPS[@]}"}")
  PE_ROLE=$r; PE_TUNNEL=$n; PE_ALLOW=(); PE_OWNED=(); PE_MSG=''
  for it in ${old[@]+"${old[@]}"}; do PE_OWNED+=("$(spec_L "$it")/$(spec_P "$it")"); done
  systemctl is-active -q "${WAT_PREFIX}@$n" 2>/dev/null || PE_OWNED=()
  port_editor || { warn "No changes saved."; return 0; }
  write_ports "$n" || { err "Could not write config."; return 1; }
  [ "$r" = Kharej ] && refresh_token "$n"
  if [ "$r" = Kharej ] && is_auto_kharej "$n"; then
    for hu in $(auto_helpers "$n"); do write_ports "$hu"; done
  fi
  ok "Saved · $(ports_summary "$n" 60) (applies in 3 s, no drop)"
  if [ "$r" = Iran ]; then
    before=" ${PE_OWNED[*]-} "
    for ((i=0; i<${#MAPS[@]}; i++)); do
      it="$(spec_L "${MAPS[$i]}")/$(spec_P "${MAPS[$i]}")"
      case "$before" in *" $it "*) ;; *) pub+=("$it") ;; esac
    done
    [ "${#pub[@]}" -gt 0 ] && fw_open "${pub[*]}"
  fi
}
change_peer() {
  local n=$1 r cr old v op np oh
  r=$(role "$n"); cr=$(cfg "$n" carrier); old=$(cfg "$n" peer)
  split_hp "$old"; oh=$HP_HOST; op=$HP_PORT
  if is_reverse "$n"; then
    if [ "$r" = Kharej ]; then
      # reverse: this server dials Iran, so its peer is the address that must be repointed here
      if [ "$cr" = icmp ]; then ask_ok "New the entry address (IPv4)" "$oh" v_ipv4 || return 1; v=$REPLY_V
      else
        ask_ok "New the entry address (host or host:port)" "$old" v_host || return 1
        split_hp "$REPLY_V"
        v=$(join_hp "$HP_HOST" "${HP_PORT:-$op}")
      fi
      set_value "$n" peer "$v"
      step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n" || return 1
      wait_link "$n" 20 && ok "CONNECTED (RTT ${LINK_RTT} ms)" || warn "Not connected yet."
      [ "$cr" != icmp ] && hint "If the carrier port changed too, set the same listen port on the entry server (tunnel page, h)."
      return 0
    fi
    # reverse on Iran: this server is the listener, so only its own port is local
    [ "$cr" = icmp ] && { hint "Reverse ICMP has no port to change: this server only answers ping."; return 0; }
    ask_ok "New carrier listen port on this server (the same port on the exit server)" "$op" v_port || return 1
    np=$((10#$REPLY_V))
    if listen_blocked "$(rproto "$cr")" "$np" && [ "$np" != "$op" ]; then
      err "Port $np/$(rproto "$cr") is already in use here by $(listen_conflict_desc "$(rproto "$cr")" "$np")."; return 1
    fi
    set_value "$n" listen "\":$np\""
    [ -n "$op" ] && set_value "$n" peer "$(join_hp "$oh" "$np")"
    fw_open "$np/$(rproto "$cr")"
    step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n" || return 1
    wait_link "$n" 20 && ok "CONNECTED (RTT ${LINK_RTT} ms)" || warn "Not connected yet."
    hint "On the exit server set the same port as its peer target (tunnel page, h)."
    return 0
  fi
  # normal: Iran dials Kharej
  ask_ok "New the exit address (host or host:port)" "$old" v_host || return 1
  split_hp "$REPLY_V"
  if is_raw_carrier "$cr"; then # raw-IP carriers take a bare host; a typed port would break the raw socket
    [ -n "$HP_PORT" ] && hint "Raw-IP carrier: dropped the port, the peer is a bare address."
    v=$HP_HOST
  else
    if [ -z "$HP_PORT" ]; then
      [ -n "$op" ] || { err "This carrier needs host:port (for example example.com:443)."; return 1; }
      HP_PORT=$op; hint "No port given: keeping port $op."
    fi
    v_port "$HP_PORT" >/dev/null 2>&1 || { err "The exit address needs a valid port, like host:443."; return 1; }
    np=$((10#$HP_PORT))
    v=$(join_hp "$HP_HOST" "$np")
  fi
  set_value "$n" peer "$v"
  step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n" || return 1
  wait_link "$n" 20 && ok "CONNECTED (RTT ${LINK_RTT} ms)" || warn "Not connected yet."
}
change_key() {
  local n=$1 k t u
  if [ "$(role "$n")" = Kharej ]; then
    warn "Every entry server on this tunnel disconnects until it gets the new token."
    confirm "Make a new key and token?" n || return 0
    [ -f "$CONF/$n.token" ] || rebuild_kharej_token "$n" || true
    k=$(new_key); ( umask 077; printf '%s\n' "$k" >"$CONF/$n.key" )
    if [ -f "$CONF/$n.token" ] && read_token "$(cat "$CONF/$n.token")"; then
      make_token "$T_CARRIER" "$T_PEER" "$k" "$T_PATH" "$T_SNI" "$T_ICMP" "$T_PORTS" "$T_REV" "$T_AUTO" "$T_PAIR" >"$CONF/$n.token"
    fi
    step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
    [ -f "$CONF/$n-r.yml" ] && is_auto_kharej "$n" && step "Restarting ${WAT_PREFIX}@$n-r" systemctl restart "${WAT_PREFIX}@$n-r"
    # H3 (2026-11-04): hidden shaped listeners read key-file only at startup; without a restart they keep accepting the
    # old key (and cannot be reached with the new token). Disabled units are pruned on purpose: leave them closed.
    for u in $(auto_ext_names "$n"); do
      systemctl is-enabled -q "${WAT_PREFIX}@$u" 2>/dev/null || continue
      step "Restarting extended listener ${WAT_PREFIX}@$u" systemctl restart "${WAT_PREFIX}@$u"
    done
    echo; ok "New token. Paste it on each entry server (tunnel page, t):"; echo
    show_token "$n"
  else
    local f="$CONF/$n.yml" oldrev=0 oldlisten='' oldproto='' keepres='' rport=''
    ask_ok "Token from exit server" "" v_token || return 1
    t=$REPLY_V; read_token "$t"
    if [ "$T_CARRIER" = auto ]; then # auto token: the type is chosen by testing, so test now and apply the winner
      local oldkey oldauto=0
      [ -f "$CONF/$n.auto" ] && oldauto=1
      oldkey=$(cat "$CONF/$n.key" 2>/dev/null || true)
      ( umask 077; printf '%s\n' "$T_KEY" >"$CONF/$n.key" )
      ( umask 077; printf '%s\n' "$t" >"$CONF/$n.auto" ); chmod 600 "$CONF/$n.auto"
      ok "Token accepted: the exit server ${T_PEER%%[:,]*}. The running tunnel stays up while the types are tested."
      if [ "$NONINTERACTIVE" = 1 ]; then
        hint "Now pick the type that works: $SELF auto-test $n"
        return 0
      fi
      AT_APPLIED=0
      auto_test_cmd "$n" || true
      if [ "$AT_APPLIED" = 1 ]; then
        wait_link "$n" 10 && ok "Connected to the new exit server." || warn "Switched, not connected yet. Press d to diagnose."
        return 0
      fi
      # nothing was chosen: put the old key back, or the next restart would use a key the old Kharej rejects
      [ -n "$oldkey" ] && ( umask 077; printf '%s\n' "$oldkey" >"$CONF/$n.key" )
      [ "$oldauto" = 1 ] || rm -f "$CONF/$n.auto"
      hint "Nothing changed: '$n' still uses its old exit server."
      return 0
    fi
    v_carrier_list "$T_CARRIER" || return 1 # D7: a shaped carrier cannot be a bond leg (engine refuses it)
    token_bond_legs || return 1 # M1: same per-leg endpoint split as the wizard import
    if is_shaped_list "$T_CARRIER"; then # F19: the far end must run 3.3.0 too; fix the peer form before writing it
      [ "$T_REV" = 1 ] && { err "F19 shaped carriers do not support reverse."; return 1; }
      shaped_supported_here "$T_CARRIER" || return 1
      if is_shaped_carrier "$T_CARRIER"; then
        T_PEER=$(shaped_peer_for_client "$T_CARRIER" "$T_PEER")
        split_hp "$T_PEER"
        [ -n "$HP_PORT" ] && { v_port "$HP_PORT" || return 1; }
      fi
      shaped_warn "$T_CARRIER"
    fi
    [ "$T_REV" = 1 ] && is_rpool "$T_CARRIER" && { split_hp "$T_PEER"; v_port "$HP_PORT" || return 1; }
    is_reverse "$n" && oldrev=1
    if [ "$oldrev" = 1 ]; then
      oldlisten=$(cfg "$n" listen); split_hp "$oldlisten"; oldlisten=$HP_PORT
      is_rpool "$(cfg "$n" carrier)" && oldproto=$(rproto "$(cfg "$n" carrier)")
    fi
    if is_pool_list "$T_CARRIER" && [ "$T_REV" != 1 ]; then keepres=1; fi
    ( umask 077; printf '%s\n' "$T_KEY" >"$CONF/$n.key" )
    rm -f "$CONF/$n.auto" # a fixed token replaces the auto plan; a stale one would let heal retest and switch it back
    # the token decides how the pair connects; drop every stale field instead of leaving a mismatch
    sed -i -E '/^(carrier|peer|path|udp-dns|sni|host|icmp-type|reverse|listen|peer-[a-z0-9-]+|listen-[a-z0-9-]+):/d' "$f"
    [ "$keepres" = 1 ] || sed -i -E '/^(fake-(sni|mode|ttl)|pool-rotate(-bytes)?|fp|ech|ech-cache|tls-frag):/d' "$f"
    set_value "$n" carrier "$T_CARRIER"
    set_value "$n" peer "$T_PEER"
    local _bl # M1: a bond token keeps its per-leg endpoints (the sed above dropped the old ones)
    for ((_bl=0; _bl<${#T_LEG_C[@]}; _bl++)); do set_value "$n" "peer-${T_LEG_C[$_bl]}" "${T_LEG_P[$_bl]}"; done
    if [ "$T_CARRIER" = udp ] && [ "$T_PATH" = dns ]; then set_value "$n" udp-dns true
    elif [ -n "$T_PATH" ]; then set_value "$n" path "$T_PATH"; fi
    if [ -n "$T_SNI" ]; then set_value "$n" sni "$T_SNI"; set_value "$n" host "$T_SNI"; fi
    [ -n "$T_ICMP" ] && [ "$T_ICMP" != echo ] && set_value "$n" icmp-type "$T_ICMP"
    if [ "$T_REV" = 1 ]; then
      set_value "$n" reverse true
      is_rpool "$T_CARRIER" && { split_hp "$T_PEER"; rport=$HP_PORT; set_value "$n" listen "\":$((10#${rport}))\""; }
    fi
    step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n" || return 1
    [ -n "$rport" ] && fw_open "$rport/$(rproto "$T_CARRIER")"
    [ "$oldrev" = 1 ] && [ -n "$oldlisten" ] && [ "$oldlisten" != "$rport" ] && fw_close "$oldlisten/$oldproto"
    [ "$T_CARRIER" = icmp ] && [ "$T_REV" = 1 ] && kreply_offer
    [ "$oldrev" = 1 ] && { [ "$T_REV" != 1 ] || [ "$T_CARRIER" != icmp ]; } && { kreply_users_left || kreply_restore; }
    wait_link "$n" 20 && ok "CONNECTED (RTT ${LINK_RTT} ms)" || warn "Not connected yet."
    # the new Kharej may allow a different set of targets: name the published rows it will refuse
    local missing='' it
    allow_to_array "$T_PORTS"
    load_maps "$n"
    for it in ${MAPS[@]+"${MAPS[@]}"}; do
      allowed_has "$(spec_T "$it")" "$(spec_P "$it")" || missing="$missing $(spec_T "$it")/$(spec_P "$it")"
    done
    [ -n "$missing" ] && warn "The exit server does not allow:${missing//\/tcp/} — those ports will be refused until you list them on the exit server (tunnel page, p)."
  fi
}
delete_tunnel() {
  local n=$1 f s p extra='' cnt u l lp lc lproto
  local -a n_fw=()
  [ -f "$CONF/$n-r.yml" ] && is_auto_kharej "$n" && extra=", companion $n-r"
  cnt=$(auto_ext_names "$n" | wc -w); [ "$cnt" -gt 0 ] && extra="$extra, $cnt extended listeners"
  warn "Stops '$n' and deletes its config, key, and token${extra}."
  if [ "$NONINTERACTIVE" = 1 ]; then REPLY_V=$n # --yes is the confirmation
  else ask "Type $n to confirm (Enter cancels)" ""; fi
  [ "$REPLY_V" = "$n" ] || { warn "Not deleted."; return 1; }
  state_dir_relative_warn "$n" # M8: the service resolves a relative state-dir from /; say so before resolving it
  while IFS= read -r l; do
    [ -n "$l" ] || continue
    lc=${l%%:*}; [ "$lc" = listen ] && lc=$(cfg "$n" carrier) || lc=${lc#listen-}
    lp=${l#*:}; lp=${lp//\"/}; lp=${lp//[[:space:]]/}
    split_hp "$lp"
    if [[ "$HP_PORT" =~ ^[0-9]+$ ]] && [ "$HP_PORT" -ge 1 ] && [ "$HP_PORT" -le 65535 ]; then
      lproto=$(rproto "$lc")
      case " ${n_fw[*]:-} " in *" $HP_PORT/$lproto "*) ;; *) n_fw+=("$HP_PORT/$lproto") ;; esac
    fi
  done < <(grep -E '^listen(-[a-z0-9-]+)?:' "$CONF/$n.yml" 2>/dev/null || true)
  if [ -f "$CONF/$n-r.yml" ] && is_auto_kharej "$n"; then # the auto reverse companion goes with its parent
    auto_drop_unit "$n-r"
  fi
  for f in $(auto_ext_names "$n"); do auto_drop_unit "$f"; done # B3/F08/F17: the hidden listeners, their state and UDP rules
  if is_auto_kharej "$n" && [ ! -f "$CONF/$n-r.yml" ]; then # the reverse side's config may be gone already: its state files go too
    while IFS= read -r f; do rm -f "$f"; done < <(state_files "$n-r")
  fi
  systemctl stop "${WAT_PREFIX}-autowatch-$n.service" >/dev/null 2>&1
  systemctl reset-failed "${WAT_PREFIX}-autowatch-$n.service" >/dev/null 2>&1
  # H8: stop the unit BEFORE removing its state files. The engine saves quota/totals on SIGTERM (and every state-save
  # seconds), so a rm first is undone by the shutdown save and a re-created tunnel starts with the old usage.
  systemctl disable --now "${WAT_PREFIX}@$n" >/dev/null 2>&1
  while IFS= read -r f; do rm -f "$f"; done < <(state_files "$n")
  bond_retest_disable "$n" # the bond-retest timer belongs to this tunnel
  rm -f "$CONF/$n".yml "$CONF/$n".ech "$CONF/$n".key "$CONF/$n".token "$CONF/$n".auto "$RUN/$n.down" "$RUN/$n.cycles" "$RUN/$n.retest" "$RUN/$n.sla_triggered" \
        "$CONF/$n".bondretest "$CONF/$n".bondretest.tmp "$CONF/$n".bondfail "$CONF/$n".bondfail.tmp "$CONF/$n".keepopen \
        "$CONF/$n".finalized "$CONF/$n".iranip "$CONF/$n".repaste \
        "$RUN/$n.autoprune" "$RUN/$n.autoprune.done" "$RUN/$n.autowiden" "$RUN/$n.autowiden.down" "$RUN/$n.abandoned"
  for p in ${n_fw[@]+"${n_fw[@]}"}; do
    [ -z "$(tunnel_using_listen "${p%/*}" "$n")" ] && fw_close "$p"
  done
  ok "Tunnel '$n' deleted."
  kreply_users_left || kreply_restore
  return 0
}
reset_traffic() { # name : zero the lifetime traffic counters (the engine keeps them across restarts)
  local n=$1 u f
  local -a units=("$n") act=()
  if is_auto_kharej "$n"; then
    while IFS= read -r u; do [ -n "$u" ] && units+=("$u"); done < <(auto_helpers "$n")
  fi
  state_dir_relative_warn "$n" # M8: same resolver rule as delete_tunnel
  for u in "${units[@]}"; do
    if systemctl is-active -q "${WAT_PREFIX}@$u"; then
      act+=("$u")
      systemctl stop "${WAT_PREFIX}@$u" >/dev/null 2>&1
    fi
    f=$(state_file "$u" totals) # F8: honour state-dir:, else the file next to the config
    rm -f "$f" "$f.host" "$f.tmp"
  done
  for u in ${act[@]+"${act[@]}"}; do
    systemctl start "${WAT_PREFIX}@$u" >/dev/null 2>&1
  done
  ok "Traffic counters of '$n' start from zero."
}
# Toggle reverse ICMP on one side. Kharej keeps Iran's IP as its peer and puts the flag in the token.
set_direction() { # name
  local n=$1 r ip cr pp pr
  r=$(role "$n"); cr=$(cfg "$n" carrier); pr=$(rproto "$cr")
  reverse_hint "$cr"
  if is_rpool "$cr"; then
    if is_reverse "$n"; then
      confirm "Switch '$n' back to the normal direction (the entry server connects to the exit server)?" n || return 1
      if [ "$r" = Kharej ]; then
        split_hp "$(cfg "$n" peer)"; pp=$HP_PORT
        v_port "$pp" >/dev/null 2>&1 || { err "Cannot read the carrier port from peer."; return 1; }
        set_value "$n" listen "\":$pp\""
        unset_value "$n" peer; unset_value "$n" sni; unset_value "$n" host
        fw_open "$pp/$pr"
      else
        unset_value "$n" listen
      fi
      unset_value "$n" reverse
    else
      confirm "Switch '$n' to reverse (the exit server connects out to the entry server)?" n || return 1
      if [ "$r" = Kharej ]; then
        split_hp "$(cfg "$n" listen)"; pp=$HP_PORT
        v_port "$pp" >/dev/null 2>&1 || { err "Cannot read the carrier port from listen."; return 1; }
        ask_ok "Entry server IP address (IPv4 or IPv6)" "" v_ip || return 1; ip=$REPLY_V
        set_value "$n" peer "$(join_hp "$ip" "$pp")"
        [ "$cr" = udp ] || unset_value "$n" listen # reverse udp keeps it: the source port of the punches
        if [ -f "$CONF/$n.token" ] && read_token "$(cat "$CONF/$n.token")" && [ -n "$T_SNI" ]; then
          set_value "$n" sni "$T_SNI"; set_value "$n" host "$T_SNI"
        fi
      else
        split_hp "$(cfg "$n" peer)"; pp=$HP_PORT
        v_port "$pp" >/dev/null 2>&1 || { err "The peer has no carrier port, so reverse cannot be set up."; return 1; }
        pp=$((10#$pp))
        if listen_blocked "$pr" "$pp"; then err "Port $pp/$pr is already in use here by $(listen_conflict_desc "$pr" "$pp")."; return 1; fi
        set_value "$n" listen "\":$pp\""
        fw_open "$pp/$pr"
      fi
      set_value "$n" reverse true
      local ofm; ofm=$(cfg "$n" fake-mode)
      case "$ofm" in sum|seqsum)
        set_value "$n" fake-mode rst; warn "fake-mode $ofm changed to rst: checksum markers are refused on a reverse tunnel." ;;
      esac
    fi
  elif is_reverse "$n"; then
    confirm "Switch '$n' back to the normal direction (the entry server sends the pings)?" n || return 1
    unset_value "$n" reverse
    [ "$r" = Kharej ] && unset_value "$n" peer
  else
    confirm "Switch '$n' to reverse (the exit server sends the pings)?" n || return 1
    if [ "$r" = Kharej ]; then
      ask_ok "Entry server IPv4 address" "" v_ipv4 || return 1; ip=$REPLY_V
      set_value "$n" peer "$ip"
    fi
    set_value "$n" reverse true
  fi
  if [ "$cr" = icmp ]; then
    if kreply_wanted "$n"; then kreply_offer; else kreply_users_left || kreply_restore; fi
  fi
  if [ "$r" = Kharej ] && [ -f "$CONF/$n.token" ] && read_token "$(cat "$CONF/$n.token")"; then
    T_REV=''; is_reverse "$n" && T_REV=1
    make_token "$T_CARRIER" "$T_PEER" "$T_KEY" "$T_PATH" "$T_SNI" "$T_ICMP" "$T_PORTS" "$T_REV" "$T_AUTO" "$T_PAIR" >"$CONF/$n.token"
  fi
  warn "Change it on the $([ "$r" = Kharej ] && echo Iran || echo Kharej) server too (Advanced, d), or the link stays down."
  return 0
}
# Validators that need context from adv_menu (its prompts are single-value, so the context travels in these globals):
# the carrier list for sessions/mtu, and the other FEC threshold when checking the loss band.
ADV_CR=''; ADV_REV=0; FEC_ON_CUR=2; FEC_OFF_CUR=0.5
v_sessions_adv() { v_sessions "$1" "$ADV_CR" "$ADV_REV"; }
v_mtu_adv() { v_mtu "$1" "$ADV_CR"; }
v_udp_hop() { # packets per source port, 0 = off, else 2..1000 (Wraith, 3.3.9)
  case "${1:-}" in ''|-|default|0) return 0 ;; *[!0-9]*) err "Enter a whole number."; return 1 ;; esac
  [ "$1" -ge 2 ] && [ "$1" -le 1000 ] || { err "Use 2 to 1000 (0 = off)."; return 1; }
}
hop_ok() { # name -> 0 when the tunnel can use -udp-hop: an Iran udp client (single carrier or a bond leg), not reverse
  [ "$(role "$1")" = Iran ] && ! is_reverse "$1" && case "+$(cfg "$1" carrier)+" in *+udp+*) return 0 ;; esac
  return 1
}
v_fec_on_adv() { v_fec_on "$1" "$FEC_OFF_CUR"; }
v_fec_off_adv() { v_fec_off "$1" "$FEC_ON_CUR"; }
adv_33() { # H4: the 3.3.0-only keys cannot go into a config an older engine reads (unknown key stops startup)
  [ -n "$(bin_ver_ok 3.3.0)" ] && return 0
  err "This setting needs wattun 3.3.0 or newer on this server (run: $SELF update); an older engine rejects the key at startup."
  return 1
}
adv_menu() { # name : max-mbps, fec, bind, icmp-type, direction, state files, FEC loss band, shaping, admission
  local n=$1 r changed=0 v cr fec_auto noise_m noisy noisw noiwin nm cb k33 wm_ok lc_ok lc
  r=$(role "$n"); cr=$(cfg "$n" carrier)
  while :; do
    # H4: the manager ships from main while the engine comes from releases/latest, so a 3.3.0-only key must never be
    # written into a config an older engine reads (it stops startup on an unknown key). Every 3.3.0-only row/case below
    # is hidden or refused unless this server's engine is >= 3.3.0.
    k33=0; [ -n "$(bin_ver_ok 3.3.0)" ] && k33=1
    wm_ok=0; [ -n "$(bin_ver_ok 3.0.3)" ] && wm_ok=1 # A3: -win-max exists since 3.0.3
    lc_ok=0; [ -n "$(bin_ver_ok 3.0.0)" ] && lc_ok=1 # A3: -loss-ceiling exists since 3.0.0
    # the direction can change inside this page, and sessions/mtu are validated against it
    ADV_CR=$cr; ADV_REV=0; is_reverse "$n" && ADV_REV=1
    FEC_ON_CUR=$(cfg "$n" fec-on-loss); FEC_ON_CUR=${FEC_ON_CUR:-2}
    FEC_OFF_CUR=$(cfg "$n" fec-off-loss); FEC_OFF_CUR=${FEC_OFF_CUR:-0.5}
    fec_auto=0; [ "$(cfg "$n" fec)" = auto ] && fec_auto=1
    noise_m=$(cfg "$n" noise); [ -n "$noise_m" ] || noise_m=off
    noisy=0; { [ "$noise_m" = custom ] || [ -n "$(cfg "$n" noise-bps)" ]; } && noisy=1
    noisw=0; { [ "$noise_m" != off ] || [ -n "$(cfg "$n" noise-window)" ]; } && noisw=1
    page "Advanced" "$n"
    # A1: four named groups, same letters and gates. Group order: Performance (what moves bytes), Shaping & DPI (what
    # changes bytes on the wire), Safety (who gets in / which way), State & data (3.3.0-only persistence).
    adv_group Performance
    set_row m 'speed limit' "$(cfg "$n" max-mbps)" 'MB/s' 'none'
    [ "$r" = Iran ] && set_row s sessions "$(cfg "$n" sessions)" '' auto # client-only in the engine
    set_row c conns "$(cfg "$n" conns)" '' auto
    set_row u mtu "$(cfg "$n" mtu)" '' auto
    [ "$cr" = icmp ] && set_row i 'icmp type' "$(cfg "$n" icmp-type)" '' echo
    case "$cr" in icmp|udp) set_row y batching "$(cfg "$n" batch)" '' "$([ "$cr" = icmp ] && echo on || echo off)" ;; esac
    hop_ok "$n" && set_row h 'udp hop' "$(cfg "$n" udp-hop)" 'pkts/port' off
    [ "$wm_ok" = 1 ] && set_row e 'win max' "$(cfg "$n" win-max)" 'MB' 'auto'
    if [ "$lc_ok" = 1 ]; then # bool key: display on/off, write true/false (Go flag Set rejects "on")
      lc=$(cfg "$n" loss-ceiling); v=''; [ "$lc" = true ] && v=on
      set_row r 'loss ceiling' "$v" '' off
    fi
    adv_group 'Shaping & DPI'
    set_row f fec "$(cfg "$n" fec)" '' off
    [ "$fec_auto" = 1 ] && [ "$k33" = 1 ] && set_row o 'fec on loss' "$(cfg "$n" fec-on-loss)" '%' 2
    [ "$fec_auto" = 1 ] && [ "$k33" = 1 ] && set_row x 'fec off loss' "$(cfg "$n" fec-off-loss)" '%' 0.5
    if [ "$k33" = 1 ]; then
      set_row p 'shape data' "$(cfg "$n" shape-data)" '%' off
      [ "$noise_m" = off ] && set_row n noise '' '' off || set_row n noise "$noise_m"
      [ "$noisy" = 1 ] && set_row g 'noise bps' "$(cfg "$n" noise-bps)" 'B/s' 'custom only'
      [ "$noisw" = 1 ] && set_row w 'noise window' "$(cfg "$n" noise-window)" '' 'all day'
    fi
    if ac_dialer "$n"; then
      v=off; [ -n "$(cfg "$n" fake-sni)$(cfg "$n" pool-rotate)$(cfg "$n" ech)" ] || [ "$(cfg "$n" governor)" = true ] && v=on
      set_row k anti-censor "$v"
    fi
    adv_group Safety
    if [ "$k33" = 1 ] && [ "$r" = Kharej ]; then # admission allowlist: server side only (the client cannot enforce it)
      if allow_clients_cdn_risk "$cr" "$(cfg "$n" sni)"; then
        hint "Admission allowlist is unavailable here: a CDN carrier or sni makes the source the CDN edge (engine refuses it)."
      else
        set_row j 'allow clients' "$(cfg "$n" allow-clients)" '' 'any source'
        set_row l 'allow clients file' "$(cfg "$n" allow-clients-file)" '' 'none'
      fi
    fi
    [ "$r" = Iran ] && set_row a bind "$(cfg "$n" bind)" '' 0.0.0.0
    if rev_capable "$cr"; then
      if is_reverse "$n"; then v="reverse ${GRY}($([ "$cr" = icmp ] && echo "Kharej sends the pings" || echo "Kharej connects to Iran"))${RST}"
      else v="normal ${GRY}($([ "$cr" = icmp ] && echo "Iran sends the pings" || echo "Iran connects to Kharej"))${RST}"; fi
      set_row d direction "$v"
    fi
    if [ "$k33" = 1 ]; then
      adv_group 'State & data'
      set_row t 'state dir' "$(cfg "$n" state-dir)" '' 'next to config'
      set_row v 'state save' "$(cfg "$n" state-save)" 's' 30
    fi
    echo
    hint "Applies on exit (restarts tunnel). File-only keys: docs/TECHNICAL.md"
    menu_line 0 back
    key_read
    case "$KEY" in
      m) echo; ask_ok "Speed ceiling in MB/s (- or 0 or default = unset)" "$(cfg "$n" max-mbps)" v_mbps_adv || continue
         case "$REPLY_V" in -|0|default) REPLY_V='' ;; esac
         if [ -z "$REPLY_V" ]; then unset_value "$n" max-mbps; else set_value "$n" max-mbps "$REPLY_V"; fi; changed=1 ;;
      s) [ "$r" = Iran ] || continue
         echo; ask_ok "Sessions count 1-$ENG_MAX_SESSIONS (- or 0 or default = unset)" "$(cfg "$n" sessions)" v_sessions_adv || continue
         case "$REPLY_V" in -|0|default) REPLY_V='' ;; esac
         if [ -z "$REPLY_V" ]; then unset_value "$n" sessions; else set_value "$n" sessions "$REPLY_V"; fi; changed=1 ;;
      c) echo; ask_ok "Conns count 1-$ENG_MAX_CONNS (- or 0 or default = unset)" "$(cfg "$n" conns)" v_conns || continue
         case "$REPLY_V" in -|0|default) REPLY_V='' ;; esac
         if [ -z "$REPLY_V" ]; then unset_value "$n" conns; else set_value "$n" conns "$REPLY_V"; fi; changed=1 ;;
      u) echo; ask_ok "MTU $ENG_MTU_MIN-$(mtu_max_for "$cr") for carrier '$cr' (- or 0 or default = unset)" "$(cfg "$n" mtu)" v_mtu_adv || continue
         case "$REPLY_V" in -|0|default) REPLY_V='' ;; esac
         if [ -z "$REPLY_V" ]; then unset_value "$n" mtu; else set_value "$n" mtu "$REPLY_V"; fi; changed=1 ;;
      k) ac_dialer "$n" || continue; anticensor_menu "$n" ;;
      f) echo; ask_ok "FEC: off or auto" "$(cfg "$n" fec | sed 's/^$/off/')" v_fec || continue
         if [ "$REPLY_V" = off ]; then unset_value "$n" fec; else set_value "$n" fec "$REPLY_V"; fi; changed=1 ;;
      o) [ "$fec_auto" = 1 ] || continue; adv_33 || { sleep 1; continue; }
         echo; hint "Enables FEC parity above this loss % (0 < on <= 50)."
         ask_ok "FEC on-loss percent (above $FEC_OFF_CUR%)" "$(cfg "$n" fec-on-loss)" v_fec_on_adv || continue
         case "$REPLY_V" in
           ''|-|default)
             awk -v o="$FEC_OFF_CUR" 'BEGIN{exit !(2 > o)}' \
               || { err "fec-off-loss is $FEC_OFF_CUR %, so default 2 % is not above it; lower fec-off-loss first."; continue; }
             unset_value "$n" fec-on-loss ;;
           *) set_value "$n" fec-on-loss "$REPLY_V" ;;
         esac; changed=1 ;;
      x) [ "$fec_auto" = 1 ] || continue; adv_33 || { sleep 1; continue; }
         echo; hint "Stops FEC parity below this loss % (must stay below fec-on-loss)."
         ask_ok "FEC off-loss percent (below $FEC_ON_CUR%)" "$(cfg "$n" fec-off-loss)" v_fec_off_adv || continue
         case "$REPLY_V" in
           ''|-|default)
             awk -v n="$FEC_ON_CUR" 'BEGIN{exit !(0.5 < n)}' \
               || { err "fec-on-loss is $FEC_ON_CUR %, so default 0.5 % is not below it; raise fec-on-loss first."; continue; }
             unset_value "$n" fec-off-loss ;;
           *) set_value "$n" fec-off-loss "$REPLY_V" ;;
         esac; changed=1 ;;
      t) adv_33 || { sleep 1; continue; }
         echo; hint "Use /run/wattun (tmpfs, cleared on reboot); custom paths require unit write access."
         ask_ok "State directory (absolute; 0 or - = next to config)" "$(cfg "$n" state-dir)" v_state_dir || continue
         case "$REPLY_V" in
           ''|-|default|0) unset_value "$n" state-dir; ok "State files stay next to config." ;;
           *) set_value "$n" state-dir "${REPLY_V%/}"; ok "State dir: ${REPLY_V%/}." ;;
         esac
         changed=1 ;;
      v) adv_33 || { sleep 1; continue; }
         echo; ask_ok "State save interval in seconds (0 = shutdown only)" "$(cfg "$n" state-save)" v_state_save || continue
         case "$REPLY_V" in
           ''|-|default) unset_value "$n" state-save; ok "Default: 30 s." ;;
           *) set_value "$n" state-save "$REPLY_V"; ok "State save: ${REPLY_V} s." ;;
         esac; changed=1 ;;
      p) adv_33 || { sleep 1; continue; }
         echo; hint "Pads stream packets up to N% (0 = off, max 25%). Spends bandwidth."
         ask_ok "shape-data percent (0..25)" "$(cfg "$n" shape-data)" v_shape_data || continue
         case "$REPLY_V" in
           ''|-|default|0|0.0) unset_value "$n" shape-data; ok "shape-data off." ;;
           *) set_value "$n" shape-data "$REPLY_V"; ok "shape-data: $REPLY_V%." ;;
         esac; changed=1 ;;
      n) adv_33 || { sleep 1; continue; }
         echo; hint "Idle filler per session: low ~11 MB/d, med ~88 MB/d (multiplied by -sessions)."
         ask "noise: off, low, med or custom" "$(cfg "$n" noise | sed 's/^$/off/')"
         v_noise_mode "$REPLY_V" || continue
         nm=$REPLY_V
         case "$nm" in
           ''|off) unset_value "$n" noise; unset_value "$n" noise-bps; ok "Idle noise off." ;;
           low|med) set_value "$n" noise "$nm"; unset_value "$n" noise-bps; ok "Idle noise: $nm." ;;
           custom)
             cb=$(cfg "$n" noise-bps); case "$cb" in ''|*[!0-9]*) cb=1024 ;; esac
             [ "$cb" -ge 64 ] && [ "$cb" -le 1000000 ] || cb=1024
             ask_ok "Noise filler bytes/second (64..1000000)" "$cb" v_noise_bps || continue
             set_value "$n" noise-bps "$REPLY_V"; set_value "$n" noise custom
             ok "Idle noise: $REPLY_V B/s." ;;
         esac; changed=1 ;;
      g) [ "$noise_m" = custom ] || continue; adv_33 || { sleep 1; continue; }
         echo; ask_ok "Noise filler bytes/second (64..1000000)" "$(cfg "$n" noise-bps)" v_noise_bps || continue
         set_value "$n" noise-bps "$REPLY_V"; ok "Idle noise: $REPLY_V B/s."; changed=1 ;;
      w) [ "$noisw" = 1 ] || continue; adv_33 || { sleep 1; continue; }
         echo; ask_ok "Noise window HH:MM-HH:MM (empty = all day)" "$(cfg "$n" noise-window)" v_noise_window || continue
         case "$REPLY_V" in
           ''|-|default) unset_value "$n" noise-window; ok "Noise window: all day." ;;
           *) set_value "$n" noise-window "$REPLY_V"; ok "Noise window: $REPLY_V." ;;
         esac; changed=1 ;;
      j) [ "$r" = Kharej ] || continue; adv_33 || { sleep 1; continue; }
         allow_clients_cdn_risk "$cr" "$(cfg "$n" sni)" && { err "Refused with CDN carrier or sni (source is CDN edge)."; sleep 1; continue; }
         echo; hint "Admits only these source IPs/CIDRs on restart (ignored in reverse mode)."
         ask_ok "Allowed client addresses/CIDRs (- = any)" "$(cfg "$n" allow-clients)" v_allow_clients || continue
         case "$REPLY_V" in
           ''|-|default) unset_value "$n" allow-clients; ok "Allowlist cleared (any source)." ;;
           *) set_value "$n" allow-clients "$REPLY_V"
              [ -n "$(cfg "$n" allow-clients-file)" ] && warn "allow-clients-file overrides this inline list."
              ok "Allowed clients: $REPLY_V" ;;
         esac; changed=1 ;;
      l) [ "$r" = Kharej ] || continue; adv_33 || { sleep 1; continue; }
         allow_clients_cdn_risk "$cr" "$(cfg "$n" sni)" && { err "Refused with CDN carrier or sni (source is CDN edge)."; sleep 1; continue; }
         echo; hint "One IP/CIDR per line under $(allow_clients_dir)/; an empty file stops startup."
         ask_ok "Allowlist file (under $(allow_clients_dir)/; - = none)" "$(cfg "$n" allow-clients-file)" v_allow_clients_file || continue
         case "$REPLY_V" in
           ''|-|default) unset_value "$n" allow-clients-file; ok "Allowlist file cleared." ;;
           *) set_value "$n" allow-clients-file "$REPLY_V"; ok "Allowlist file: $REPLY_V." ;;
         esac; changed=1 ;;
      a) [ "$r" = Iran ] || continue; echo; ask_ok "Bind address" "$(cfg "$n" bind | sed 's/^$/0.0.0.0/')" v_bind || continue
         if [ "$REPLY_V" = 0.0.0.0 ]; then unset_value "$n" bind; else set_value "$n" bind "$REPLY_V"; fi; changed=1 ;;
      i) [ "$cr" = icmp ] || continue; echo; hint "Must match the exit server."; ask_ok "ICMP type" "$(cfg "$n" icmp-type | sed 's/^$/echo/')" v_icmp || continue
         if [ "$REPLY_V" = echo ]; then unset_value "$n" icmp-type; else set_value "$n" icmp-type "$REPLY_V"; fi; changed=1 ;;
      h) hop_ok "$n" || continue
         [ -n "$(bin_ver_ok 3.3.9)" ] || { err "udp hop needs wattun 3.3.9+ on this server (run: $SELF update)."; sleep 1; continue; }
         echo; hint "Sends from a new UDP source port every N-1.5N packets: passes a filter that cuts each flow after ~30 packets. 12 = field setting. Any exit server connects; the exit server 3.3.9+ downloads at full speed."
         ask_ok "Packets per source port (0 = off)" "$(cfg "$n" udp-hop)" v_udp_hop || continue
         case "$REPLY_V" in ''|-|default|0) unset_value "$n" udp-hop ;; *) set_value "$n" udp-hop "$REPLY_V" ;; esac; changed=1 ;;
      y) case "$cr" in icmp|udp) ;; *) continue ;; esac
         echo; ask "Batching (on, off, default; needs 3.0.0+)" "$(cfg "$n" batch | sed 's/^$/default/')"
         case "$REPLY_V" in
           on|off) [ "$(bin_ver_ok 3.0.0)" = 1 ] || { err "batch needs wattun 3.0.0+ (run: $SELF update)."; sleep 1; continue; }
              set_value "$n" batch "$REPLY_V"; changed=1 ;;
           default|-|'') unset_value "$n" batch; changed=1 ;;
           *) err "Use on, off or default."; sleep 1 ;;
         esac ;;
      e) [ "$wm_ok" = 1 ] || { err "win-max needs wattun 3.0.3+ (run: $SELF update)."; sleep 1; continue; }
         echo; ask_ok "Stream receive window cap in MB (4-64; 0/- = auto)" "$(cfg "$n" win-max | sed 's/^$/0/')" v_win_max || continue
         case "$REPLY_V" in ''|-|0|default) unset_value "$n" win-max; ok "win-max: auto." ;;
           *) set_value "$n" win-max "$REPLY_V"; ok "win-max: $REPLY_V MB." ;;
         esac; changed=1 ;;
      r) [ "$lc_ok" = 1 ] || { err "loss-ceiling needs wattun 3.0.0+ (run: $SELF update)."; sleep 1; continue; }
         echo; hint "Also cut rate on sudden loss spikes (default is delay-only CC)."
         ask "Loss ceiling: on or off" "$([ "$(cfg "$n" loss-ceiling)" = true ] && echo on || echo off)"
         v_loss_ceiling "$REPLY_V" || { sleep 1; continue; }
         case "$REPLY_V" in on|true|1) set_value "$n" loss-ceiling true; ok "loss-ceiling on." ;;
           *) unset_value "$n" loss-ceiling; ok "loss-ceiling off." ;;
         esac; changed=1 ;;
      d) rev_capable "$cr" || continue; echo
         # applied at once, so the direction never sits in the file without running
         set_direction "$n" && step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
         pause ;;
      b|0|q|enter|esc) break ;;
      *) : ;;
    esac
  done
  # Every setting here needs a restart; apply it automatically (an unapplied change only logs "restart needed").
  if [ "$changed" = 1 ]; then
    if [ "$r" = Kharej ] && is_auto_kharej "$n"; then
      auto_sync_helper_settings "$n"
      step "Restarting ${WAT_PREFIX}@$n to apply" auto_for_each_unit "$n" restart
    else
      step "Restarting ${WAT_PREFIX}@$n to apply" systemctl restart "${WAT_PREFIX}@$n"
    fi
  fi
  return 0
}

# ======================================================================================
#  Automated Anti-Censorship Testing & Verification
# ======================================================================================
anticensor_test() {
  local n=$1 r cr peer s alive=false srtt pkts_in pkts_out fprof ech_st gov_st
  [ -f "$CONF/$n.yml" ] || { err "No tunnel named '$n'."; return 1; }
  r=$(role "$n"); cr=$(cfg "$n" carrier); peer=$(cfg "$n" peer)
  ac_dialer "$n" || { err "'$n' does not dial the carrier (anti-censorship verification runs on the dialing end)."; return 1; }
  echo
  say "  ${BOLD}Anti-censor test${RST}  ${GRY}$n · $r · $cr${RST}"
  echo

  if ! systemctl is-active -q "${WAT_PREFIX}@$n" 2>/dev/null; then
    warn "$n is stopped. Starting it."
    systemctl start "${WAT_PREFIX}@$n" 2>/dev/null
    sleep 1
  fi

  # Active profile report
  local fks=$(cfg "$n" fake-sni) fkm=$(cfg "$n" fake-mode) fkt=$(cfg "$n" fake-ttl)
  local rot=$(cfg "$n" pool-rotate) rbytes=$(cfg "$n" pool-rotate-bytes)
  local ech=$(cfg "$n" ech) gov=$(cfg "$n" governor)
  local dl=$(cfg "$n" dns-listen) sip=$(cfg "$n" src-ip)

  if [ -n "$fks" ]; then
    say "  $(kv 'fake sni' "$fks · ${fkm:-seq}${fkt:+ · ttl $fkt}")"
  else
    say "  $(kv 'fake sni' "${GRY}off${RST}")"
  fi
  [ -n "$rot" ] && say "  $(kv rotate "$rot${rbytes:+ / $rbytes}")"
  [ -n "$ech" ] && say "  $(kv ech "$ech")"
  [ "$gov" = true ] && say "  $(kv governor on)"
  [ -n "$dl" ] && say "  $(kv 'dns relay' "$dl")"
  [ -n "$sip" ] && say "  $(kv 'source ip' "$sip")"
  echo

  spin_start "Waiting for the link"
  local wait_sec=${ANTICENSOR_TEST_WAIT:-6}
  for ((i=0; i<wait_sec; i++)); do
    s=$(stats "$n" 2>/dev/null) # JSON: filter_profile below is an object, which the flat form leaves out
    if [ "$(jget "$s" alive)" = true ]; then
      alive=true; break
    fi
    sleep 1
  done
  spin_stop

  if [ "$alive" = true ]; then
    srtt=$(jget_flat "$s" rtt_ms srtt_ms)
    pkts_in=$(jget "$s" pkts_in)
    pkts_out=$(jget "$s" pkts_out)
    fprof=$(jget "$s" filter_profile)
    ech_st=$(jget "$s" ech)

    sec_hdr "Result"
    ok "Connected · RTT $(ms "$srtt") ms · ${pkts_in:-0} in / ${pkts_out:-0} out"
    [ -n "$fprof" ] && say "  $(kv filter "$fprof")"
    [ -n "$ech_st" ] && say "  $(kv ech "$ech_st")"

    # Forwarded port check
    load_maps "$n"
    if [ "${#MAPS[@]}" -gt 0 ]; then
      local first_map="${MAPS[0]}"
      local lport=$(spec_L "$first_map")
      local proto=$(spec_P "$first_map")
      if [ -n "$lport" ] && [[ "$lport" =~ ^[0-9]+$ ]]; then
        if [ "$proto" = tcp ]; then
          if timeout 2 bash -c "</dev/tcp/127.0.0.1/$lport" 2>/dev/null; then
            ok "Port :$lport/$proto answers"
          fi
        elif port_busy "$lport" "$proto"; then
          ok "Port :$lport/$proto open"
        fi
      fi
    fi
    return 0
  else
    err "No link within ${wait_sec} s"
    if [ -n "$fks" ]; then
      hint " · Try blackout:  $SELF blackout $n blackout"
      hint " · Try mode rst/synrst (tunnel page -> z -> 3) or another SNI (irancell.ir, divar.ir)"
    else
      hint " · Enable fake-SNI:  $SELF blackout $n mci"
    fi
    [ "$cr" = icmp ] && hint " · ICMP filtered? Turn governor on (tunnel page -> z -> 2)"
    return 1
  fi
}

# ======================================================================================
#  Interactive Anti-Censorship Menu Hub
# ======================================================================================
AC_KEYS="fake-sni fake-mode fake-ttl fake-ip fake-split fp tls-small-ch ech ech-cache tls-frag pool-rotate pool-rotate-bytes governor dns-listen src-ip conns loss-ceiling keep-slow"
anticensor_menu() {
  local n=$1 cr r
  cr=$(cfg "$n" carrier); r=$(role "$n")
  [ "$(uname -s)" = Linux ] || return 0
  if ! ac_dialer "$n"; then # the listening end has nothing to configure
    page "Anti-censor" "$n · $cr"
    say "  The $([ "$r" = Iran ] && echo Kharej || echo Iran) server dials this $(is_reverse "$n" && echo reverse || echo normal) tunnel, so anti-censor is set there."
    hint "To change who dials: Advanced, d, on both servers."
    menu_line h 'what spoofing and shaping mean'
    key_read
    [ "$KEY" = h ] && spoofhelp_page "$n"
    return 0
  fi
  local changed=0 k v
  while :; do
    page "Anti-censor" "$n · $cr"
    local fs fm ft pr pb ech gov dl sip
    fs=$(cfg "$n" fake-sni)
    fm=$(cfg "$n" fake-mode); [ -n "$fm" ] || fm=seq
    ft=$(cfg "$n" fake-ttl)
    pr=$(cfg "$n" pool-rotate)
    pb=$(cfg "$n" pool-rotate-bytes)
    ech=$(cfg "$n" ech)
    gov=$(cfg "$n" governor)
    dl=$(cfg "$n" dns-listen)
    sip=$(cfg "$n" src-ip)

    if [ -n "$fs" ] || [ "$gov" = true ] || [ -n "$pr" ]; then set_row 1 anti-censor "${GRN}on${RST} · $(detect_preset "$n")"
    else set_row 1 anti-censor "off ${GRY}(plain tunnel, full speed)${RST}"; fi
    set_row r direction "$(is_reverse "$n" && echo "reverse ${GRY}(Kharej dials Iran)${RST}" || echo "normal ${GRY}(Iran dials Kharej)${RST}")"
    echo
    if is_pool_list "$cr"; then
      set_row 2 'fake sni' "$fs" '' off
      [ -n "$fs" ] && set_row 3 'desync mode' "$fm"
      [ -n "$fs" ] && [ "$fm" = ttl ] && set_row 4 'fake ttl' "$ft" '' auto
      set_row 5 'rotate every' "$pr" '' off
      set_row 6 'rotate after' "$pb" '' off
    elif [ "$cr" = icmp ]; then
      set_row 2 governor "$([ "$gov" = true ] && echo on)" '' off
    fi
    has_ech_list "$cr" && set_row 7 ech "$ech" '' off
    set_row 8 'dns forwarder' "$dl" '' off
    set_row 9 'source ip' "$sip" '' 'default route'
    echo
    menu_line w presets t 'test now' m 'test all modes' h 'what these do'
    menu_line p 'save as profile' e 'edit any key'
    menu_line 0 back
    key_read
    case "$KEY" in
      h|H) spoofhelp_page "$n"; continue ;;
      1) # Toggle: on -> plain tunnel, off -> preset (apply_preset restarts the tunnel itself)
         echo
         if [ -n "$fs" ] || [ "$gov" = true ] || [ -n "$pr" ]; then
           confirm "Turn anti-censor OFF (plain tunnel, open connections drop)?" y && apply_preset "$n" off
         elif pick_preset "cloudflare"; then
           apply_preset "$n" "$REPLY_V"
         fi
         sleep 1 ;;
      w|W) echo
         if pick_preset "cloudflare"; then
           apply_preset "$n" "$REPLY_V"
         fi
         sleep 1 ;;
      r|R) rev_capable "$cr" || continue; echo
         if set_direction "$n"; then
           step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
           hint "Anti-censor now belongs to the dialing end: open this screen on the other server and press 1 there."
           pause; return 0
         fi
         pause ;;
      e|E) echo
         hint "Keys: $AC_KEYS"
         ask "Key to set" ""; k=$REPLY_V
         [ -n "$k" ] || continue
         case " $AC_KEYS " in *" $k "*) ;; *) err "Unknown key '$k'."; sleep 1; continue ;; esac
         ask "Value for $k (- = remove)" "$(cfg "$n" "$k")"; v=$REPLY_V
         if [ -z "$v" ] || [ "$v" = - ]; then unset_value "$n" "$k"; ok "$k removed."; changed=1
         elif [[ "$v" =~ ^[A-Za-z0-9._:/@+-]+$ ]]; then set_value "$n" "$k" "$v"; ok "$k set to $v."; changed=1
         else err "Value may only hold letters, digits and . _ : / @ + -"; fi
         sleep 1 ;;
      2) # Pick SNI (pool) or Toggle Governor (icmp)
         if [ "$cr" = icmp ]; then
           echo
           if [ "$(cfg "$n" governor)" = true ]; then
             unset_value "$n" governor; ok "Volume governor turned OFF."
           else
             set_value "$n" governor true; ok "Volume governor turned ON."
           fi
           changed=1; sleep 1; continue
         fi
         is_pool_list "$cr" || continue
         echo
         if pick_sni_preset "${fs:-mci.ir}"; then
           if [ "$REPLY_V" = off ] || [ "$REPLY_V" = 0 ]; then
             sed -i -E '/^fake-(sni|mode|ttl):/d' "$CONF/$n.yml"
             ok "Fake-SNI turned OFF."; changed=1
           else
             set_value "$n" fake-sni "$REPLY_V"
             [ -n "$(cfg "$n" fake-mode)" ] || set_value "$n" fake-mode rst
             ok "Fake-SNI set to $REPLY_V"; changed=1
           fi
         fi
         sleep 1 ;;
      3) # Pick Fake Mode
         is_pool_list "$cr" || continue
         [ -n "$(cfg "$n" fake-sni)" ] || { warn "Turn on Fake-SNI first (option 2)."; sleep 1; continue; }
         echo
         if pick_fake_mode "$fm" && ! rev_sum_refused "$n" "$REPLY_V"; then
           set_value "$n" fake-mode "$REPLY_V"
           [ "$REPLY_V" != ttl ] && unset_value "$n" fake-ttl
           ok "Fake mode set to $REPLY_V"; changed=1
         fi
         sleep 1 ;;
      4) # Fake TTL
         is_pool_list "$cr" || continue
         [ "$(cfg "$n" fake-mode)" = ttl ] || { warn "Fake TTL is only used in ttl mode."; sleep 1; continue; }
         echo
         ask "Fake TTL (hop count, empty = auto-calibrate)" "$ft"
         if [ -z "$REPLY_V" ]; then
           unset_value "$n" fake-ttl; ok "Fake TTL set to auto-calibrate."; changed=1
         elif v_fake_ttl "$REPLY_V"; then
           set_value "$n" fake-ttl "$REPLY_V"; ok "Fake TTL set to $REPLY_V."; changed=1
         fi
         sleep 1 ;;
      5) # Pool Rotate (Time)
         is_pool_list "$cr" || continue
         echo
         if pick_pool_rotate "${pr:-30m}"; then
           if [ "$REPLY_V" = off ] || [ "$REPLY_V" = 0 ]; then
             unset_value "$n" pool-rotate; ok "Pool rotate by time turned OFF."; changed=1
           else
             set_value "$n" pool-rotate "$REPLY_V"; ok "Pool rotate set to $REPLY_V."; changed=1
           fi
         fi
         sleep 1 ;;
      6) # Pool Rotate (Bytes)
         is_pool_list "$cr" || continue
         echo
         if pick_pool_rotate_bytes "${pb:-500MB}"; then
           if [ "$REPLY_V" = off ] || [ "$REPLY_V" = 0 ]; then
             unset_value "$n" pool-rotate-bytes; ok "Pool rotate by bytes turned OFF."; changed=1
           else
             set_value "$n" pool-rotate-bytes "$REPLY_V"; ok "Pool rotate bytes set to $REPLY_V."; changed=1
           fi
         fi
         sleep 1 ;;
      7) # ECH Mode
         case "$cr" in
           tls|wss|h2|grpc)
             echo
             if pick_ech "${ech:-ladder}"; then
               if [ "$REPLY_V" = off ]; then
                 unset_value "$n" ech; ok "ECH turned OFF."; changed=1
               else
                 set_value "$n" ech "$REPLY_V"; ok "ECH set to $REPLY_V."; changed=1
               fi
             fi
             sleep 1 ;;
         esac ;;
      8) # DNS Forwarder Listener
         echo
         if pick_dns_listen "${dl:-off}"; then
           if [ "$REPLY_V" = off ] || [ "$REPLY_V" = 0 ]; then
             unset_value "$n" dns-listen; ok "DNS forwarder listener turned OFF."; changed=1
           else
             set_value "$n" dns-listen "$REPLY_V"; ok "DNS forwarder listening on $REPLY_V."; changed=1
           fi
         fi
         sleep 1 ;;
      9) # Carrier Source IP Binding
         echo
         if pick_src_ip "${sip:-off}"; then
           if [ "$REPLY_V" = off ] || [ "$REPLY_V" = 0 ]; then
             unset_value "$n" src-ip; ok "Carrier source IP binding turned OFF."; changed=1
           else
             set_value "$n" src-ip "$REPLY_V"; ok "Carrier bound to source IP $REPLY_V."; changed=1
           fi
         fi
         sleep 1 ;;
      t|T)
         anticensor_test "$n"
         pause ;;
      m|M)
         ac_matrix_cmd "$n"
         pause ;;
      p|P)
         echo
         ask "Profile name to save" ""
         if [ -n "$REPLY_V" ]; then
           profile_cmd save "$REPLY_V" "$n"
           sleep 1
         fi ;;
      b|0|q|enter|esc) break ;;
      *) : ;;
    esac
  done
  if [ "$changed" = 1 ]; then
    hint "Applying changes: restarting '$n'..."
    step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
  fi
}

# ---- spoofing vs shaping: what each anti-censor option actually does (matches docs/TECHNICAL.md) ----
# One page, no network calls. The classification is the docs' one: fake-sni is the only true spoof, everything that
# changes our own packet bytes/sizes/timing is shape, FEC/governor are neither, and tunnel-level spoofing is not shipped.
spoofhelp_page() { # [name]
  page "Spoofing & shaping" "${1:-}"
  printf '  %sSpoof%s    fake-sni          decoy TLS hello (peer drops it)\n' "$CYN" "$RST"
  printf '  %sShape%s    tcp-mimic, tls-frag, ech, hdr-mask, udp-dns, pool-rotate, shape-data, noise\n' "$CYN" "$RST"
  printf '  %sOther%s    fec (loss parity) · governor (ICMP pacing)\n\n' "$CYN" "$RST"
  hint "Auto mode can also test the 13 F19 shaped carriers: --extended on the exit server (both ends 3.3.0)."
  hint "Does not hide server IPs, traffic volume/timing, or the entry server↔user plaintext (no VLESS/Trojan handshake mimicry)."
  echo
  printf '  %s%-30s %s%s\n' "$BOLD" "Symptom" "Use" "$RST"
  printf '  %-30s %s\n' "SNI allowlist cuts flow" "rst/synrst mode"
  printf '  %-30s %s\n' "SNI black-holed after hello" "ech (wss/grpc via Cloudflare)"
  printf '  %-30s %s\n' "Non-TLS first bytes cut" "tcp-mimic + hdr-mask"
  printf '  %-30s %s\n' "UDP cut, DNS/53 passes" "udp-dns on both ends"
  printf '  %-30s %s\n' "Flow time/byte cap" "pool-rotate / pool-rotate-bytes"
  printf '  %-30s %s\n' "ICMP throttled at volume" "governor + max-mbps"
  echo
  hint "Full table: docs/TECHNICAL.md"
  pause
}

# ---- resilience profiles: save one tunnel's working fake-sni/pool-rotate combination, re-apply it later ----
prof_names() { local f; for f in "$CONF/profiles"/*.env; do [ -e "$f" ] || continue; basename "$f" .env; done; }
prof_path() { echo "$CONF/profiles/$1.env"; }
v_prof_name() { [[ "$1" =~ ^[a-zA-Z0-9_-]{1,32}$ ]] || { err "Profile name: 1-32 letters, digits, - or _."; return 1; }; return 0; }
prof_read() { # file -> the KEY=VALUE lines this manager wrote (comments and anything else are ignored)
  local l
  [ -f "$1" ] || return 0
  while IFS= read -r l; do
    case "$l" in FAKESNI=*|FAKEMODE=*|FAKETTL=*|POOLROT=*|POOLBYTES=*|ECH=*|GOVERNOR=*|DNSLISTEN=*|SRCIP=*) echo "$l" ;; esac
  done <"$1"
}
prof_pick_defaults() { # fill the wizard's resilience defaults from a saved profile (interactive only)
  local names pick l k v
  names=$(prof_names)
  [ -n "$names" ] || return 0
  echo
  hint "Saved resilience profiles: $(echo "$names" | tr '\n' ' ')"
  ask "Start from a saved profile (name, empty = skip)" ""; pick=$REPLY_V
  [ -n "$pick" ] || return 0
  [ -f "$(prof_path "$pick")" ] || { err "No profile named '$pick'."; return 0; }
  while IFS= read -r l; do
    k=${l%%=*}; v=${l#*=}
    case "$k" in
      FAKESNI) T_FAKESNI=$v ;; FAKEMODE) T_FAKEMODE=$v ;; FAKETTL) T_FAKETTL=$v ;;
      POOLROT) T_POOLROT=$v ;; POOLBYTES) T_POOLBYTES=$v ;;
      ECH) T_ECH=$v ;; GOVERNOR) T_GOVERNOR=$v ;;
      DNSLISTEN) T_DNSLISTEN=$v ;; SRCIP) T_SRCIP=$v ;;
    esac
  done < <(prof_read "$(prof_path "$pick")")
  hint "Profile '$pick' loaded as the defaults below; press Enter to keep each."
}
prof_only_tunnel() { # the single Iran pool tunnel, when there is exactly one
  local n count=0 pick=''
  for n in $(tunnels); do
    [ "$(role "$n")" = Iran ] && is_pool_list "$(cfg "$n" carrier)" || continue
    count=$((count+1)); pick=$n
  done
  [ "$count" = 1 ] && echo "$pick"
  return 0
}

blackout_cmd() { # name [sni_or_preset] : turn the resilience kit on when a censor starts blocking the tunnel.
  local n=$1 sni=${2:-}
  [ "$(uname -s)" = Linux ] || { err "The resilience kit is a Linux feature (fake-SNI needs CAP_NET_RAW, like the icmp carrier)."; return 1; }
  [ -f "$CONF/$n.yml" ] || { err "No tunnel named '$n'."; return 1; }
  ac_dialer "$n" || {
    err "'$n' does not dial the carrier, so anti-censorship runs on its other end (the entry server normally, the exit server when reverse)."; return 1; }

  if [ -z "$sni" ] && [ "$NONINTERACTIVE" != 1 ]; then
    echo
    say "  ${BOLD}Blackout Resilience Activation for '$n'${RST}"
    say "  Under an SNI allowlist or blackout, choose an operator preset or allowlisted domain."
    echo
    pick_preset "mci" || return 1; sni=$REPLY_V
  fi
  [ -n "$sni" ] || { err "An allowlisted name or preset is required (blackout $n mci.ir or blackout $n mci)."; return 1; }

  if is_builtin_preset "$sni"; then
    apply_preset "$n" "$sni" || return 1
    if [ -t 0 ] && [ "$NONINTERACTIVE" != 1 ] && [ "${WAT_MANAGER_LIB:-0}" != 1 ]; then
      anticensor_test "$n"
    fi
    return 0
  fi

  # Custom SNI domain
  [ "$(role "$n")" = Iran ] && is_pool "$(cfg "$n" carrier)" && ! is_reverse "$n" || {
    err "'$n' is not a direct entry tunnel on a pool carrier (tcp, tls, ws, wss, h2, h2c, grpc); the kit is client-only and only attaches there."; return 1; }
  v_sni_name "$sni" || return 1
  [ "$(bin_ver_ok 2.7.0)" = 1 ] || { err "fake-sni needs wattun 2.7.0 or newer on this server (run: $SELF update)."; return 1; }
  set_value "$n" fake-sni "$sni"
  set_value "$n" fake-mode rst
  unset_value "$n" fake-ttl
  ok "Resilience kit on: fake-sni $sni (rst mode). pool-rotate stays off; tune later: tunnel page -> o -> k."
  if step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"; then
    ok "Restart applied. Watch whether the link comes back: $SELF test $n"
    if [ -t 0 ] && [ "$NONINTERACTIVE" != 1 ] && [ "${WAT_MANAGER_LIB:-0}" != 1 ]; then
      anticensor_test "$n"
    fi
  else
    err "Restart failed: run  systemctl restart ${WAT_PREFIX}@$n"; return 1
  fi
  return 0
}

arm_blackout_cmd() { # name
  local n=$1 r
  [ -f "$CONF/$n.yml" ] || { err "No tunnel named '$n'."; return 1; }
  r=$(role "$n")
  if [ "$r" = Kharej ]; then
    say "  ${BOLD}Arming exit server '$n' in Fortress Mode for Blackout Resilience${RST}"
    if [ "$(uname -s)" = Linux ]; then
      sysctl -w net.ipv4.icmp_echo_ignore_all=0 >/dev/null 2>&1 || true
      sysctl -w net.core.default_qdisc=fq >/dev/null 2>&1 || true
      sysctl -w net.ipv4.tcp_congestion_control=bbr >/dev/null 2>&1 || true
      sysctl -w net.core.rmem_max=67108864 >/dev/null 2>&1 || true
      sysctl -w net.core.wmem_max=67108864 >/dev/null 2>&1 || true
    fi
    local ptcp ptls pwss pudp used_b=''
    ptcp=$(rand_open_port tcp "$used_b") || { err "No free TCP port for blackout tcp listener."; return 1; }
    used_b+=" $ptcp"
    ptls=$(rand_open_port tcp "$used_b") || { err "No free TCP port for blackout tls listener."; return 1; }
    used_b+=" $ptls"
    pwss=$(rand_open_port tcp "$used_b") || { err "No free TCP port for blackout wss listener."; return 1; }
    used_b+=" $pwss"
    pudp=$(rand_open_port udp "$used_b") || { err "No free UDP port for blackout udp listener."; return 1; }
    sed -i -E '/^(listen|listen-[a-z0-9-]+):/d' "$CONF/$n.yml"
    set_value "$n" carrier 'icmp+tcp+tls+wss+udp'
    set_value "$n" listen-tcp "\":$ptcp\""
    set_value "$n" listen-tls "\":$ptls\""
    set_value "$n" listen-wss "\":$pwss\""
    set_value "$n" listen-udp "\":$pudp\""
    [ -n "$(cfg "$n" path)" ] || set_value "$n" path "$(rand_path)"
    [ -n "$(cfg "$n" dns-relay-upstream)" ] || set_value "$n" dns-relay-upstream "1.1.1.1:53"
    fw_open "$ptcp/tcp $ptls/tcp $pwss/tcp $pudp/udp" >/dev/null 2>&1 || true
    systemctl restart "${WAT_PREFIX}@$n" >/dev/null 2>&1 || true
    ok "Exit server '$n' armed in Fortress Mode (ICMP, TCP:$ptcp, TLS:$ptls, WSS:$pwss, UDP:$pudp)."
    say "  Emergency blackout token for the entry server distribution:"
    refresh_token "$n" fortress
    show_token "$n"
  else
    say "  ${BOLD}Arming entry server '$n' for Autonomous Blackout Failover${RST}"
    set_value "$n" path-probe-max "6s"
    set_value "$n" governor true
    heal_enable >/dev/null 2>&1 || true
    systemctl restart "${WAT_PREFIX}@$n" >/dev/null 2>&1 || true
    ok "Entry server '$n' armed for Autonomous Failover (fast silence detection, auto-heal timer active)."
  fi
  return 0
}

audit_blackout_cmd() { # name
  local n=$1 r pid pass_cnt=0 fail_cnt=0
  [ -f "$CONF/$n.yml" ] || { err "No tunnel named '$n'."; return 1; }
  r=$(role "$n")
  echo
  say "  ${BOLD}Blackout Preparedness Audit for '$n' ($r)${RST}"
  echo
  pid=$(systemctl show -p MainPID --value "${WAT_PREFIX}@$n" 2>/dev/null || echo 0)
  if [ -n "$pid" ] && [ "$pid" -gt 0 ] && [ -r "/proc/$pid/status" ]; then
    local cap_eff; cap_eff=$(grep -i CapEff "/proc/$pid/status" 2>/dev/null | awk '{print $2}')
    if [ -n "$cap_eff" ]; then
      ok "Process capabilities active (PID $pid, CapEff $cap_eff)"
      pass_cnt=$((pass_cnt+1))
    else
      warn "Unable to read process capabilities"
      fail_cnt=$((fail_cnt+1))
    fi
  else
    warn "Tunnel process is not currently running"
    fail_cnt=$((fail_cnt+1))
  fi

  if [ "$(uname -s)" = Linux ]; then
    local icmp_ign; icmp_ign=$(sysctl -n net.ipv4.icmp_echo_ignore_all 2>/dev/null || echo 1)
    if [ "$icmp_ign" = 0 ]; then
      ok "Sysctl: net.ipv4.icmp_echo_ignore_all == 0 (ICMP replies enabled)"
      pass_cnt=$((pass_cnt+1))
    else
      ok "Sysctl: net.ipv4.icmp_echo_ignore_all == 1 (plain ping is off; the ICMP tunnel still receives its packets)"
      pass_cnt=$((pass_cnt+1))
    fi
    local cc; cc=$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo cubic)
    if [ "$cc" = bbr ]; then
      ok "Sysctl: congestion control is BBR"
      pass_cnt=$((pass_cnt+1))
    else
      hint "Sysctl: congestion control is $cc (BBR recommended for anti-policing)"
    fi
  fi

  if [ "$r" = Kharej ]; then
    local lline lp lcar lpr lchk
    while IFS= read -r lline; do
      [ -n "$lline" ] || continue
      lcar=${lline%%:*}; [ "$lcar" = listen ] && lcar=$(cfg "$n" carrier) || lcar=${lcar#listen-}
      lp=${lline#*:}; lp=${lp//\"/}; lp=${lp//\'/}; lp=${lp##*:}; lp=${lp//[[:space:]]/}
      [[ "$lp" =~ ^[0-9]+$ ]] || continue
      lpr=$(rproto "$lcar")
      lchk=$(port_user "$lp" "$lpr" 2>/dev/null || true)
      if [ -n "$lchk" ] && [[ "$lchk" != *"wattun"* ]]; then
        warn "Port $lp/$lpr bound by another process: $lchk"
        fail_cnt=$((fail_cnt+1))
      else
        ok "Port $lp/$lpr available or bound by wattun"
        pass_cnt=$((pass_cnt+1))
      fi
    done < <(grep -E '^listen(-[a-z0-9-]+)?:' "$CONF/$n.yml" 2>/dev/null)
  fi

  local dns_up; dns_up=$(cfg "$n" dns-relay-upstream)
  if [ -n "$dns_up" ]; then
    ok "DNS in-band relay configured ($dns_up)"
    pass_cnt=$((pass_cnt+1))
  else
    hint "DNS in-band relay not configured (default upstreams active)"
  fi

  local st; st=$(systemctl is-active "${WAT_PREFIX}@$n" 2>/dev/null || echo inactive)
  if [ "$st" = active ]; then
    ok "Service ${WAT_PREFIX}@$n is active"
    pass_cnt=$((pass_cnt+1))
  else
    warn "Service ${WAT_PREFIX}@$n is $st"
    fail_cnt=$((fail_cnt+1))
  fi

  echo
  if [ "$fail_cnt" -eq 0 ]; then
    say "  ${GRN}${BOLD}OVERALL STATUS: ARMED & READY FOR BLACKOUT${RST} (${pass_cnt} checks passed)"
  else
    say "  ${YEL}${BOLD}OVERALL STATUS: PARTIALLY ARMED${RST} (${pass_cnt} passed, ${fail_cnt} warnings)"
  fi
  echo
  return 0
}

preset_cmd() { # name [preset]
  local n=$1 p=${2:-}
  [ "$(uname -s)" = Linux ] || { err "Anti-censorship presets are a Linux feature."; return 1; }
  [ -f "$CONF/$n.yml" ] || { err "No tunnel named '$n'."; return 1; }
  ac_dialer "$n" || { err "'$n' does not dial the carrier, so presets run on its other end (the entry server normally, the exit server when reverse)."; return 1; }
  if [ -z "$p" ] && [ "$NONINTERACTIVE" != 1 ]; then
    pick_preset "cloudflare" || return 1; p=$REPLY_V
  fi
  [ -n "$p" ] || { err "A preset name is required (preset $n mci). Available: cloudflare, rst-fast, mci, irancell, blackout, conservative"; return 1; }
  v_preset "$p" || return 1
  apply_preset "$n" "$p" || return 1
  if [ -t 0 ] && [ "$NONINTERACTIVE" != 1 ] && [ "${WAT_MANAGER_LIB:-0}" != 1 ]; then
    anticensor_test "$n"
  fi
  return 0
}

profile_cmd() { # profile save|list|show|del|apply NAME [tunnel]
  local sub name tun f names x tmp
  sub=${1:-}; name=${2:-}; tun=${3:-}
  case "$sub" in
    save)
      if is_builtin_preset "$name"; then
        err "'$name' is a built-in preset name. Choose another name for your custom profile."
        return 1
      fi
      v_prof_name "$name" || return 1
      [ -n "$tun" ] || tun=$(prof_only_tunnel)
      [ -n "$tun" ] || { err "Name the tunnel explicitly (profile save $name TUNNEL)."; return 1; }
      [ -f "$CONF/$tun.yml" ] || { err "No tunnel named '$tun'."; return 1; }
      [ "$(uname -s)" = Linux ] || { err "Resilience profiles are a Linux feature (fake-SNI needs CAP_NET_RAW, like the icmp carrier)."; return 1; }
      mkdir -p "$CONF/profiles"
      f=$(prof_path "$name"); tmp="$f.tmp.$$"
      if { echo "# WatTunnel resilience profile: $name"
           echo "# From tunnel $tun, saved $(date -u '+%Y-%m-%d %H:%M UTC'). Apply: $SELF profile apply $name TUNNEL"
           echo "# FAKESNI   allowlisted server name (e.g. mci.ir); empty = fake-SNI off"
           echo "# FAKEMODE  seq | ttl | sum | seqsum | auto | rst | synrst"
           echo "# FAKETTL   hop count for fake-mode ttl; empty = auto-calibrate"
           echo "# POOLROT   recycle each healthy pool connection after this long (90s, 30m, 4h); empty = off"
           echo "# POOLBYTES recycle after this much traffic (500MB, 4G); empty = off"
           echo "# ECH       ECH mode: ladder | auto | off"
           echo "# GOVERNOR  ICMP volume pacer: true | false"
           echo "FAKESNI=$(cfg "$tun" fake-sni)"
           echo "FAKEMODE=$(cfg "$tun" fake-mode)"
           echo "FAKETTL=$(cfg "$tun" fake-ttl)"
           echo "POOLROT=$(cfg "$tun" pool-rotate)"
           echo "POOLBYTES=$(cfg "$tun" pool-rotate-bytes)"
           echo "ECH=$(cfg "$tun" ech)"
           echo "GOVERNOR=$(cfg "$tun" governor)"
           echo "DNSLISTEN=$(cfg "$tun" dns-listen)"
           echo "SRCIP=$(cfg "$tun" src-ip)"
         } >"$tmp"; then
        wmv "$tmp" "$f"
        ok "Profile '$name' saved (from $tun). Re-apply later: $SELF profile apply $name TUNNEL."
      else rm -f "$tmp"; err "Could not write $(prof_path "$name")."; return 1
      fi ;;
    list)
      say "  ${BOLD}Built-in Presets:${RST}"
      echo "  rst-fast     Fastest direct setup (www.cloudflare.com, rst, 4 sessions x 4 conns, 30m)"
      echo "  mci          Iran Whitelist - MCI (mci.ir, rst, 30m, 500MB, ECH ladder)"
      echo "  irancell     Iran Whitelist - Irancell/Mokhaberat (irancell.ir, seq, 20m, 300MB, ECH ladder)"
      echo "  blackout     Emergency Blackout Mode (mci.ir, rst, 90s, 100MB, ECH ladder)"
      echo "  conservative Conservative / Low-Churn (mci.ir, seq, 4h, 4GB, ECH auto)"
      echo
      say "  ${GRY}saved profiles${RST}"
      names=$(prof_names)
      if [ -n "$names" ]; then
        echo "$names" | while read -r x; do echo "  $x"; done
      else
        hint "No custom saved profiles."
      fi ;;
    show)
      if is_builtin_preset "$name"; then
        show_builtin_preset "$name"
      else
        v_prof_name "$name" || return 1
        if [ -f "$(prof_path "$name")" ]; then
          cat "$(prof_path "$name")"
        else
          err "No profile named '$name'."
          return 1
        fi
      fi ;;
    del|delete|rm)
      if is_builtin_preset "$name"; then
        err "Cannot delete built-in preset '$name'."
        return 1
      fi
      v_prof_name "$name" || return 1
      [ -f "$(prof_path "$name")" ] || { err "No profile named '$name'."; return 1; }
      rm -f "$(prof_path "$name")"; ok "Profile '$name' deleted." ;;
    apply)
      if is_builtin_preset "$name"; then
        [ -n "$tun" ] || tun=$(prof_only_tunnel)
        [ -n "$tun" ] || { err "Name the tunnel explicitly (profile apply $name TUNNEL)."; return 1; }
        [ -f "$CONF/$tun.yml" ] || { err "No tunnel named '$tun'."; return 1; }
        apply_preset "$tun" "$name" || return 1
      else
        v_prof_name "$name" || return 1
        [ -n "$tun" ] || tun=$(prof_only_tunnel)
        [ -n "$tun" ] || { err "Name the tunnel explicitly (profile apply $name TUNNEL)."; return 1; }
        [ -f "$CONF/$tun.yml" ] || { err "No tunnel named '$tun'."; return 1; }
        [ "$(role "$tun")" = Iran ] || { err "'$tun' is not an entry tunnel; these keys are client-only."; return 1; }
        if [ -f "$(prof_path "$name")" ]; then
          [ "$(role "$tun")" = Iran ] && is_pool_list "$(cfg "$tun" carrier)" || { err "'$tun' is not an entry tunnel on a pool carrier (tcp, tls, ws, wss, h2, h2c, grpc, alone or bonded); these keys are client-only."; return 1; }
          prof_apply "$name" "$tun" || return 1
        else
          err "No profile named '$name'."
          return 1
        fi
      fi ;;
    *) err "profile: use save, list, show, del or apply."; return 1 ;;
  esac
  return 0
}

prof_apply() { # profile tunnel : write the tunnel's resilience keys from a saved profile, then restart
  local name=$1 tun=$2 l k v changed=0
  local fs='' fm='' ft='' pr='' pb='' ech='' gov='' dl='' sip=''
  while IFS= read -r l; do
    k=${l%%=*}; v=${l#*=}
    case "$k" in
      FAKESNI) fs=$v ;; FAKEMODE) fm=$v ;; FAKETTL) ft=$v ;; POOLROT) pr=$v ;; POOLBYTES) pb=$v ;;
      ECH) ech=$v ;; GOVERNOR) gov=$v ;; DNSLISTEN) dl=$v ;; SRCIP) sip=$v ;;
    esac
  done < <(prof_read "$(prof_path "$name")")
  if [ -n "$fs" ]; then
    [ "$(bin_ver_ok 2.7.0)" = 1 ] || { err "fake-sni needs wattun 2.7.0 or newer (run: $SELF update)."; return 1; }
    set_value "$tun" fake-sni "$fs"; changed=1
  elif [ -n "$(cfg "$tun" fake-sni)" ]; then
    unset_value "$tun" fake-sni; unset_value "$tun" fake-mode; unset_value "$tun" fake-ttl; changed=1
  fi
  if [ -n "$fs" ] && [ -n "$fm" ]; then
    v_fake_mode "$fm" || return 1
    rev_sum_refused "$tun" "$fm" && return 1
    case "$fm" in
      auto|rst) [ "$(bin_ver_ok 2.9.0)" = 1 ] || { err "fake-mode $fm needs wattun 2.9.0 or newer (run: $SELF update)."; return 1; } ;;
      synrst) [ "$(bin_ver_ok 2.10.5)" = 1 ] || { err "fake-mode synrst needs wattun 2.10.5 or newer (run: $SELF update)."; return 1; } ;;
      paws) [ "$(bin_ver_ok 3.0.2)" = 1 ] || { err "fake-mode paws needs wattun 3.0.2 or newer (run: $SELF update)."; return 1; } ;;
      seqsum) [ "$(bin_ver_ok 2.8.0)" = 1 ] || { err "fake-mode seqsum needs wattun 2.8.0 or newer (run: $SELF update)."; return 1; } ;;
      sum) [ "$(bin_ver_ok 2.7.1)" = 1 ] || { err "fake-mode sum needs wattun 2.7.1 or newer (run: $SELF update)."; return 1; } ;;
    esac
    set_value "$tun" fake-mode "$fm"; changed=1
    if [ "$fm" = ttl ] && [ -n "$ft" ]; then set_value "$tun" fake-ttl "$ft"; else unset_value "$tun" fake-ttl; fi
  fi
  if [ -n "$pr" ] && [ "$pr" != 0 ] && [ "$pr" != off ]; then
    [ "$(bin_ver_ok 2.8.0)" = 1 ] || { err "pool-rotate needs wattun 2.8.0 or newer (run: $SELF update)."; return 1; }
    set_value "$tun" pool-rotate "$pr"; changed=1
  elif [ -n "$(cfg "$tun" pool-rotate)" ]; then unset_value "$tun" pool-rotate; changed=1
  fi
  if [ -n "$pb" ] && [ "$pb" != 0 ] && [ "$pb" != off ]; then
    [ "$(bin_ver_ok 2.8.1)" = 1 ] || { err "pool-rotate-bytes needs wattun 2.8.1 or newer (run: $SELF update)."; return 1; }
    set_value "$tun" pool-rotate-bytes "$pb"; changed=1
  elif [ -n "$(cfg "$tun" pool-rotate-bytes)" ]; then unset_value "$tun" pool-rotate-bytes; changed=1
  fi
  if [ -n "$ech" ] && [ "$ech" != off ]; then
    [ "$(bin_ver_ok 2.9.0)" = 1 ] || { err "ech needs wattun 2.9.0 or newer (run: $SELF update)."; return 1; }
    set_value "$tun" ech "$ech"; changed=1
  elif [ -n "$(cfg "$tun" ech)" ]; then unset_value "$tun" ech; changed=1
  fi
  if [ "$gov" = true ] || [ "$gov" = on ]; then
    [ "$(bin_ver_ok 2.9.0)" = 1 ] || { err "governor needs wattun 2.9.0 or newer (run: $SELF update)."; return 1; }
    set_value "$tun" governor true; changed=1
  elif [ -n "$(cfg "$tun" governor)" ]; then unset_value "$tun" governor; changed=1
  fi
  if [ -n "$dl" ] && [ "$dl" != off ]; then
    set_value "$tun" dns-listen "$dl"; changed=1
  elif [ -n "$(cfg "$tun" dns-listen)" ]; then unset_value "$tun" dns-listen; changed=1
  fi
  if [ -n "$sip" ] && [ "$sip" != off ]; then
    set_value "$tun" src-ip "$sip"; changed=1
  elif [ -n "$(cfg "$tun" src-ip)" ]; then unset_value "$tun" src-ip; changed=1
  fi
  [ "$changed" = 1 ] || { hint "Nothing to change."; return 0; }
  ok "Profile '$name' applied to $tun."
  if step "Restarting ${WAT_PREFIX}@$tun" systemctl restart "${WAT_PREFIX}@$tun"; then ok "Restart applied."
  else err "Restart failed: run  systemctl restart ${WAT_PREFIX}@$tun"; return 1; fi
  return 0
}

change_type() { # name : one place to change how the two servers connect, whatever kind of tunnel this is
  local n=$1 c; c=$(cfg "$n" carrier)
  echo
  if is_shaped_list "$c"; then shaped_warn "$c"; fi # F19: repeat the wattun-internal note where the type is shown
  if [ "$(role "$n")" = Iran ]; then
    if [ -f "$CONF/$n.auto" ]; then
      auto_test_cmd "$n"; return
    fi
    say "  In use: $c. The exit server fixed this type when it made the token."
    hint "To choose freely: on the exit server press n, then paste the new token here with t."
    return 0
  fi
  if is_auto_kharej "$n"; then
    say "  In use: $(in_use "$n" | sed 's/^$/none yet/'). The entry server chooses the type: on the entry server, tunnel page, c."
    return 0
  fi
  say "  In use: $c, fixed when the tunnel was made."
  hint "To let the entry server choose: press n here, paste the token on the entry server with t, then delete this tunnel."
}
# ======================================================================================
#  Kernel Speed Boost (/boost)
# ======================================================================================
BOOST_SYSCTL=/etc/sysctl.d/99-$WAT_PREFIX-boost.conf
BOOST_OFF=$CONF/.boost-off # written by boost --undo: the installer's automatic boost leaves this server alone
is_container() {
  if [ -f /.dockerenv ] || [ -f /run/.containerenv ]; then return 0; fi
  if command -v systemd-detect-virt >/dev/null 2>&1 && systemd-detect-virt --container -q 2>/dev/null; then return 0; fi
  if [ -f /proc/user_beancounters ]; then return 0; fi
  if [ ! -w /proc/sys/net/ipv4/tcp_congestion_control ]; then return 0; fi
  return 1
}
boost_status() {
  local cc qdisc rmax wmax
  cc=$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || cat /proc/sys/net/ipv4/tcp_congestion_control 2>/dev/null || echo unknown)
  qdisc=$(sysctl -n net.core.default_qdisc 2>/dev/null || cat /proc/sys/net/core/default_qdisc 2>/dev/null || echo unknown)
  rmax=$(sysctl -n net.core.rmem_max 2>/dev/null || cat /proc/sys/net/core/rmem_max 2>/dev/null || echo 0)
  wmax=$(sysctl -n net.core.wmem_max 2>/dev/null || cat /proc/sys/net/core/wmem_max 2>/dev/null || echo 0)
  if [ -f "$BOOST_SYSCTL" ]; then say "  $(kv boost "${GRN}on${RST}")"
  else say "  $(kv boost "${GRY}off${RST}")"; fi
  say "  $(kv congestion "$cc")"
  say "  $(kv qdisc "$qdisc")"
  say "  $(kv 'rmem max' "$(human "$rmax")")"
  say "  $(kv 'wmem max' "$(human "$wmax")")"
  is_container && warn "Container environment: sysctl writes may be restricted."
  boost_nic_hint
  return 0
}
default_dev() { ip route show default 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "dev") { print $(i+1); exit }}'; }
boost_qdisc() { # put the default-route interface on fq now: default_qdisc alone only covers interfaces created later
  # Field 2026-11-08 (Iran VPS): boost had set default_qdisc=fq, eth0 stayed pfifo_fast until a reboot.
  local dev cur
  [ "$SANDBOX" = 1 ] && return 0
  command -v tc >/dev/null 2>&1 || return 0
  dev=$(default_dev); [ -n "$dev" ] || return 0
  cur=$(tc qdisc show dev "$dev" root 2>/dev/null | awk '{print $2; exit}')
  case "$cur" in
    mq) tc qdisc replace dev "$dev" root mq 2>/dev/null ;; # re-creates the per-queue children with default_qdisc
    pfifo_fast|pfifo|fq_codel) tc qdisc replace dev "$dev" root fq 2>/dev/null ;;
  esac # any other root (htb, cake, tbf ...) is someone's own shaping: left alone
  return 0
}
boost_nic_hint() { # an emulated NIC is the usual 1 Gbit/s limit on a cheap VPS, and no setting here fixes it
  local dev drv
  command -v ethtool >/dev/null 2>&1 || return 0
  dev=$(default_dev); [ -n "$dev" ] || return 0
  drv=$(ethtool -i "$dev" 2>/dev/null | sed -n 's/^driver: //p')
  case "$drv" in
    e1000|e1000e|8139cp|8139too|rtl8139|pcnet32|ne2k-pci)
      warn "Network card: $drv (emulated). One CPU core handles every packet, which usually caps the server below 1 Gbit/s."
      hint "Ask your provider to switch this VPS to a virtio network card." ;;
  esac
  return 0
}
boost_apply() {
  if is_container; then
    warn "Container environment detected. Sysctl writes may be restricted by the host."
  fi
  mkdir -p "${BOOST_SYSCTL%/*}"
  cat >"$BOOST_SYSCTL" <<EOF
# WatTunnel High-Speed Transport Engine Tunables (/boost)
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.rmem_max = 67108864
net.core.wmem_max = 67108864
net.core.rmem_default = 33554432
net.core.wmem_default = 33554432
net.ipv4.tcp_rmem = 4096 87380 67108864
net.ipv4.tcp_wmem = 4096 65536 67108864
net.core.netdev_max_backlog = 100000
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_fastopen = 3
EOF
  chmod 644 "$BOOST_SYSCTL"
  modprobe tcp_bbr 2>/dev/null || true
  if command -v sysctl >/dev/null 2>&1; then
    sysctl -p "$BOOST_SYSCTL" >/dev/null 2>&1 || sysctl --system >/dev/null 2>&1 || true
  fi
  boost_qdisc
  rm -f "$BOOST_OFF"
  ok "Boost parameters written to $BOOST_SYSCTL and applied."
  boost_status
}
boost_undo() {
  rm -f "$BOOST_SYSCTL"
  mkdir -p "$CONF" && : >"$BOOST_OFF"
  if command -v sysctl >/dev/null 2>&1; then
    sysctl --system >/dev/null 2>&1 || true
  fi
  ok "Removed $BOOST_SYSCTL and reloaded system defaults."
  boost_status
}
boost_cmd() {
  case "${1:-}" in
    --status|-s|status) boost_status ;;
    --undo|-u|undo) boost_undo ;;
    --yes|-y|apply|"") boost_apply ;;
    auto) # the installer and wattun update: on by default, except in a container or after boost --undo
      [ -f "$BOOST_OFF" ] || is_container || boost_apply >/dev/null 2>&1; return 0 ;;
    *) err "Usage: $SELF boost [--status|--undo|--yes]"; return 1 ;;
  esac
}
boost_menu() {
  while :; do
    page "Kernel speed boost"
    boost_status
    echo
    menu_line a 'enable (bbr, fq, 64 MiB)' u 'restore defaults' 0 back
    key_read
    case "$KEY" in
      a) boost_apply; pause ;;
      u) confirm "Restore default kernel sysctl values?" y && boost_undo; pause ;;
      b|0|q|enter|esc) return 0 ;;
    esac
  done
}

# ======================================================================================
#  Off-Peak Auto-Optimize (Timer)
# ======================================================================================
OPTIMIZE_UNIT=$WAT_PREFIX-auto-optimize
optimize_enable() {
  local mgr=/usr/local/bin/wattun-manager
  [ "$SANDBOX" = 1 ] && mgr=$MGR
  {
    printf '[Unit]\nDescription=WatTunnel off-peak auto-optimize%s\n[Service]\nType=oneshot\n' "$([ "$SANDBOX" = 1 ] && echo " (sandbox $WAT_PREFIX)")"
    unit_env_lines
    printf 'ExecStart=%s auto-optimize\n' "$mgr"
  } >"/etc/systemd/system/$OPTIMIZE_UNIT.service"
  cat >"/etc/systemd/system/$OPTIMIZE_UNIT.timer" <<EOF
[Unit]
Description=WatTunnel off-peak auto-optimize daily at 04:30
[Timer]
OnCalendar=*-*-* 04:30:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
  chmod 644 "/etc/systemd/system/$OPTIMIZE_UNIT.service" "/etc/systemd/system/$OPTIMIZE_UNIT.timer"
  systemctl daemon-reload && systemctl enable --now "$OPTIMIZE_UNIT.timer" >/dev/null 2>&1 && ok "Auto-optimize timer enabled (daily at 04:30)."
}
optimize_disable() {
  systemctl disable --now "$OPTIMIZE_UNIT.timer" >/dev/null 2>&1; ok "Auto-optimize timer disabled."
}
auto_optimize_all() {
  local n
  for n in $(tunnels); do
    if [ "$(role "$n")" = Iran ] && [ -f "$CONF/$n.auto" ]; then
      logger -t wattun-auto-optimize "running scheduled off-peak optimization for $n"
      AUTO_OPTIMIZE=1 auto_retest "$n"
    fi
  done
}

# ======================================================================================
#  Bond auto-retest (F10): re-test the carriers of a bond on a schedule and add one back
#  when it works again (a censor can block one leg of a bond for hours and then clear it).
#  Settings live in the $CONF/NAME.bondretest sidecar, never in NAME.yml: the engine
#  rejects unknown YAML keys and only ports:/limits: hot-reload.
# ======================================================================================
BONDRETEST_BUDGET_MB=20 # traffic budget of one run, .manager.conf key bondretest-budget
bond_is_bond() { case "${1:-}" in *+*) return 0 ;; esac; return 1; }
bond_retest_visible() { # role carrier -> 0 when the setting belongs on this tunnel (a bonded Iran client)
  [ "${1:-}" = Iran ] && bond_is_bond "${2:-}"
}
bondretest_ok() { # value -> the stored form (off|30m|1h|6h|daily-offpeak) ; rc 1 on anything else
  case "${1,,}" in
    off|0|none|never) echo off ;;
    30m|30min|half-hour) echo 30m ;;
    1h|60m|hourly) echo 1h ;;
    6h|360m) echo 6h ;;
    daily-offpeak|daily|offpeak|off-peak) echo daily-offpeak ;;
    *) return 1 ;;
  esac
}
v_bondretest() { # validator for ask_ok: normalizes the value into REPLY_V
  local v
  v=$(bondretest_ok "$1") || { err "Use off, 30m, 1h, 6h or daily-offpeak."; return 1; }
  REPLY_V=$v; return 0
}
bondretest_get() { # name -> stored value (off when the sidecar is missing or unreadable)
  local v=''
  [ -f "$CONF/$1.bondretest" ] && v=$(head -1 "$CONF/$1.bondretest" 2>/dev/null | tr -d '[:space:]')
  bondretest_ok "${v:-off}" || echo off
}
bondretest_set_file() { # name value : write the sidecar atomically, like every other state file here
  local n=$1 v
  v=$(bondretest_ok "$2") || return 1
  ( umask 077; printf '%s\n' "$v" >"$CONF/$n.bondretest.tmp" ) && mv -f "$CONF/$n.bondretest.tmp" "$CONF/$n.bondretest"
}
bondretest_timer_lines() { # value -> the [Timer] lines (pure; the self-test pins every schedule)
  case "$1" in
    30m) printf 'OnBootSec=5min\nOnUnitActiveSec=30min\nRandomizedDelaySec=60\nPersistent=true\n' ;;
    1h)  printf 'OnBootSec=5min\nOnUnitActiveSec=1h\nRandomizedDelaySec=60\nPersistent=true\n' ;;
    6h)  printf 'OnBootSec=5min\nOnUnitActiveSec=6h\nRandomizedDelaySec=60\nPersistent=true\n' ;;
    daily-offpeak) printf 'OnCalendar=*-*-* 04:15:00\nRandomizedDelaySec=300\nPersistent=true\n' ;;
  esac
}
bondretest_unit() { echo "${WAT_PREFIX}-bondretest-$1"; }
bond_retest_enable() { # name value : write the oneshot unit + timer and enable them
  local n=$1 v u mgr=/usr/local/bin/wattun-manager
  v=$(bondretest_ok "$2") || return 1
  [ "$SANDBOX" = 1 ] && mgr=$MGR
  u=$(bondretest_unit "$n")
  {
    printf '[Unit]\nDescription=WatTunnel bond carrier re-test for %s%s\n[Service]\nType=oneshot\n' "$n" "$([ "$SANDBOX" = 1 ] && echo " (sandbox $WAT_PREFIX)")"
    unit_env_lines
    printf 'ExecStart=%s bond-retest %s --yes\n' "$mgr" "$n"
  } >"/etc/systemd/system/$u.service"
  {
    printf '[Unit]\nDescription=WatTunnel bond carrier re-test for %s (%s)\n[Timer]\n' "$n" "$v"
    bondretest_timer_lines "$v"
    printf '[Install]\nWantedBy=timers.target\n'
  } >"/etc/systemd/system/$u.timer"
  chmod 644 "/etc/systemd/system/$u.service" "/etc/systemd/system/$u.timer"
  systemctl daemon-reload && systemctl enable --now "$u.timer" >/dev/null 2>&1
}
bond_retest_disable() { # name : stop and remove the timer (toggling the setting off or deleting the tunnel)
  local u; u=$(bondretest_unit "$1")
  systemctl disable --now "$u.timer" >/dev/null 2>&1
  rm -f "/etc/systemd/system/$u.service" "/etc/systemd/system/$u.timer"
  systemctl daemon-reload >/dev/null 2>&1
  return 0
}
bond_retest_set() { # name value : store the setting and install/remove its timer
  local n=$1 v
  v=$(bondretest_ok "$2") || { err "Use off, 30m, 1h, 6h or daily-offpeak."; return 1; }
  bond_retest_visible "$(role "$n")" "$(cfg "$n" carrier)" \
    || { err "Bond auto-retest applies to a bonded tunnel on the entry server (carrier list with '+'), not '$n'."; return 1; }
  bondretest_set_file "$n" "$v" || { err "Could not write $CONF/$n.bondretest."; return 1; }
  if [ "$v" = off ]; then bond_retest_disable "$n"; ok "Bond auto-retest off for '$n'."
  elif bond_retest_enable "$n" "$v"; then ok "Bond auto-retest for '$n': $v."
  else err "Could not install the bond-retest timer."; return 1; fi
  return 0
}
bond_candidates_plan() { # bond-carriers plan-d token-peer [sni] -> "carrier peer" for every planned carrier the bond lacks
  # An auto tunnel's token lists what Kharej listens on, so a carrier that failed at auto-test time is known even
  # though the chosen bond never had a peer-<carrier> line for it. icmp has no listen port: it uses the bare peer.
  # H4 (2026-11-04): the engine refuses a shaped carrier inside a '+' bond (D7), and a bare raw plan entry has no
  # ':<port>' to probe. Both are skipped here rather than written into a bond the engine would reject.
  local cur=" ${1//+/ } " pd=$2 addr=$3 sni=${4:-} c p out='' h
  case "$cur" in *" icmp "*) ;; *) [[ "$addr" == *:* ]] || out="icmp $addr" ;; esac
  for x in ${pd//,/ }; do
    c=${x%%:*}; p=${x##*:}
    case "$cur" in *" $c "*) continue ;; esac
    is_shaped_carrier "$c" && continue
    case "$p" in ''|*[!0-9]*) continue ;; esac
    [ "$p" -ge 1 ] && [ "$p" -le 65535 ] || continue
    h=$addr
    if [ -n "$sni" ]; then
      case "$c" in ws|wss|grpc) h=$sni ;; esac
    fi
    out="${out:+$out
}$c $(join_hp "$h" "$p")"
  done
  printf '%s' "$out"
}
bond_peer_for() { # name carrier -> address for a throw-away probe (config peer-<carrier>, the auto plan, else peer)
  local n=$1 c=$2 p='' addr pd
  p=$(cfg "$n" "peer-$c"); [ -n "$p" ] && { printf '%s' "$p"; return 0; }
  addr=$(cfg "$n" peer)
  if [ -f "$CONF/$n.auto" ] && read_token "$(cat "$CONF/$n.auto")" && [ -n "$T_AUTO" ]; then
    pd=$(plan_part "$T_AUTO" d); p=$(plan_port "$pd" "$c")
    if [ -n "$p" ] && [ "$c" != icmp ]; then printf '%s' "$(join_hp "$T_PEER" "$p")"; return 0; fi
    addr=$T_PEER
  fi
  printf '%s' "$addr"
}
bondfail_get() { # name -> stored failures, comma separated (empty when none)
  local v=''
  [ -f "$CONF/$1.bondfail" ] && v=$(head -1 "$CONF/$1.bondfail" 2>/dev/null | tr -d '[:space:]')
  [ "$v" = none ] && v=''
  printf '%s' "${v%,}"
}
bondfail_set() { # name list : store the carriers to retry next run
  local n=$1 v=${2:-}
  ( umask 077; printf '%s\n' "${v:-none}" >"$CONF/$n.bondfail.tmp" ) && mv -f "$CONF/$n.bondfail.tmp" "$CONF/$n.bondfail"
}
bondfail_next() { # prev-failures carrier tested failing -> the list the next run retries
  # Only carriers outside the bond are remembered: a leg that is in the bond is probed on every run anyway, so
  # remembering it would just duplicate work. prev/testing/failing accept spaces or commas; carrier is a+b.
  local old=$1 car=${2//+/ } tested=$3 failing=$4 out='' x
  for x in ${tested//,/ }; do
    case " $car " in *" $x "*) continue ;; esac
    case " $failing " in *" $x "*) out="${out:+$out,}$x" ;; esac
  done
  for x in ${old//,/ }; do
    case " $car " in *" $x "*) continue ;; esac
    case " $tested " in *" $x "*) continue ;; esac
    case ",$out," in *",$x,"*) continue ;; esac
    out="${out:+$out,}$x"
  done
  printf '%s' "$out"
}
bond_worth() { # candidate-score best-leg-score -> 0 when adding this carrier is measurable value
  # A working carrier is always worth adding when no leg of the bond works right now; otherwise it must reach 10 %
  # of the best working leg's throughput, so a barely-alive path does not enlarge the bond.
  awk -v c="${1:-0}" -v b="${2:-0}" 'BEGIN{ if (c <= 0) exit 1; if (b <= 0) exit 0; exit !(c >= b*0.1) }'
}
bond_budget_fit() { # candidates budget-mb -> how many fit (1 MB each way per candidate)
  local max=$((${2:-$BONDRETEST_BUDGET_MB} / 2))
  [ "$max" -lt 1 ] && max=1
  [ "$1" -gt "$max" ] && echo "$max" || echo "$1"
}
bond_retest_job() { # name : probe the bond's carriers + the last failures, add one that works now
  local n=$1 cur cur_sp prev pd='' auto=0 pair pairs=() budget nfit c peer path sni icmp fp ech frag fs fm
  local best=0 score added='' failed='' tested=' ' total=0 i=0 npairs
  [ -f "$CONF/$n.yml" ] || { err "No tunnel named '$n'."; return 1; }
  [ "$(role "$n")" = Iran ] || { err "Bond auto-retest runs on the entry server (the side that dials the bond), not on the exit server."; return 1; }
  cur=$(cfg "$n" carrier)
  bond_retest_visible Iran "$cur" || { err "'$n' is not bonded (carrier '$cur' has no '+'); nothing to re-test."; return 1; }
  is_reverse "$n" && { env -u WAT_BASH_MGR "$BIN" bond-retest "$n" --yes; return $?; } # 4.5.1: reverse bonds live in the Go manager
  cur_sp=${cur//+/ }
  prev=$(bondfail_get "$n")
  sni=$(cfg "$n" sni)
  # Candidates: the bond's legs, every carrier the auto plan left out (known from Iran's NAME.auto token), then the
  # stored failures. A carrier that works again is only added, never swapped in: a bond leg is never removed here.
  if [ -f "$CONF/$n.auto" ] && read_token "$(cat "$CONF/$n.auto")" && [ -n "$T_AUTO" ]; then
    auto=1; pd=$(plan_part "$T_AUTO" d)
  fi
  local -a cur_pairs=() cand_pairs=()
  declare -A cand_peer=()
  for c in $cur_sp; do cur_pairs+=("$c $(bond_peer_for "$n" "$c")"); done
  if [ "$auto" = 1 ]; then
    while IFS= read -r pair; do [ -n "$pair" ] && cand_pairs+=("$pair"); done < <(bond_candidates_plan "$cur" "$pd" "$T_PEER" "$sni")
  fi
  for c in ${prev//,/ }; do
    case " $cur_sp " in *" $c "*) continue ;; esac
    case " ${cand_pairs[*]:-} " in *" $c "*) continue ;; esac
    cand_pairs+=("$c $(bond_peer_for "$n" "$c")")
  done
  pairs=("${cur_pairs[@]}" ${cand_pairs[@]+"${cand_pairs[@]}"})
  budget=$(conf_get bondretest-budget "$BONDRETEST_BUDGET_MB")
  [[ "$budget" =~ ^[0-9]+$ ]] && [ "$budget" -gt 0 ] || budget=$BONDRETEST_BUDGET_MB
  npairs=${#pairs[@]}
  nfit=$(bond_budget_fit "$npairs" "$budget")
  if [ "$nfit" -lt "$npairs" ] && [ "${#cur_pairs[@]}" -ge "$nfit" ] && [ "${#cand_pairs[@]}" -gt 0 ]; then
    if [ "$nfit" -ge 2 ]; then
      pairs=("${cur_pairs[0]}" "${cand_pairs[@]}" "${cur_pairs[@]:1}")
    else
      pairs=("${cand_pairs[@]}" "${cur_pairs[@]}")
    fi
  fi
  [ "$nfit" -lt "$npairs" ] && logger -t wattun-bondretest "$n: traffic budget ${budget} MB, probing $nfit of $npairs carriers"
  # Probes are throw-away clients (the at_* machinery) with this tunnel's key and settings: the live bond is untouched.
  path=$(cfg "$n" path); icmp=$(cfg "$n" icmp-type)
  fp=$(cfg "$n" fp); ech=$(cfg "$n" ech); frag=$(cfg "$n" tls-frag)
  fs=$(cfg "$n" fake-sni); fm=$(cfg "$n" fake-mode)
  AT_DIR=$AUTO_RUN/bondretest.$$
  AT_QUIET=1; AT_KEYS=0; AT_MB=1; AT_STOP=0; AT_ACT=''; AT_SKIP=''
  mkdir -p "$AUTO_RUN" && chmod 700 "$AUTO_RUN" && rm -rf "$AT_DIR" && mkdir -p "$AT_DIR" \
    || { err "Could not prepare $AUTO_RUN."; return 1; }
  cp -f "$CONF/$n.key" "$AT_DIR/key" 2>/dev/null || { ( umask 077; cat "$CONF/$n.key" >"$AT_DIR/key" ); }
  chmod 600 "$AT_DIR/key" 2>/dev/null
  T_PATH=${path:-/wat}; T_SNI=$sni; T_ICMP=$icmp
  for pair in "${pairs[@]}"; do
    i=$((i+1)); [ "$i" -le "$nfit" ] || break
    c=${pair%% *}; peer=${pair#* }
    cand_peer[$c]=$peer
    AV_LABEL=("$c"); AV_CAR=("$c"); AV_KIND=(d); AV_PEER=("$peer"); AV_PORT=('')
    AV_SNI=(''); AV_FP=(''); AV_ECH=(''); AV_FRAG=(''); AV_FS=(''); AV_FM=(''); AV_X=('')
    if is_pool "$c"; then AV_SNI=("$sni"); AV_FP=("$fp"); AV_ECH=("$ech"); AV_FRAG=("$frag"); AV_FS=("$fs"); AV_FM=("$fm"); fi
    at_probe 0 8
    tested+="$c "; total=$((total + 2 * AT_MB))
    case " $cur_sp " in *" $c "*) # a bond leg: never removed, only its speed sets the bar for a new path
      if [ "${AR_OK[0]}" = 1 ]; then
        score=$(at_score 0)
        best=$(awk -v a="$best" -v b="$score" 'BEGIN{print (b>a)?b:a}')
        logger -t wattun-bondretest "$n/$c (in the bond): $(printf '%.1f' "${AR_DOWN[0]:-0}") down / $(printf '%.1f' "${AR_UP[0]:-0}") up MB/s"
      else
        logger -t wattun-bondretest "$n/$c (in the bond): failed, ${AR_WHY[0]}; it stays in the bond"
      fi ;;
      *)
      if [ "${AR_OK[0]}" = 1 ]; then
        score=$(at_score 0)
        if bond_worth "$score" "$best"; then
          added+="$c "
          logger -t wattun-bondretest "$n/$c works now: $(printf '%.1f' "${AR_DOWN[0]:-0}") down / $(printf '%.1f' "${AR_UP[0]:-0}") up MB/s, adding it to the bond"
        else
          logger -t wattun-bondretest "$n/$c works but is too slow next to the bond; not adding it"
        fi
      else
        failed+="$c "; logger -t wattun-bondretest "$n/$c failed: ${AR_WHY[0]}"
      fi ;;
    esac
  done
  at_cleanup
  local new='' oknew=1
  if [ -n "$added" ]; then
    local a
    new="$cur"
    for a in $added; do new="$new+$a"; done
    v_carrier_list "$new" || oknew=0 # H4: never write/restart into a carrier list the engine refuses
    for a in $added; do carrier_ok_here "$a" || oknew=0; done
    if [ "$oknew" = 0 ]; then
      logger -t wattun-bondretest "$n: '$new' is not a carrier list this engine can run; keeping the bond unchanged"
      added=''
    fi
  fi
  if [ -n "$added" ]; then
    for a in $added; do
      [ -n "${cand_peer[$a]:-}" ] && set_value "$n" "peer-$a" "${cand_peer[$a]}"
    done
    set_value "$n" carrier "$new"
    logger -t wattun-bondretest "$n: adding ${added% } to the bond ($cur -> $new), restarting the tunnel"
    systemctl restart "${WAT_PREFIX}@$n" >/dev/null 2>&1
    ok "Added ${added% } to '$n' (bond now $new). The tunnel restarted."
  else
    ok "No carrier to add: the bond keeps its legs${prev:+ (still failing:$prev)}."
  fi
  local nf; nf=$(bondfail_next "$prev" "$cur" "$tested" "$failed")
  bondfail_set "$n" "$nf"
  [ -n "$nf" ] && logger -t wattun-bondretest "$n: retrying next run: $nf"
  logger -t wattun-bondretest "$n: probed$tested($total MB of test traffic)"
  return 0
}

# ======================================================================================
#  Backup & Restore, Bulk Operations
# ======================================================================================
backup_cmd() { # [dest.tar.gz]
  local dest=${1:-wattun-backup-$(date +%Y%m%d%H%M%S).tar.gz}
  dest=$(readlink -f "$dest" 2>/dev/null || echo "$dest")
  say "  Backing up $CONF to $dest..."
  tar -czf "$dest" -C "${CONF%/*}" "${CONF##*/}" || { err "Backup failed"; return 1; }
  chmod 600 "$dest"
  ok "Backup saved: $dest ($(du -h "$dest" | cut -f1))"
}
restore_cmd() { # <archive.tar.gz>
  local src=${1:-}
  [ -f "$src" ] || { err "Backup archive '$src' not found."; return 1; }
  say "  Restoring $CONF from $src..."
  mkdir -p "$CONF"
  tar -xzf "$src" -C "${CONF%/*}" || { err "Restore extraction failed"; return 1; }
  chmod 700 "$CONF"
  chmod 600 "$CONF"/*.key 2>/dev/null || true
  chmod 600 "$CONF"/*.yml 2>/dev/null || true
  ok "Restored configuration to $CONF."
  systemctl daemon-reload 2>/dev/null || true
  ok "Ready. You can start or restart your tunnels now."
}
start_all() {
  local n c=0
  for n in $(tunnels); do # hidden auto helpers start with their parent
    if ! systemctl is-active -q "${WAT_PREFIX}@$n" 2>/dev/null; then
      step "Starting ${WAT_PREFIX}@$n" auto_for_each_unit "$n" start; c=$((c+1))
    elif is_auto_kharej "$n"; then
      auto_for_each_unit "$n" start >/dev/null 2>&1 || true
    fi
  done
  [ "$c" -gt 0 ] && ok "Started $c tunnel(s)." || warn "All tunnels are already active."
}
stop_all() {
  local n c=0
  for n in $(tunnels); do # hidden auto helpers stop with their parent
    if systemctl is-active -q "${WAT_PREFIX}@$n" 2>/dev/null; then
      step "Stopping ${WAT_PREFIX}@$n" auto_for_each_unit "$n" stop; c=$((c+1))
    elif is_auto_kharej "$n"; then
      auto_for_each_unit "$n" stop >/dev/null 2>&1 || true
    fi
  done
  [ "$c" -gt 0 ] && ok "Stopped $c tunnel(s)." || warn "All tunnels are already stopped."
}
batch_actions_menu() {
  while :; do
    page "All tunnels"
    menu_line 1 'start all' 2 'stop all' 3 'restart all' 4 'status list'
    menu_line 5 'back up configs' 6 'restore configs' 0 back
    key_read
    case "$KEY" in
      1) start_all; pause ;;
      2) confirm "Stop all active tunnels?" n && stop_all; pause ;;
      3) confirm "Restart all tunnels? Open connections drop." n && restart_all; pause ;;
      4) status_all; pause ;;
      5) echo; ask "Backup file" "wattun-backup-$(date +%Y%m%d).tar.gz"; backup_cmd "$REPLY_V"; pause ;;
      6) echo; ask "Backup .tar.gz path" ""; restore_cmd "$REPLY_V"; pause ;;
      b|0|q|enter|esc) return 0 ;;
    esac
  done
}

# ======================================================================================
#  Bonding Manager Submenu
# ======================================================================================
bonding_menu() { # name
  local n=$1 r cr isauto=0
  r=$(role "$n")
  [ "$r" = Iran ] && [ -f "$CONF/$n.auto" ] && read_token "$(cat "$CONF/$n.auto")" && [ -n "$T_AUTO" ] && isauto=1
  while :; do
    cr=$(cfg "$n" carrier)
    page "Bonding" "$n · $cr"
    tinfo "$n"
    local bmode=$(cfg "$n" bond-mode)
    set_row m mode "${bmode:-balanced}"
    local brv='' brvis=0
    if bond_retest_visible "$r" "$cr"; then brvis=1; brv=$(bondretest_get "$n"); set_row r 'auto-retest' "$brv" '' off; fi
    echo
    if [ "$TI_CAR_COUNT" -gt 0 ]; then
      printf '  %s%4s  %-10s %-8s %8s %8s %12s%s\n' "$GRY" '#' path state rtt loss share "$RST"
      local ci ccol cdot ctxt c_pct
      for ((ci=0; ci<TI_CAR_COUNT; ci++)); do
        if [ "${CAR_MUTED[$ci]}" = true ]; then
          ccol=$GRY; cdot='○'; ctxt="muted"
        elif [ "${CAR_ALIVE[$ci]}" = true ]; then
          ccol=$GRN; cdot='●'; ctxt="up"
        else
          ccol=$RED; cdot='○'; ctxt="down"
        fi
        c_pct=$(awk -v s="${CAR_SHARE[$ci]:-0}" 'BEGIN{printf "%.0f", s*100}')
        printf '  %s%4s%s  %-10s %s%s %-6s%s %6.0f ms %7.1f%% %11s%%\n' "$CYN" "$ci" "$RST" \
          "${CAR_NAME[$ci]}" "$ccol" "$cdot" "$ctxt" "$RST" "${CAR_RTT[$ci]}" "$(awk -v l="${CAR_LOSS[$ci]:-0}" 'BEGIN{printf "%.1f", l*100}')" "$c_pct"
      done
    else
      hint "No path data: the tunnel is stopped or has one carrier."
    fi
    echo
    menu_line t 'mute or unmute a path' a 'add carrier' d 'remove carrier'
    [ "$brvis" = 1 ] && menu_line r 're-test blocked paths (off/30m/1h/6h/daily-offpeak)'
    menu_line 0 back
    key_read
    case "$KEY" in
      r|R)
        [ "$brvis" = 1 ] || continue
        echo
        say "  ${BOLD}Bond auto-retest${RST} ${GRY}(re-tests every leg plus the last failures; never removes a working leg)${RST}"
        hint "A carrier that works again is added back only when it reaches 10 % of the best working leg."
        ask_ok "Re-test: off, 30m, 1h, 6h or daily-offpeak" "$brv" v_bondretest || continue
        bond_retest_set "$n" "$REPLY_V"
        pause ;;
      t)
        echo
        ask_ok "Path index to mute or unmute" "0" v_num || continue
        local pidx=$REPLY_V act
        ask_ok "mute or unmute?" "mute" v_nonempty || continue
        act=$REPLY_V
        # routed through carrier_toggle_cmd (2026-11-20 review F3): it carries the auto dead-leg index
        # realignment, the range check and the engine-answer interpretation this raw POST lacked
        case "$act" in
          mute|unmute) carrier_toggle_cmd "$act" "$n" "$pidx" ;;
          *) err "Choose mute or unmute." ;;
        esac
        pause ;;
      m)
        echo
        say "  Choose bond mode:"
        say "    ${CYN}1${RST} balanced       (smooth weighted round-robin based on path capacities)"
        say "    ${CYN}2${RST} active-backup  (100% on primary path, 50ms keepalives on secondary, fast cutover)"
        say "    ${CYN}3${RST} replicate      (replicate datagrams across all paths for zero loss)"
        say "    ${CYN}4${RST} adaptive       (one path; moves to a clearly better one after 5 min, at most every 30 min; fails over at once)"
        ask_ok "Choice" "1" v_nonempty || continue
        case "$REPLY_V" in
          1|balanced) set_value "$n" bond-mode balanced ;;
          2|active-backup) set_value "$n" bond-mode active-backup ;;
          3|replicate) set_value "$n" bond-mode replicate ;;
          4|adaptive) set_value "$n" bond-mode adaptive ;;
          *) warn "Unknown bond mode '$REPLY_V'."; continue ;;
        esac
        ok "Set bond-mode: $(cfg "$n" bond-mode)"
        confirm "Restart '$n' to apply mode change?" y && step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
        pause ;;
      a)
        echo
        # Only auto Iran tunnels can gain a path safely: Kharej already listens on every type in
        # the plan, and the per-carrier port comes from it. A fixed/hand-made bond needs peer-<carrier>
        # and listen-<carrier> in Advanced YAML, so this menu must not guess them.
        if [ "$isauto" != 1 ]; then
          warn "Adding a carrier here is for auto tunnels on the entry server: the plan already made the exit server listen on every type."
          hint "A hand-made bond needs peer-<carrier> and listen-<carrier> in Advanced YAML (tunnel page, o)."
          hint "To get a bond the easy way: make an auto tunnel on the exit server, then join the tested types on the entry server (tunnel page, m)."
          pause; continue
        fi
        local pd=$(plan_part "$T_AUTO" d)
        ask_ok "Carrier name to add (in the plan: ${pd:-none})" "tls" v_nonempty || continue
        local ncar=$REPLY_V cur_car=$(cfg "$n" carrier) p
        if ! carrier_ok "$ncar"; then err "Unknown carrier '$ncar' (use icmp, udp, tcp, tls, ws, wss, h2, h2c, grpc, gre, ipip or an F19 shape)."; pause; continue; fi
        if is_shaped_carrier "$ncar"; then err "F19 shaped carriers are single-carrier only in 3.3.0 (the engine refuses a shaped leg in a '+'-bond)."; pause; continue; fi # D7
        if [[ "+$cur_car+" == *"+$ncar+"* ]]; then
          warn "Carrier '$ncar' is already in carrier list '$cur_car'."
        elif [ "$ncar" = icmp ]; then
          if [[ "$T_PEER" == *:* ]] && ! ipv4_ok "$T_PEER"; then
            err "icmp requires an IPv4/hostname peer."
          else
            set_value "$n" peer-icmp "$T_PEER"
            set_value "$n" carrier "$cur_car+icmp"
            ok "Updated carrier: $(cfg "$n" carrier)"
            confirm "Restart '$n' to apply new carrier bond?" y && step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
          fi
        else
          p=$(plan_port "$pd" "$ncar")
          if [ -z "$p" ]; then
            err "Carrier '$ncar' is not in this tunnel's auto plan, so the exit server does not listen for it."
          else
            set_value "$n" "peer-$ncar" "$(join_hp "$T_PEER" "$p")"
            set_value "$n" carrier "$cur_car+$ncar"
            ok "Updated carrier: $(cfg "$n" carrier)"
            if ! is_pool "$ncar" && [ -n "$(cfg "$n" fake-sni)$(cfg "$n" pool-rotate)$(cfg "$n" pool-rotate-bytes)" ]; then
              warn "The $ncar leg carries no fake-SNI or rotation: only tcp/tls/ws/wss/h2/h2c/grpc legs are disguised."
            fi
            confirm "Restart '$n' to apply new carrier bond?" y && step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
          fi
        fi
        pause ;;
      d)
        echo
        if [ "$isauto" != 1 ]; then
          warn "Removing a carrier here is for auto tunnels on the entry server; for a hand-made bond edit the YAML (tunnel page, o)."
          pause; continue
        fi
        ask_ok "Carrier name to remove" "" v_nonempty || continue
        local rcar=$REPLY_V cur_car=$(cfg "$n" carrier)
        if ! carrier_ok "$rcar"; then err "Unknown carrier '$rcar'."; pause; continue; fi
        if [[ "+$cur_car+" != *"+$rcar+"* ]]; then
          warn "Carrier '$rcar' not found in '$cur_car'."
        else
          local new_car
          new_car=$(echo "$cur_car" | sed -E "s/(^|\+)$rcar(\+|$)/\1/g; s/^\+//; s/\+$//")
          if [ -z "$new_car" ]; then
            err "Cannot remove the only carrier."
          else
            set_value "$n" carrier "$new_car"
            sed -i -E "/^peer-$rcar:/d" "$CONF/$n.yml"
            ok "Updated carrier: $(cfg "$n" carrier)"
            confirm "Restart '$n' to apply?" y && step "Restarting ${WAT_PREFIX}@$n" systemctl restart "${WAT_PREFIX}@$n"
          fi
        fi
        pause ;;
      b|0|q|enter|esc) break ;;
    esac
  done
}

# ======================================================================================
#  Auto Mode Settings Submenu
# ======================================================================================
auto_menu() { # name
  local n=$1 cur pol sla_f isauto=0
  sla_f="$CONF/$n.sla"
  [ -f "$CONF/$n.auto" ] && read_token "$(cat "$CONF/$n.auto")" && [ -n "$T_AUTO" ] && isauto=1
  while :; do
    page "Auto mode" "$n"
    cur=$(auto_current_key "$n" 2>/dev/null || cfg "$n" carrier)
    pol=$(cat "$CONF/$n.policy" 2>/dev/null || echo speed)
    [ "$isauto" != 1 ] && { hint "Fixed-type token: policy and retest need a new token (tunnel page, t)."; echo; }
    printf '      %-13s %s\n' 'in use' "${cur:--}"
    set_row p policy "$pol"
    local sla_v=''
    if [ -f "$sla_f" ]; then
      local min_r=$(grep '^sla_min_rate_kbps=' "$sla_f" 2>/dev/null | cut -d= -f2)
      local max_rtt=$(grep '^sla_max_rtt_ms=' "$sla_f" 2>/dev/null | cut -d= -f2)
      local max_l=$(grep '^sla_max_loss_pct=' "$sla_f" 2>/dev/null | cut -d= -f2)
      sla_v="rate ≥ ${min_r:-0} kbps · rtt ≤ ${max_rtt:-0} ms · loss ≤ ${max_l:-0} %"
    fi
    set_row s 'heal when' "$sla_v" '' 'the link is down'
    local opt_timer_st=''
    systemctl is-active -q "$WAT_PREFIX-auto-optimize.timer" 2>/dev/null && opt_timer_st="${GRN}on${RST} ${GRY}(retests once a day off-peak)${RST}"
    set_row o 'daily retest' "$opt_timer_st" '' off
    echo
    menu_line r 'retest now' 0 back
    key_read
    case "$KEY" in
      p)
        echo
        if [ "$isauto" != 1 ]; then
          warn "The selection policy is read only by auto tunnels; this one was made with a fixed type."
          hint "For an auto tunnel: make one on the exit server, paste its token here (t), run auto-test."
          pause; continue
        fi
        say "  Choose carrier selection policy:"
        say "    ${CYN}1${RST} speed    (rank by Down+Up throughput, lowest RTT tiebreak)"
        say "    ${CYN}2${RST} latency  (rank by lowest round-trip latency)"
        say "    ${CYN}3${RST} direct   (prioritize direct unproxied paths over CDN)"
        say "    ${CYN}4${RST} bond     (automatically bond top direct performers)"
        ask_ok "Choice" "1" v_nonempty || continue
        case "$REPLY_V" in
          1|speed) echo speed >"$CONF/$n.policy" ;;
          2|latency) echo latency >"$CONF/$n.policy" ;;
          3|direct) echo direct >"$CONF/$n.policy" ;;
          4|bond) echo bond >"$CONF/$n.policy" ;;
          *) warn "Unknown policy '$REPLY_V'."; continue ;;
        esac
        ok "Policy saved: $(cat "$CONF/$n.policy")"
        pause ;;
      s)
        echo
        local cur_min=0 cur_rtt=0 cur_loss=0
        if [ -f "$sla_f" ]; then
          cur_min=$(grep '^sla_min_rate_kbps=' "$sla_f" | cut -d= -f2)
          cur_rtt=$(grep '^sla_max_rtt_ms=' "$sla_f" | cut -d= -f2)
          cur_loss=$(grep '^sla_max_loss_pct=' "$sla_f" | cut -d= -f2)
        fi
        ask_ok "Minimum required throughput in kbps (0 = none)" "${cur_min:-0}" v_num || continue
        cur_min=$REPLY_V
        ask_ok "Maximum tolerable RTT in ms (0 = none, e.g. 300)" "${cur_rtt:-0}" v_num || continue
        cur_rtt=$REPLY_V
        ask_ok "Maximum tolerable packet loss % (0 = none, e.g. 10)" "${cur_loss:-0}" v_num || continue
        cur_loss=$REPLY_V
        {
          echo "sla_min_rate_kbps=$cur_min"
          echo "sla_max_rtt_ms=$cur_rtt"
          echo "sla_max_loss_pct=$cur_loss"
        } >"$sla_f"
        chmod 600 "$sla_f"
        ok "SLA configured."
        pause ;;
      r)
        echo
        if [ "$isauto" = 1 ]; then
          say "  Running auto-test & policy re-evaluation..."
        elif cdn_tunnel_p "$n"; then
          say "  Refreshing the CDN edge list..."
        else
          hint "Nothing to re-rank: this tunnel was made with a fixed type. To switch types, make a new tunnel or use an auto token."
          pause; continue
        fi
        AUTO_OPTIMIZE=1 auto_retest "$n"
        pause ;;
      o)
        echo
        if systemctl is-active -q "$WAT_PREFIX-auto-optimize.timer" 2>/dev/null; then
          optimize_disable
        else
          optimize_enable
        fi
        sleep 1 ;;
      b|0|q|enter|esc) break ;;
    esac
  done
}

# ======================================================================================
#  Bandwidth Quotas & Limits Submenu
# ======================================================================================
limits_menu() { # name
  local n=$1 r cr
  r=$(role "$n"); cr=$(cfg "$n" carrier)
  while :; do
    page "Limits" "$n"
    set_row m 'speed limit' "$(cfg "$n" max-mbps)" 'MB/s' 'none'
    echo
    say "  ${GRY}per port${RST}"
    local -a p_limits=()
    mapfile -t p_limits < <(grep -E '^[[:space:]]*-[[:space:]]+[0-9]+' "$CONF/$n.yml" | grep -E 'rate=|quota=' || true)
    if [ "${#p_limits[@]}" -gt 0 ]; then
      local it
      for it in "${p_limits[@]}"; do
        say "    $it"
      done
    else
      say "    ${GRY}none${RST}"
    fi
    echo
    local m=$(cfg "$n" metrics)
    if [ -n "$m" ]; then
      local prt_json
      prt_json=$(curl -fs --noproxy '*' --max-time 2 "http://$m/ports" 2>/dev/null)
      if [ -n "$prt_json" ]; then
        say "  ${GRY}quota used${RST}"
        local pobj
        while read -r pobj; do
          [ -n "$pobj" ] || continue
          local lp qu ql qe qp qr
          lp=$(jget "$pobj" port)
          qp=$(jget "$pobj" quota_period); qr=$(jget "$pobj" quota_resets_at)
          qu=$(jget "$pobj" quota_used)
          ql=$(jget "$pobj" quota_limit)
          qe=$(jget "$pobj" quota_exceeded)
          if [ "${ql:-0}" -gt 0 ]; then
            say "    $lp  $(human "$qu") of $(human "$ql")$([ "$qe" = true ] && printf '  %s✘ used up%s' "$RED" "$RST")$([ -n "$qp" ] && [ "${qr:-0}" -gt 0 ] 2>/dev/null && printf '  %sper %s, resets %s%s' "$GRY" "$qp" "$(date -d "@$qr" '+%Y-%m-%d %H:%M' 2>/dev/null)" "$RST")"
          fi
        done < <(grep -o '{[^{}]*}' <<<"$prt_json")
      fi
    fi
    echo
    menu_line e 'set a port limit' r 'reset a port quota' 0 back
    key_read
    case "$KEY" in
      m)
        echo
        ask_ok "Global speed ceiling in MB/s (- or 0 or default = unset)" "$(cfg "$n" max-mbps)" v_mbps_adv || continue
        case "$REPLY_V" in -|0|default) REPLY_V='' ;; esac
        if [ -z "$REPLY_V" ]; then unset_value "$n" max-mbps; else set_value "$n" max-mbps "$REPLY_V"; fi
        [ "$r" = Kharej ] && is_auto_kharej "$n" && auto_sync_helper_settings "$n"
        ok "Saved. Restart '$n' to apply."
        pause ;;
      e)
        echo
        ask_ok "Port to limit" "" v_port || continue
        local lport=$REPLY_V
        ask_ok "Rate limit (e.g. 5MB, 300k, 0 = none)" "0" v_pool_bytes || continue
        local lrate=$REPLY_V
        ask_ok "Quota limit (e.g. 100GB, 500MB, 0 = none)" "0" v_pool_bytes || continue
        local lquota=$REPLY_V lper=''
        if [ -n "$lquota" ] && [ "$lquota" != 0 ] && [ "$(bin_ver_ok 3.3.6)" = 1 ]; then # an older wattun refuses period=
          ask_ok "Reset the quota every day, week or month (- = never)" "-" v_quota_period || continue
          case "${REPLY_V,,}" in day|week|month) lper=${REPLY_V,,} ;; esac
        fi
        set_port_limit "$n" "$lport" "$lrate" "$lquota" "$lper"
        [ "$r" = Kharej ] && is_auto_kharej "$n" && auto_sync_helper_settings "$n"
        ok "Saved limit for port $lport. Hot-reloaded automatically by engine."
        pause ;;
      r)
        echo
        ask_ok "Port to reset quota for" "" v_port || continue
        local rport=$REPLY_V
        if [ -n "$m" ]; then
          local rres
          rres=$(curl -fs --noproxy '*' --max-time 3 -X POST "http://$m/quota/reset?port=$rport" 2>/dev/null)
          if [ -n "$rres" ]; then
            ok "Quota for port $rport reset."
          else
            err "Failed to reset quota on metrics server http://$m."
          fi
        else
          warn "Tunnel '$n' has no metrics endpoint configured."
        fi
        pause ;;
      b|0|q|enter|esc) break ;;
    esac
  done
}

# ======================================================================================
#  Tunnel page: status header + two-column command deck
# ======================================================================================
# The deck has two columns of rows. A row is a section header or an action. Arrows and Tab move a
# visible cursor (">"); Enter runs the selected action, and every action keeps its hotkey so the
# page stays fast for people who know it. Each action carries a one-line description, so the page
# explains itself instead of asking the operator to memorize 16 cryptic labels.
TM_SELKEY=''; TM_FSIDE=L; TM_FIDX=0; TM_CW=36
TL_TYPE=(); TL_KEY=(); TL_LAB=(); TL_DESC=(); TL_HELP=()
TR_TYPE=(); TR_KEY=(); TR_LAB=(); TR_DESC=(); TR_HELP=()

tmenu_lhdr() { TL_TYPE+=(H); TL_KEY+=(''); TL_LAB+=("$1"); TL_DESC+=(''); TL_HELP+=(''); }
tmenu_rhdr() { TR_TYPE+=(H); TR_KEY+=(''); TR_LAB+=("$1"); TR_DESC+=(''); TR_HELP+=(''); }
tmenu_ladd() { TL_TYPE+=(I); TL_KEY+=("$1"); TL_LAB+=("$2"); TL_DESC+=("$3"); TL_HELP+=("$4"); }
tmenu_radd() { TR_TYPE+=(I); TR_KEY+=("$1"); TR_LAB+=("$2"); TR_DESC+=("$3"); TR_HELP+=("$4"); }

tunnel_menu_build() { # name role run boot carrier z_ok reverse auto_kharej has_companion
  local n=$1 r=$2 run=$3 boot=$4 car=$5 z_ok=${6:-0} rev=${7:-0} auto=${8:-0} comp=${9:-0}
  local stop_lab stop_desc boot_desc pcnt bmode ac_st=''
  TL_TYPE=(); TL_KEY=(); TL_LAB=(); TL_DESC=(); TL_HELP=()
  TR_TYPE=(); TR_KEY=(); TR_LAB=(); TR_DESC=(); TR_HELP=()
  if [ "$run" = active ]; then stop_lab=Stop; stop_desc='active'
  else stop_lab=Start; stop_desc='stopped'; fi
  if [ "$boot" = on ]; then boot_desc='on · toggle'; else boot_desc='off · toggle'; fi
  pcnt=$(yml_maps "$n" 2>/dev/null | wc -l)
  [ "$pcnt" -gt 0 ] && pcnt="$pcnt rule$([ "$pcnt" = 1 ] || echo s)" || pcnt=$([ "$r" = Kharej ] && echo any || echo none)
  bmode=$(cfg "$n" bond-mode 2>/dev/null || true)
  if [ "$z_ok" = 1 ]; then
    ac_st=$(detect_preset "$n" 2>/dev/null || echo off)
    [ "$ac_st" = off ] && [ -z "$(cfg "$n" fake-sni)$(cfg "$n" pool-rotate)$(cfg "$n" ech)$(cfg "$n" governor)" ] && ac_st=off
  fi

  tmenu_lhdr Observe
  tmenu_ladd l Logs '' "Follow ${WAT_PREFIX}@$n in journalctl (Ctrl+C returns)"
  tmenu_ladd d Diagnose '' 'Check key, carrier, route, MTU and run speed test'
  tmenu_ladd v 'Speed test' '' 'Transfer 10 MB down/up through the live tunnel'
  tmenu_ladd m Monitor '' 'Live throughput & RTT view (any key returns)'
  tmenu_lhdr Route
  tmenu_ladd p Ports "$pcnt" 'Edit port mappings (reloads in 3 s, no drop)'
  tmenu_ladd c Carrier "${car:0:12}" 'Change transport carrier (icmp, tcp, tls, wss...)'
  tmenu_ladd q Limits '' 'Per-port bandwidth limits and traffic quotas'
  tmenu_ladd b Bonding "$bmode" 'Bond multiple carriers or set bonding policy'
  [ "$z_ok" = 1 ] && tmenu_ladd z Anti-censor "$ac_st" 'fake-SNI, ECH, rotation, presets and matrix'

  tmenu_rhdr Service
  tmenu_radd r Restart '' 'Restart service (drops active connections)'
  tmenu_radd s "$stop_lab" "$stop_desc" 'Start or stop this service now'
  tmenu_radd e Boot "$boot_desc" 'Toggle automatic start at boot'
  tmenu_radd o Advanced '' 'MTU, FEC, batching, sessions, bind, direction'
  tmenu_rhdr Identity
  if [ "$r" = Kharej ]; then
    tmenu_radd t Token '' "Show token for the entry server setup"
    tmenu_radd k 'New key' '' 'Rotate PSK and regenerate token'
    [ "$rev" = 1 ] && [ "$comp" = 0 ] && tmenu_radd h 'Entry IP' '' 'Change the entry peer address (reverse tunnel)'
  else
    tmenu_radd t 'New token' '' 'Replace the exit server, key and carrier (ports stay)'
    if [ "$rev" = 1 ]; then
      [ "$car" != icmp ] && tmenu_radd h 'Listen port' '' 'Change reverse carrier listen port'
    else
      tmenu_radd h 'Exit IP' '' 'Change the exit peer address'
    fi
    tmenu_radd a 'Auto mode' '' 'Probe carriers and pick fastest route'
  fi
  # keep the cursor on the same action across redraws; if it vanished, start from the first action
  tmenu_find "$TM_SELKEY" || tunnel_menu_first
}

tmenu_find() { # key -> TM_FSIDE=L|R, TM_FIDX=row ; rc 1 when the key is not an action on this page
  local k=$1 i
  for i in "${!TL_KEY[@]}"; do
    [ "${TL_TYPE[$i]}" = I ] && [ "${TL_KEY[$i]}" = "$k" ] && { TM_FSIDE=L; TM_FIDX=$i; return 0; }
  done
  for i in "${!TR_KEY[@]}"; do
    [ "${TR_TYPE[$i]}" = I ] && [ "${TR_KEY[$i]}" = "$k" ] && { TM_FSIDE=R; TM_FIDX=$i; return 0; }
  done
  return 1
}
tunnel_menu_first() {
  local i
  for i in "${!TL_KEY[@]}"; do [ "${TL_TYPE[$i]}" = I ] && { TM_SELKEY=${TL_KEY[$i]}; return 0; }; done
  for i in "${!TR_KEY[@]}"; do [ "${TR_TYPE[$i]}" = I ] && { TM_SELKEY=${TR_KEY[$i]}; return 0; }; done
}
tunnel_menu_select() { # key : follow a typed hotkey with the cursor (no-op for unknown keys)
  local k=${1,,}
  [ -n "$k" ] || return 0
  tmenu_find "$k" && TM_SELKEY=$k
  return 0
}
tmenu_closest_to() { # side row -> TM_CKEY: the action in that column nearest to row
  local side=$1 row=$2 i d bestd=999
  TM_CKEY=''
  if [ "$side" = L ]; then
    for i in "${!TL_KEY[@]}"; do
      [ "${TL_TYPE[$i]}" = I ] || continue
      d=$(( i > row ? i - row : row - i ))
      [ "$d" -lt "$bestd" ] && { bestd=$d; TM_CKEY=${TL_KEY[$i]}; }
    done
  else
    for i in "${!TR_KEY[@]}"; do
      [ "${TR_TYPE[$i]}" = I ] || continue
      d=$(( i > row ? i - row : row - i ))
      [ "$d" -lt "$bestd" ] && { bestd=$d; TM_CKEY=${TR_KEY[$i]}; }
    done
  fi
  [ -n "$TM_CKEY" ]
}
tunnel_menu_move() { # up|down|left|right : move the cursor, skipping section headers
  local dir=$1 side idx i n want
  if ! tmenu_find "$TM_SELKEY"; then tunnel_menu_first; return 0; fi
  side=$TM_FSIDE; idx=$TM_FIDX
  case "$dir" in
    up) n=-1 ;;
    down) n=1 ;;
    *)
      want=R; [ "$side" = R ] && want=L
      tmenu_closest_to "$want" "$idx" && TM_SELKEY=$TM_CKEY
      return 0 ;;
  esac
  i=$(( idx + n ))
  if [ "$side" = L ]; then
    while [ "$i" -ge 0 ] && [ "$i" -lt "${#TL_TYPE[@]}" ]; do
      [ "${TL_TYPE[$i]}" = I ] && { TM_SELKEY=${TL_KEY[$i]}; return 0; }
      i=$(( i + n ))
    done
  else
    while [ "$i" -ge 0 ] && [ "$i" -lt "${#TR_TYPE[@]}" ]; do
      [ "${TR_TYPE[$i]}" = I ] && { TM_SELKEY=${TR_KEY[$i]}; return 0; }
      i=$(( i + n ))
    done
  fi
  return 0
}
tmenu_cell() { # side row -> CELL : one deck cell with colours (empty past the column's last row)
  local side=$1 i=$2 t key lab desc
  local -a ty=("${TL_TYPE[@]}") ky=("${TL_KEY[@]}") la=("${TL_LAB[@]}") de=("${TL_DESC[@]}")
  if [ "$side" = R ]; then
    ty=("${TR_TYPE[@]}"); ky=("${TR_KEY[@]}"); la=("${TR_LAB[@]}"); de=("${TR_DESC[@]}")
  fi
  t=${ty[$i]:-}
  case "$t" in
    H) CELL="${BOLD}${la[$i]}${RST}" ;;
    I) key=${ky[$i]}; lab=${la[$i]}; desc=${de[$i]}
       if [ "$key" = "$TM_SELKEY" ]; then
         CELL="$(printf '%s▸%s %s %s%-14s%s %s%s%s' "$CYN" "$RST" "$(key_label "$key")" "$BOLD" "$lab" "$RST" "$GRY" "$desc" "$RST")"
       else
         CELL="$(printf '  %s %-14s %s%s%s' "$(key_label "$key")" "$lab" "$GRY" "$desc" "$RST")"
       fi ;;
    *) CELL='' ;;
  esac
}
tunnel_menu_render() {
  local rows i l r pad cols
  cols=$(term_cols)
  if [ "$cols" -lt 74 ]; then
    for ((i=0; i<${#TL_TYPE[@]}; i++)); do tmenu_cell L "$i"; printf '  %s\n' "$CELL"; done
    echo
    for ((i=0; i<${#TR_TYPE[@]}; i++)); do tmenu_cell R "$i"; printf '  %s\n' "$CELL"; done
    return 0
  fi
  rows=${#TL_TYPE[@]}
  [ "${#TR_TYPE[@]}" -gt "$rows" ] && rows=${#TR_TYPE[@]}
  for ((i=0; i<rows; i++)); do
    tmenu_cell L "$i"; l=$CELL
    tmenu_cell R "$i"; r=$CELL
    if [ -z "$r" ]; then printf '  %s\n' "$l"; continue; fi
    vlen "$l"; pad=$(( TM_CW - VLEN )); [ "$pad" -lt 0 ] && pad=0
    printf '  %s%*s  %s\n' "$l" "$pad" '' "$r"
  done
}
tunnel_menu_help_line() {
  local lab help
  tmenu_find "$TM_SELKEY" || return 0
  if [ "$TM_FSIDE" = L ]; then lab=${TL_LAB[$TM_FIDX]}; help=${TL_HELP[$TM_FIDX]}
  else lab=${TR_LAB[$TM_FIDX]}; help=${TR_HELP[$TM_FIDX]}; fi
  printf '\n  %s▸%s %s%s%s  %s%s%s\n' "$CYN" "$RST" "$BOLD" "$lab" "$RST" "$GRY" "$help" "$RST"
}
tunnel_menu_footer() {
  local nav pad w=${UI_W:-74}
  nav="${GRY}↑↓${RST} move  ${GRY}tab${RST} col  ${GRY}enter${RST} open  ${GRY}0${RST} back  ${GRY}?${RST} keys"
  vlen "$nav"; pad=$(( w - VLEN - 10 )); [ "$pad" -lt 2 ] && pad=2
  printf '  %s%*s%s[x] delete%s\n' "$nav" "$pad" '' "$RED" "$RST"
}
tunnel_menu_keys() { # name : the full key map, for "?" (any key returns to the deck)
  local n=$1 i
  local -a ty ky la he
  page "Keys" "$n"
  ty=("${TL_TYPE[@]}"); ky=("${TL_KEY[@]}"); la=("${TL_LAB[@]}"); he=("${TL_HELP[@]}")
  for i in "${!ty[@]}"; do
    case "${ty[$i]}" in
      H) printf '  %s%s%s\n' "$BOLD" "${la[$i]}" "$RST" ;;
      I) printf '  %s %-14s %s%s%s\n' "$(key_label "${ky[$i]}")" "${la[$i]}" "$GRY" "${he[$i]}" "$RST" ;;
    esac
  done
  ty=("${TR_TYPE[@]}"); ky=("${TR_KEY[@]}"); la=("${TR_LAB[@]}"); he=("${TR_HELP[@]}")
  for i in "${!ty[@]}"; do
    case "${ty[$i]}" in
      H) printf '  %s%s%s\n' "$BOLD" "${la[$i]}" "$RST" ;;
      I) printf '  %s %-14s %s%s%s\n' "$(key_label "${ky[$i]}")" "${la[$i]}" "$GRY" "${he[$i]}" "$RST" ;;
    esac
  done
  printf '  %s %-14s %s%s%s\n' "$(key_label x)" Delete 'Remove tunnel and all files (confirms first)' "$GRY" "$RST"
  printf '  %s %-14s %s%s%s\n' "$(key_label s)" 'Spoofing & shaping' 'How each anti-censor option behaves' "$GRY" "$RST"
  echo
  hint "Press any key to go back"
  while :; do
    key_read
    [ "$KEY" = s ] && { spoofhelp_page "$n"; continue; }
    return 0
  done
}
tunnel_header() { # name role
  local n=$1 r=$2 left right pad
  if [ "$NONINTERACTIVE" = 1 ]; then printf '== %s (%s) ==\n' "$n" "$r"; return 0; fi
  ui_init_width; clear_screen; echo
  tinfo "$n"; state_cell "$r" "$TI_STATE"
  left="${GRY}WatTunnel${VER:+ v$VER} ·${RST} ${BOLD}${n}${RST}  ${GRY}${r}${RST}"
  right="${SC_COL}${SC_DOT} ${SC_TXT}${RST} ${GRY}· $(carrier_label "$n")${RST}"
  if [ "$TI_STATE" = up ] || [ "$TI_STATE" = degraded ]; then
    if awk -v r="${TI_RATE:-0}" 'BEGIN{exit !(r > 0)}'; then
      right+=" ${GRY}·${RST} ↓$(human "$TI_RATE")/s"
    else
      right+=" ${GRY}· idle${RST}"
    fi
  fi
  vlen "$left"; pad=$(( UI_W - VLEN )); vlen "$right"; pad=$(( pad - VLEN ))
  [ "$pad" -lt 2 ] && pad=2
  printf '  %s%*s%s\n' "$left" "$pad" '' "$right"
  hr
  echo
}

tunnel_page() {
  local n=$1 r run boot car z_ok rev auto comp par first=1
  TM_SELKEY=''
  while :; do
    [ -f "$CONF/$n.yml" ] || return 0
    r=$(role "$n")
    run=$(systemctl is-active "${WAT_PREFIX}@$n" 2>/dev/null)
    boot=off; systemctl is-enabled -q "${WAT_PREFIX}@$n" 2>/dev/null && boot=on
    car=$(cfg "$n" carrier)
    z_ok=0; [ "$(uname -s)" = Linux ] && { is_pool_list "$car" || [ "$car" = icmp ]; } && z_ok=1
    rev=0; is_reverse "$n" && rev=1
    auto=0; is_auto_kharej "$n" && auto=1
    comp=0; [ -n "$(companion_of "$n")" ] && comp=1
    tunnel_header "$n" "$r"
    # first render: put the cursor on the action that is useful right now
    if [ "$first" = 1 ]; then
      first=0
      case "$TI_STATE" in
        stopped) TM_SELKEY=s ;;
        down|degraded) TM_SELKEY=d ;;
        *) TM_SELKEY=l ;;
      esac
    fi
    tunnel_card "$n"
    echo
    tunnel_menu_build "$n" "$r" "$run" "$boot" "$car" "$z_ok" "$rev" "$auto" "$comp"
    tunnel_menu_render
    tunnel_menu_help_line
    echo
    tunnel_menu_footer
    KEY_NAV=1; key_read; KEY_NAV=0
    case "$KEY" in
      up|down|left|right) tunnel_menu_move "$KEY"; continue ;;
      tab|$'\t') tunnel_menu_move right; continue ;;
      enter|' ') [ -n "$TM_SELKEY" ] && KEY=$TM_SELKEY || continue ;;
    esac
    tunnel_menu_select "$KEY"
    case "$KEY" in
      d|D) page "Diagnose" "$n"; run_flow test_tunnel "$n"; pause ;;
      v|V) page "Speed test" "$n"; run_flow speed_test "$n"; pause ;;
      l|L) page "Logs" "$n"; run_flow logs_menu "$n"; pause ;;
      m|M) run_flow live_monitor ;;
      p|P) run_flow edit_ports "$n"; pause ;;
      q|Q) run_flow limits_menu "$n" ;;
      c|C) page "Connection type" "$n"; run_flow change_type "$n"; pause ;;
      b|B) run_flow bonding_menu "$n" ;;
      a|A) [ "$r" = Iran ] && run_flow auto_menu "$n" ;;
      h|H) if [ "$r" = Kharej ] && is_reverse "$n" && [ -z "$(companion_of "$n")" ]; then page "Entry address" "$n"; echo; run_flow change_peer "$n"; pause
           elif [ "$r" = Iran ]; then
             if is_reverse "$n"; then
               [ "$(cfg "$n" carrier)" != icmp ] && { page "Carrier listen port" "$n"; echo; run_flow change_peer "$n"; pause; }
             else page "Exit address" "$n"; echo; run_flow change_peer "$n"; pause; fi
           fi ;;
      t|T) if [ "$r" = Kharej ]; then
           par=$(companion_of "$n")
           page "Token" "$n"
           show_token "${par:-$n}"
         else page "New token" "$n"
               hint "Replaces the exit server, key and carrier; ports stay."
               echo; run_flow change_key "$n"; fi
         pause ;;
      k|K) if [ "$r" = Kharej ]; then
           par=$(companion_of "$n"); page "New key" "$n"
           run_flow change_key "${par:-$n}"; pause
         else anticensor_menu "$n"; fi ;;
      o|O) run_flow adv_menu "$n" ;;
      z|Z) anticensor_menu "$n" ;;
      r|R) echo; if confirm "Restart '$n'? Open connections drop." n; then step "Restarting ${WAT_PREFIX}@$n" auto_for_each_unit "$n" restart; sleep 1; fi ;;
      s|S) echo
         if [ "$run" = active ]; then auto_for_each_unit "$n" stop; ok "Stopped (it still starts at boot if enabled)."; sleep 1
         else start_unit "$n"; sleep 1; fi ;;
      e|E) echo
         if systemctl is-enabled -q "${WAT_PREFIX}@$n" 2>/dev/null; then auto_for_each_unit "$n" disable; ok "Will NOT start at boot."
         else auto_for_each_unit "$n" enable; ok "Will start at boot."; fi
         sleep 1 ;;
      x|X) page "Delete tunnel" "$n"; echo; run_flow delete_tunnel "$n"; pause ;;
      0|esc) return 0 ;;
      \?|\/|help) tunnel_menu_keys "$n"; continue ;;
      *) : ;;
    esac
  done
}

# ======================================================================================
#  Auto-heal, update, rollback, uninstall, settings
# ======================================================================================
# The heal timer also drives the automatic auto-tunnel cleanup (R3: prune, widen safety net), so a Kharej-only server
# with an auto tunnel needs it too (ensure_prune_timer below installs it). heal() itself is role-gated: the restart/
# retest/matrix work runs only for Iran tunnels, so on a server it can only prune/widen. WAT_UNIT_DIR is a self-test
# hook (write the unit files into a throwaway directory); production always uses /etc/systemd/system.
unit_dir() { printf '%s' "${WAT_UNIT_DIR:-/etc/systemd/system}"; }
# heal_running: enabled AND running; a stopped timer heals nothing, so it reads off and h starts it (4.0.12)
heal_running() { systemctl is-enabled -q "$HEAL_UNIT.timer" 2>/dev/null && systemctl is-active -q "$HEAL_UNIT.timer" 2>/dev/null; }
heal_enable() {
  local mgr=/usr/local/bin/wattun-manager ud
  ud=$(unit_dir); mkdir -p "$ud" 2>/dev/null
  [ "$SANDBOX" = 1 ] && mgr=$MGR
  {
    printf '[Unit]\nDescription=WatTunnel auto-heal%s\n[Service]\nType=oneshot\n' "$([ "$SANDBOX" = 1 ] && echo " (sandbox $WAT_PREFIX)")"
    unit_env_lines
    printf 'ExecStart=%s heal\n' "$mgr"
  } >"$ud/$HEAL_UNIT.service"
  cat >"$ud/$HEAL_UNIT.timer" <<EOF
[Unit]
Description=WatTunnel auto-heal and auto-tunnel cleanup every minute
[Timer]
OnBootSec=2min
OnUnitActiveSec=1min
[Install]
WantedBy=timers.target
EOF
  chmod 644 "$ud/$HEAL_UNIT.service" "$ud/$HEAL_UNIT.timer"
  systemctl daemon-reload && systemctl enable --now "$HEAL_UNIT.timer" >/dev/null 2>&1 && ok "Auto-heal and auto-tunnel cleanup enabled."
}
heal_disable() {
  local ud; ud=$(unit_dir)
  systemctl disable --now "$HEAL_UNIT.timer" >/dev/null 2>&1
  rm -f "$ud/$HEAL_UNIT.service" "$ud/$HEAL_UNIT.timer"
  ok "Auto-heal disabled."
}
prune_timer_needed() { # role is-auto(1|0) -> 0 when this host has an auto Kharej tunnel that needs the heal timer
  [ "${1:-}" = Kharej ] && [ "${2:-0}" = 1 ]
}
ensure_heal_timer() { # an auto Kharej tunnel is healed/maintained by heal(), so its timer must exist even on a Kharej-only server
  local n any=0
  for n in $(tunnels); do
    prune_timer_needed "$(role "$n")" "$(is_auto_kharej "$n" && echo 1 || echo 0)" && { any=1; break; }
  done
  [ "$any" = 1 ] || return 0
  systemctl is-enabled -q "$HEAL_UNIT.timer" 2>/dev/null && return 0
  heal_enable >/dev/null 2>&1 && logger -t wattun-auto "enabled the heal timer (auto-tunnel maintenance)"
  return 0
}
ensure_prune_timer() { ensure_heal_timer "$@"; }
mgr_lock() { # L10: one manager pass at a time; fd 9 holds the lock until this process exits (no explicit unlock)
  mkdir -p "$RUN" 2>/dev/null
  command -v flock >/dev/null 2>&1 || return 0 # no flock (a stripped test host): run unlocked, never refuse to work
  exec 9>"$RUN/manager.lock" || return 0
  flock -n 9 && return 0
  warn "Another wattun-manager pass is running; skipping this one."
  return 1
}
# One systemd read per heal pass: an auto Kharej has ~75 units, and an is-active/is-enabled call per unit (~200 a
# pass, each a round trip through PID 1) cost 40+ s of CPU a minute on a 1-core server. U_SNAP=0: ask systemd.
declare -A U_ST=()
U_SNAP=0
units_snapshot() {
  local u load act rest
  U_ST=()
  while read -r u load act rest; do [ -n "$act" ] && U_ST[${u%.service}]=$act; done < <(systemctl list-units --all --plain --no-legend "${WAT_PREFIX}@*" 2>/dev/null)
  # an empty answer (no unit loaded, or a systemctl that cannot list) proves nothing: keep asking per unit
  [ "${#U_ST[@]}" -gt 0 ] && U_SNAP=1 || U_SNAP=0
}
u_state() { # name -> active/inactive/failed/activating/...: a unit systemd has not loaded is inactive
  if [ "$U_SNAP" = 1 ]; then printf '%s' "${U_ST[${WAT_PREFIX}@$1]:-inactive}"; else systemctl is-active "${WAT_PREFIX}@$1" 2>/dev/null; fi
}
u_active() { if [ "$U_SNAP" = 1 ]; then [ "${U_ST[${WAT_PREFIX}@$1]:-}" = active ]; else systemctl is-active -q "${WAT_PREFIX}@$1" 2>/dev/null; fi; }
u_enabled() { # the wants/ symlink answers without systemd; anything else (a disabled unit) asks it
  [ "$U_SNAP" = 1 ] && compgen -G "/etc/systemd/system/*.wants/${WAT_PREFIX}@$1.service" >/dev/null && return 0
  systemctl is-enabled -q "${WAT_PREFIX}@$1" 2>/dev/null
}
heal() { # restart Iran tunnels whose link is down or breaches SLA 3 checks in a row
  local n cnt f st cyc sla_f b_f slow=0
  HEAL_PASS=1
  mkdir -p "$RUN"
  units_snapshot
  # the web panel: restarted only when it is on (panel.conf) and its unit failed; a panel that is off stays off
  if [ -f "$CONF/panel.conf" ] && systemctl is-failed -q "${WAT_PREFIX}-panel" 2>/dev/null; then
    logger -t wattun-heal "web panel failed, restarting" 2>/dev/null || true
    systemctl restart "${WAT_PREFIX}-panel" 2>/dev/null || true
  fi
  for n in $(tunnels); do
    [ "$(role "$n")" = Iran ] && u_enabled "$n" || continue
    f="$RUN/$n.down"
    b_f="$RUN/$n.sla_breach"
    # no metrics: line means no /stats to judge by: never count it as down (it would restart every 3 checks forever)
    if [ -z "$(cfg "$n" metrics)" ]; then rm -f "$f" "$RUN/$n.cycles" "$b_f" "$RUN/$n.sla_bytes"; continue; fi
    st=$(u_state "$n")
    if [ "$st" = inactive ]; then rm -f "$f" "$RUN/$n.cycles" "$b_f" "$RUN/$n.sla_bytes"; continue; fi # stopped on purpose: leave it alone
    local s_raw; s_raw=$(stats_flat "$n")
    local rx_age; rx_age=$(jget "$s_raw" last_rx_age_ms 2>/dev/null || echo -1)
    if [ "$(jget "$s_raw" alive)" = true ] && [ "$rx_age" -ge 0 ] && [ "$rx_age" -lt 35000 ]; then
      rm -f "$f" "$RUN/$n.cycles"
      sla_f="$CONF/$n.sla"
      if [ -f "$sla_f" ]; then
        local min_r max_rtt max_loss rtt loss tot now prev_tot prev_t act rate_kbps="" breached=0
        min_r=$(grep '^sla_min_rate_kbps=' "$sla_f" 2>/dev/null | cut -d= -f2)
        max_rtt=$(grep '^sla_max_rtt_ms=' "$sla_f" 2>/dev/null | cut -d= -f2)
        max_loss=$(grep '^sla_max_loss_pct=' "$sla_f" 2>/dev/null | cut -d= -f2)
        rtt=$(jget_flat "$s_raw" rtt_ms srtt_ms)
        loss=$(jget "$s_raw" loss_pct)
        # measured throughput in kbit/s from the byte counters since the last check (rate_bps is the pacer's allowed
        # rate in bytes/s, not traffic). awk does the math: the counters outgrow bash on 32-bit and may print as 1.2e+07.
        tot=$(awk -v a="$(jget "$s_raw" bytes_in_total)" -v b="$(jget "$s_raw" bytes_out_total)" 'BEGIN { printf "%.0f", a + b }')
        now=$(date +%s)
        if [ -f "$RUN/$n.sla_bytes" ] && read -r prev_tot prev_t <"$RUN/$n.sla_bytes"; then # first run or a restart (counter went back): no verdict
          rate_kbps=$(awk -v t="$tot" -v p="${prev_tot:-0}" -v n="$now" -v q="${prev_t:-0}" 'BEGIN { if (t >= p && n > q) printf "%d", (t - p) * 8 / 1000 / (n - q) }')
        fi
        echo "$tot $now" >"$RUN/$n.sla_bytes"
        act=$(jget_flat "$s_raw" streams_total streams) # an idle tunnel is not slow: judge the rate only while streams are open
        [ -n "$max_rtt" ] && [ "$max_rtt" -gt 0 ] && [ "${rtt%.*}" -gt "$max_rtt" ] 2>/dev/null && breached=1
        [ -n "$max_loss" ] && [ "$max_loss" -gt 0 ] && [ "${loss%.*}" -gt "$max_loss" ] 2>/dev/null && breached=1
        [ -n "$min_r" ] && [ "$min_r" -gt 0 ] && [ -n "$rate_kbps" ] && [ "${act:-0}" -gt 0 ] && [ "$rate_kbps" -lt "$min_r" ] 2>/dev/null && breached=1
        if [ "$breached" = 1 ]; then
          local b_cnt=$(( $(cat "$b_f" 2>/dev/null || echo 0) + 1 ))
          echo "$b_cnt" >"$b_f"
          if [ "$b_cnt" -ge 3 ]; then
            logger -t wattun-heal "tunnel $n breached SLA for 3 consecutive checks (rtt=${rtt}ms, loss=${loss}%, rate=${rate_kbps:-?}kbps), triggering re-evaluation"
            rm -f "$b_f"
            touch "$RUN/$n.sla_triggered"
            if [ -f "$CONF/$n.auto" ]; then
              heal_retest "$n"
            fi
          fi
        else
          rm -f "$b_f"
        fi
      fi
      continue
    fi
    cnt=$(( $(cat "$f" 2>/dev/null || echo 0) + 1 )); echo "$cnt" >"$f"
    if [ "$cnt" -ge 3 ]; then
      logger -t wattun-heal "tunnel $n down for $cnt checks, restarting"
      systemctl restart "${WAT_PREFIX}@$n"; rm -f "$f"
      cyc=$(( $(cat "$RUN/$n.cycles" 2>/dev/null || echo 0) + 1 )); echo "$cyc" >"$RUN/$n.cycles"
      # a direct Iran pool tunnel (single or bonded) that restarts do not fix: tell the operator the kit exists
      if [ "$cyc" -ge 2 ] && ! is_reverse "$n" && is_pool_list "$(cfg "$n" carrier)" \
         && [ "$(cfg "$n" fake-sni)" = '' ]; then
        logger -t wattun-heal "tunnel $n: restarts do not fix it and it runs with no anti-censor; if the route is being filtered, run: wattun blackout $n <allowlisted-name>"
      fi
      # still down after three restart cycles (9 checks) on a pool/icmp tunnel: try the full matrix unattended
      if [ "$cyc" -ge 3 ] && ! is_reverse "$n" && { is_pool "$(cfg "$n" carrier)" || [ "$(cfg "$n" carrier)" = icmp ]; }; then
        heal_matrix "$n"
      fi
      # auto tunnel still down after two restart cycles (6 checks): test the other connection types in the background
      # (a plain CDN tunnel gets a fresh Cloudflare edge scan instead: dead edge IPs are replaced)
      if [ "$cyc" -ge 2 ] && { [ -f "$CONF/$n.auto" ] || { cdn_ok && cdn_tunnel_p "$n"; }; }; then heal_retest "$n"; fi
    fi
  done
  # Migrate legacy finalized/narrowed auto Kharej tunnels and keep all auto test carriers + companions running.
  # The slow half (migration, and the Iran-IP sync that reads every helper's /stats) runs every 5 minutes: it was
  # most of a pass, and Iran's IP rarely moves. A tunnel made in the last 10 minutes without its companion yet is
  # synced every pass, so a new auto tunnel still gets its reverse fallback within a minute of Iran connecting.
  if [ ! -f "$RUN/heal.slow" ] || [ -n "$(find "$RUN/heal.slow" -mmin +4 2>/dev/null)" ]; then slow=1; touch "$RUN/heal.slow"; fi
  [ "$slow" = 1 ] && auto_migrate_all 0
  # 4.1.2: a deleted or rolled-back auto tunnel left its shaped helpers running with no parent
  local ax u par
  for ax in "$CONF"/*-e-*.autoext; do
    [ -f "$ax" ] || continue
    u=$(basename "$ax" .autoext); par=$(head -n1 "$ax" | tr -d '[:space:]')
    [ -n "$par" ] && [ ! -f "$CONF/$par.yml" ] || continue
    logger -t wattun-heal "removing $u: its auto tunnel $par is gone" 2>/dev/null || true
    auto_drop_unit "$u"
  done
  for n in $(tunnels); do
    [ "$(role "$n")" = Kharej ] && is_auto_kharej "$n" || continue
    if [ "$slow" = 1 ] || { [ ! -f "$CONF/$n-r.yml" ] && [ -n "$(find "$CONF/$n.yml" -mmin -10 2>/dev/null)" ]; }; then
      auto_sync_companion "$n"
    fi
    heal_auto_helpers "$n"
  done
}
# A running tunnel keeps executing the binary it was started with. Once update/rollback replaces the file,
# /proc/PID/exe reads "... (deleted)": that tunnel still runs the OLD version until it is restarted.
bin_ver() { "${1:-$BIN}" -version 2>/dev/null | awk '{print $2; exit}'; }
is_stale() {
  local pid
  pid=$(systemctl show -p MainPID --value "${WAT_PREFIX}@$1" 2>/dev/null)
  [ -n "$pid" ] && [ "$pid" != 0 ] && [[ "$(readlink "/proc/$pid/exe" 2>/dev/null)" == *"(deleted)"* ]]
}
stale_tunnels() { # prints unique visible tunnel names whose service (or hidden auto helper) still runs an old binary
  local u p seen=' '
  for u in $(tunnels_all); do
    is_probe_unit "$u" && continue # a live probe is throw-away machinery: it dies at its ttl, never a restart prompt
    systemctl is-active -q "${WAT_PREFIX}@$u" 2>/dev/null || continue
    is_stale "$u" || continue
    p=$(companion_of "$u")
    [ -n "$p" ] || { [ -f "$CONF/$u.autoext" ] && p=$(head -1 "$CONF/$u.autoext" 2>/dev/null); }
    p=${p:-$u}
    case "$seen" in *" $p "*) ;; *) seen+="$p "; printf '%s ' "$p" ;; esac
  done
}
restart_stale() { # offer to restart tunnels that still run the old binary, then prove they switched
  local st n hu bad=''
  st=$(stale_tunnels)
  [ -n "$st" ] || { ok "All running tunnels use wattun $(bin_ver)."; return 0; }
  warn "Still running the OLD binary: ${BOLD}${st% }${RST}"
  hint "They switch to $(bin_ver) only after a restart. A restart drops open connections for a few seconds."
  confirm "Restart them now?" y || { hint "Later: open the tunnel and press [r], or Settings -> restart all."; return 0; }
  for n in $st; do step "Restarting ${WAT_PREFIX}@$n" auto_for_each_unit "$n" restart; done
  sleep 1
  for n in $st; do
    if is_stale "$n"; then bad="$bad $n"; continue; fi
    if is_auto_kharej "$n"; then
      for hu in $(auto_helpers "$n"); do
        systemctl is-active -q "${WAT_PREFIX}@$hu" 2>/dev/null && is_stale "$hu" && { bad="$bad $n"; break; }
      done
    fi
  done
  if [ -n "$bad" ]; then err "Still on the old binary:$bad (see: journalctl -u ${WAT_PREFIX}@NAME)"; return 1; fi
  ok "Tunnels now run wattun $(bin_ver)."
}
restart_all() {
  local n c=0
  for n in $(tunnels); do # hidden auto helpers restart with their parent
    if systemctl is-enabled -q "${WAT_PREFIX}@$n" 2>/dev/null || systemctl is-active -q "${WAT_PREFIX}@$n" 2>/dev/null; then
      step "Restarting ${WAT_PREFIX}@$n" auto_for_each_unit "$n" restart; c=$((c+1))
    fi
  done
  [ "$c" -gt 0 ] || warn "No tunnels to restart."
}
U_URL_PREFIX=''; U_CURL_PROXY=''
apply_update_proxy() { # url -> U_URL_PREFIX (mirror prefix) or U_CURL_PROXY (curl -x proxy)
  local v=${1:-}
  U_URL_PREFIX=''; U_CURL_PROXY=''
  [ -n "$v" ] || return 0
  case "$v" in
    socks4://*|socks4a://*|socks5://*|socks5h://*) U_CURL_PROXY=$v ;;
    http://*)
      if [[ "$v" =~ ^http://([^/]*@)?(\[[0-9a-fA-F:]+\]|[^/:]+):[0-9]{1,5}/?$ ]]; then U_CURL_PROXY=${v%/}
      else U_URL_PREFIX="${v%/}/"; fi ;;
    https://*)
      if [[ "$v" =~ ^https://[^/]*@ ]] || [[ "$v" =~ ^https://(127\.|localhost|\[::1\])(:[0-9]{1,5})?/?$ ]]; then U_CURL_PROXY=${v%/}
      else U_URL_PREFIX="${v%/}/"; fi ;;
    *)
      if [[ "$v" =~ ^(\[[0-9a-fA-F:]+\]|[^/:]+):[0-9]{1,5}$ ]]; then U_CURL_PROXY=$v
      else U_URL_PREFIX="${v%/}/"; fi ;;
  esac
}
update_proxy_env() { # env WAT_PROXY / WAT_CURL_PROXY win; else .manager.conf update-proxy
  U_URL_PREFIX=${WAT_PROXY:-}; U_CURL_PROXY=${WAT_CURL_PROXY:-}
  [ -n "$U_URL_PREFIX" ] && U_URL_PREFIX="${U_URL_PREFIX%/}/"
  if [ -z "$U_URL_PREFIX" ] && [ -z "$U_CURL_PROXY" ]; then
    local saved; saved=$(conf_get update-proxy '')
    [ -n "$saved" ] && apply_update_proxy "$saved"
  fi
  return 0
}
u_curl() { # [curl args...] : curl with update proxy + retry-all-errors fallback for curl < 7.71
  local -a px=()
  [ -n "${U_CURL_PROXY:-}" ] && px=(-x "$U_CURL_PROXY")
  if curl --help all 2>&1 | grep -q -- '--retry-all-errors'; then
    curl -fsSL ${px[@]+"${px[@]}"} --connect-timeout 10 --max-time 90 --retry 4 --retry-all-errors "$@"
  else
    curl -fsSL ${px[@]+"${px[@]}"} --connect-timeout 10 --max-time 90 --retry 4 "$@"
  fi
}
OFFLINE_DIR=''
resolve_offline_bundle() { # path extract_dir -> OFFLINE_DIR (directory containing install.sh)
  local src=$1 dst=$2 d
  OFFLINE_DIR=''
  if [ -d "$src" ] && [ -f "$src/install.sh" ]; then
    OFFLINE_DIR=$(cd "$src" 2>/dev/null && pwd) || OFFLINE_DIR=$src
    return 0
  fi
  if [ -f "$src" ]; then
    mkdir -p "$dst" || return 1
    if tar -xzf "$src" -C "$dst" 2>/dev/null || tar -xf "$src" -C "$dst" 2>/dev/null; then
      if [ -f "$dst/install.sh" ]; then OFFLINE_DIR=$dst; return 0; fi
      for d in "$dst"/*; do
        [ -d "$d" ] && [ -f "$d/install.sh" ] && { OFFLINE_DIR=$d; return 0; }
      done
    fi
  fi
  err "No install.sh found in '$src' (pass a wattun-offline-<arch>.tar.gz archive or its extracted directory)."
  return 1
}
bundle_cmd() { # [amd64|arm64] [dest.tar.gz] : build a signed offline install/update bundle (e.g. on Kharej for Iran)
  local arch=${1:-} out=${2:-} bdir sub base f got
  if [ -z "$arch" ]; then
    case "$(uname -m)" in
      x86_64|amd64) arch=amd64 ;;
      aarch64|arm64) arch=arm64 ;;
      *) err "Specify architecture: $SELF bundle amd64  or  $SELF bundle arm64"; return 1 ;;
    esac
  fi
  case "$arch" in amd64|arm64) ;; *) err "Unsupported bundle architecture '$arch' (use amd64 or arm64)."; return 1 ;; esac
  [ -n "$out" ] || out="$PWD/wattun-offline-$arch.tar.gz"
  for f in curl tar sha256sum openssl; do
    command -v "$f" >/dev/null 2>&1 || { err "'$f' is required to build and verify an offline bundle."; return 1; }
  done
  update_proxy_env
  base="${U_URL_PREFIX}https://github.com/$REPO/releases/latest/download"
  bdir=$(mktemp -d /tmp/wattun-bundle.XXXXXX) || { err "Cannot create a temporary directory."; return 1; }
  BDIR_TMP=$bdir
  sub="$bdir/wattun-offline-$arch"
  mkdir -p "$sub" || { rm -rf "$bdir"; BDIR_TMP=''; return 1; }
  spin_start "Downloading release files for linux/$arch"
  u_curl -o "$sub/install.sh" "$base/install.sh" \
    && u_curl -o "$sub/wattun-linux-$arch" "$base/wattun-linux-$arch" \
    && u_curl -o "$sub/wattun-manager" "$base/wattun-manager" \
    && u_curl -o "$sub/SHA256SUMS" "$base/SHA256SUMS" \
    && u_curl -o "$sub/SHA256SUMS.sig" "$base/SHA256SUMS.sig"
  local rc=$?
  spin_stop
  if [ "$rc" -ne 0 ]; then
    rm -rf "$bdir"; BDIR_TMP=''
    err "Download failed from $base."
    return 1
  fi
  if ! sums_verify "$sub/SHA256SUMS" "$sub/SHA256SUMS.sig"; then
    rm -rf "$bdir"; BDIR_TMP=''
    err "Signature check on SHA256SUMS failed; refusing to create an unverified bundle."
    return 1
  fi
  for f in install.sh "wattun-linux-$arch" wattun-manager; do
    got=$(sha256sum "$sub/$f" 2>/dev/null | awk '{print $1}')
    if [ -z "$got" ] || ! sums_has "$sub/SHA256SUMS" "$f" "$got"; then
      rm -rf "$bdir"; BDIR_TMP=''
      err "Checksum mismatch for $f in SHA256SUMS; aborting."
      return 1
    fi
  done
  chmod 755 "$sub/install.sh" "$sub/wattun-linux-$arch" "$sub/wattun-manager"
  if ! tar -czf "$out" -C "$bdir" "wattun-offline-$arch"; then
    rm -rf "$bdir"; BDIR_TMP=''
    err "Failed to write archive '$out'."
    return 1
  fi
  rm -rf "$bdir"; BDIR_TMP=''
  ok "Verified offline bundle written: ${BOLD}$out${RST}"
  hint "1. Copy to the entry server:   scp \"$out\" root@IRAN_IP:/root/"
  hint "2. Fresh install:  tar xzf /root/${out##*/} -C /root && bash /root/wattun-offline-$arch/install.sh"
  hint "3. Offline update: wattun update --from /root/${out##*/}"
  return 0
}
UPDATE_MIRRORS="https://ghfast.top/ https://gh-proxy.com/ https://ghproxy.net/ https://github.moeyy.xyz/" # same list as the Go manager
update() { # [--from <dir|tar.gz>] [installer args...]
  local url="https://raw.githubusercontent.com/$REPO/main/install.sh" tmp before after mbefore imgr a
  local from_src='' pass_args=() ienv=()
  while [ $# -gt 0 ]; do
    case "$1" in
      --from) [ $# -ge 2 ] || { err "--from needs a path to a .tar.gz bundle or directory"; return 1; }; from_src=$2; shift 2 ;;
      --from=*) from_src=${1#--from=}; shift ;;
      *)
        if [ -z "$from_src" ] && { [ -d "$1" ] && [ -f "$1/install.sh" ] || [[ "$1" == *.tar.gz || "$1" == *.tgz ]]; }; then
          from_src=$1; shift
        else
          pass_args+=("$1"); shift
        fi ;;
    esac
  done
  if [ "$SANDBOX" = 1 ]; then
    for a in ${pass_args[@]+"${pass_args[@]}"}; do [ "$a" = --uninstall ] && { err "Sandbox: use the manager's uninstall (Settings), not the installer's --uninstall (it removes the production units)."; return 1; }; done
    imgr=$MGR; [ "$MGR" = /usr/local/bin/wattun-manager ] && imgr=${BIN%/*}/wattun-manager
    mkdir -p "${BIN%/*}" || { err "Cannot create ${BIN%/*}"; return 1; }
    say "  Sandbox $WAT_PREFIX: the update writes only $BIN, $imgr and $CONF (not /usr/local/bin, not wattun@.service)."
  fi
  update_proxy_env
  before=$(bin_ver); mbefore=$(cksum <"${imgr:-$MGR}" 2>/dev/null)
  local udir; udir=$(mktemp -d /tmp/wattun-update.XXXXXX) || { err "Cannot create a temporary directory"; return 1; }
  UDIR_TMP=$udir
  tmp=$udir/install.sh # every temp file lives in one private (0700) directory: no guessable names in /tmp
  local sums=$udir/SHA256SUMS sig=$udir/SHA256SUMS.sig mkeep=$udir/manager.keep rc
  [ "$SANDBOX" = 1 ] && ienv=(WAT_BIN="$BIN" WAT_MGR="$imgr" WAT_CONF="$CONF" WAT_UNIT="$tmp.unit" WAT_REQUIRE_SANDBOX=1) # the installer's unit file goes to a throwaway path
  [ -n "$U_URL_PREFIX" ] && ienv+=(WAT_PROXY="$U_URL_PREFIX")
  [ -n "$U_CURL_PROXY" ] && ienv+=(WAT_CURL_PROXY="$U_CURL_PROXY")
  # keep the current manager so a bad replacement can be undone
  cp -f "${imgr:-$MGR}" "$mkeep" 2>/dev/null || { rm -f "$mkeep"; mkeep=""; }
  if [ -n "$from_src" ]; then
    resolve_offline_bundle "$from_src" "$udir/bundle" || { rm -rf "$udir"; UDIR_TMP=''; return 1; }
    tmp="$OFFLINE_DIR/install.sh"
    if [ "${WAT_ALLOW_UNSIGNED_UPDATE:-0}" != 1 ]; then
      local got bsums="$OFFLINE_DIR/SHA256SUMS" bsig="$OFFLINE_DIR/SHA256SUMS.sig"
      [ -f "$bsums" ] && [ -f "$bsig" ] || { rm -rf "$udir"; UDIR_TMP=''; err "Offline bundle '$from_src' is missing SHA256SUMS or SHA256SUMS.sig."; return 1; }
      sums_verify "$bsums" "$bsig" || { rm -rf "$udir"; UDIR_TMP=''; err "Signature verification failed on '$bsums'."; return 1; }
      got=$(sha256sum "$tmp" 2>/dev/null | awk '{print $1}')
      [ -n "$got" ] && sums_has "$bsums" install.sh "$got" || { rm -rf "$udir"; UDIR_TMP=''; err "install.sh checksum does not match signed SHA256SUMS."; return 1; }
      ok "Offline bundle verified against the pinned release key"
    else
      warn "WAT_ALLOW_UNSIGNED_UPDATE=1: running offline installer without checking SHA256SUMS.sig."
    fi
    ienv+=(WAT_OFFLINE_DIR="$OFFLINE_DIR")
  elif [ "${WAT_ALLOW_UNSIGNED_UPDATE:-0}" = 1 ]; then
    warn "WAT_ALLOW_UNSIGNED_UPDATE=1: fetching the installer without a signature check (only if you trust the source)."
    # raw.githubusercontent.com caches main for minutes: resolve main to a commit sha and fetch everything by it
    local sha mref=""
    sha=$(u_curl "${U_URL_PREFIX}https://api.github.com/repos/$REPO/commits/main" 2>/dev/null | grep -m1 '"sha"' | sed -n 's/.*"sha"[^"]*"\([0-9a-f]\{40\}\)".*/\1/p')
    if [ -n "$sha" ]; then url="https://raw.githubusercontent.com/$REPO/$sha/install.sh"; mref=$sha; ienv+=(WAT_MGR_REF="$sha")
    else warn "Could not resolve the latest commit; using the main branch (GitHub's cache may be a few minutes old)."; fi
    spin_start "Downloading the installer"
    u_curl -o "$tmp" "${U_URL_PREFIX}$url"; rc=$?
    spin_stop
    if [ "$rc" -ne 0 ] || ! head -c 2 "$tmp" | grep -q '#!'; then
      rm -rf "$udir"; UDIR_TMP=''; err "Update failed (could not download the installer). If GitHub is blocked: $SELF update --from <bundle.tar.gz> or set update proxy in Settings [p]."; return 1
    fi
    ok "Installer downloaded UNSIGNED${mref:+ (${mref:0:7})}"
  else
    # Release assets are immutable: verify the installer against the release's RSA-signed SHA256SUMS, then run it.
    local base got verified=0 dl_ok=0 pre pres
    local refusal="Cannot verify the installer against the signed release; refusing to run it unverified. On filtered the entry hosts, build a signed bundle on the exit server ($SELF bundle) and run: $SELF update --from wattun-offline-amd64.tar.gz"
    # no mirror or proxy set: direct first, then public GitHub mirrors (4.0.5); the pinned-key signature still
    # checks every file, so a mirror can only fail, not change what is installed
    pres="$U_URL_PREFIX"
    [ -z "$U_URL_PREFIX$U_CURL_PROXY" ] && pres="- $UPDATE_MIRRORS"
    if command -v openssl >/dev/null 2>&1; then
      for pre in $pres; do
        [ "$pre" = - ] && pre=''
        base="${pre}https://github.com/$REPO/releases/latest/download"
        spin_start "Downloading the installer and its signature${pre:+ through $pre}"
        u_curl -o "$tmp" "$base/install.sh" \
          && u_curl -o "$sums" "$base/SHA256SUMS" \
          && u_curl -o "$sig" "$base/SHA256SUMS.sig"
        rc=$?
        spin_stop
        if [ "$rc" -eq 0 ]; then
          dl_ok=1
          if sums_verify "$sums" "$sig"; then
            got=$(sha256sum "$tmp" 2>/dev/null | awk '{print $1}')
            if [ -n "$got" ] && sums_has "$sums" install.sh "$got"; then verified=1; fi
          fi
        fi
        if [ "$verified" = 1 ]; then
          [ "$pre" != "$U_URL_PREFIX" ] && { U_URL_PREFIX=$pre; ienv+=("WAT_PROXY=$pre"); }
          break
        fi
      done
    else
      warn "openssl is required to check the release signature."
    fi
    if [ "$verified" != 1 ]; then
      if [ "$dl_ok" = 0 ] && [ "$IS_TTY" = 1 ] && [ "$NONINTERACTIVE" != 1 ] && [ "${U_RETRIED:-0}" = 0 ]; then
        warn "Could not reach GitHub from this server."
        hint "Tip: on the exit server run '$SELF bundle', scp wattun-offline-<arch>.tar.gz here, or enter an HTTP/SOCKS5 proxy / mirror."
        ask "Proxy/mirror URL or path to offline .tar.gz (Enter = cancel)" ""
        if [ -n "$REPLY_V" ]; then
          rm -rf "$udir"; UDIR_TMP=''
          if [ -e "$REPLY_V" ]; then
            U_RETRIED=1 update --from "$REPLY_V" ${pass_args[@]+"${pass_args[@]}"}
            return $?
          fi
          confirm "Save '$REPLY_V' in Settings for future updates?" y && conf_set update-proxy "$REPLY_V"
          apply_update_proxy "$REPLY_V"
          U_RETRIED=1 WAT_PROXY="$U_URL_PREFIX" WAT_CURL_PROXY="$U_CURL_PROXY" update ${pass_args[@]+"${pass_args[@]}"}
          return $?
        fi
      fi
      rm -rf "$udir"; UDIR_TMP=''
      hint "The latest release must ship install.sh with SHA256SUMS and SHA256SUMS.sig signed by the pinned key."
      err "$refusal"; return 1
    fi
    ok "Installer verified against the signed release"
  fi
  env ${ienv[@]+"${ienv[@]}"} WAT_FROM_MANAGER=1 bash "$tmp" ${pass_args[@]+"${pass_args[@]}"}; rc=$?
  rm -f "$udir/install.sh" "$tmp.unit" "$sums" "$sig"
  [ "$rc" -eq 0 ] || { rm -rf "$udir"; UDIR_TMP=''; err "The installer reported an error. Nothing was changed: still wattun ${before:-?}."; return 1; }
  # self-check: in a sandbox the new manager must understand WAT_PREFIX, or it would drive the production paths
  if [ "$SANDBOX" = 1 ] && [ -n "$mkeep" ] && ! grep -q 'WAT_PREFIX' "${imgr:-$MGR}" 2>/dev/null; then
    install -m 755 "$mkeep" "${imgr:-$MGR}.new" && mv -f "${imgr:-$MGR}.new" "${imgr:-$MGR}"
    rm -rf "$udir"; UDIR_TMP=''; err "The new manager has no sandbox (WAT_PREFIX) support; the previous manager was restored."; return 1
  fi
  rm -rf "$udir"; UDIR_TMP=''
  after=$(bin_ver)
  echo
  if [ -z "$after" ]; then err "$BIN does not run after the update. Roll back from the dashboard ([r])."; return 1
  elif [ "$after" != "$before" ]; then ok "wattun updated: ${BOLD}${before:-none} -> $after${RST}"
  else ok "wattun is already the latest release (${BOLD}$after${RST})."; fi
  [ "$(cksum <"${imgr:-$MGR}" 2>/dev/null)" != "$mbefore" ] && ok "Manager updated."
  restart_stale
  return 0
}
rollback() {
  [ -x "$BIN.prev" ] || { warn "No previous version saved."; return 0; }
  say "  Current: ${BOLD}$($BIN -version 2>&1)${RST}    Previous: ${BOLD}$($BIN.prev -version 2>&1)${RST}"
  echo
  confirm "Roll back to the previous version?" n || return 0
  cp -f "$BIN" "$BIN.rb" && mv -f "$BIN.prev" "$BIN" && mv -f "$BIN.rb" "$BIN.prev"
  ok "Rolled back: wattun is now ${BOLD}$(bin_ver)${RST}."
  restart_stale
  return 0
}
uninstall_all() {
  local n list=() u units p
  for n in $(tunnels_all); do list+=("$n"); done # B3: hidden extended listeners are removed with their parent
  echo
  if [ "${#list[@]}" -gt 0 ]; then
    warn "These tunnels will be stopped:"
    for n in "${list[@]}"; do printf '      %s%-14s%s %s · %s\n' "$BOLD" "$n" "$RST" "$(role "$n")" "$(cfg "$n" carrier)"; done
  else hint "No tunnels are configured."; fi
  echo
  if [ "$NONINTERACTIVE" = 1 ]; then REPLY_V=uninstall # --yes is the confirmation
  else ask "Type 'uninstall' to remove WatTunnel (empty = cancel)" ""; fi
  [ "$REPLY_V" = uninstall ] || { warn "Cancelled."; return 1; }
  heal_disable >/dev/null 2>&1 # stops the timer and removes its unit files (heal_disable removes them)
  # loaded instances plus every configured name (enabled-but-unloaded ones are not in list-units)
  units=$(systemctl list-units --all --plain --no-legend "${WAT_PREFIX}@*" 2>/dev/null | awk '{print $1}')
  for n in "${list[@]}"; do units+=$'\n'"${WAT_PREFIX}@$n.service"; done
  for u in $(printf '%s\n' "$units" | sort -u); do
    systemctl disable --now "$u" >/dev/null 2>&1
  done
  # F17: the hidden extended listeners had a UDP rule opened per child; close them while their configs are readable
  for n in "${list[@]}"; do
    is_auto_ext "$n" || continue
    p=$(cfg "$n" listen); p=${p##*:}
    [ -n "$p" ] && is_shaped_udp "$(cfg "$n" carrier)" && fw_close "$p/udp"
  done
  kreply_restore
  # every timer/transient unit the manager created for a tunnel goes with it (bond-retest, watcher, retest, matrix)
  for u in /etc/systemd/system/"${WAT_PREFIX}-bondretest-"*.service /etc/systemd/system/"${WAT_PREFIX}-bondretest-"*.timer; do
    [ -e "$u" ] || continue
    systemctl disable --now "${u##*/}" >/dev/null 2>&1
    rm -f "$u"
  done
  for u in $(systemctl list-units --all --plain --no-legend "${WAT_PREFIX}-autowatch-*" "${WAT_PREFIX}-autoretest-*" "${WAT_PREFIX}-matrix-*" 2>/dev/null | awk '{print $1}'); do
    systemctl stop "$u" >/dev/null 2>&1; systemctl reset-failed "$u" >/dev/null 2>&1
  done
  # F8: a custom state-dir puts totals/quota outside $CONF; remove each tunnel's files before its config goes
  for n in "${list[@]}"; do
    while IFS= read -r u; do rm -f "$u"; done < <(state_files "$n")
  done
  rm -f "/etc/systemd/system/${WAT_PREFIX}@.service" "$BIN" "$BIN.prev"
  [ "$SANDBOX" = 1 ] && rm -rf "$RUN" "$AUTO_RUN"
  if [ "$SANDBOX" = 1 ] && [ "${BIN%/*}" = "/opt/$WAT_PREFIX" ]; then rm -rf "/opt/$WAT_PREFIX"; ok "Removed /opt/$WAT_PREFIX"; fi
  systemctl daemon-reload
  ok "Services and binaries removed."
  if [ -d "$CONF" ] && confirm "Also delete $CONF (tunnel configs, keys, tokens)?" "$([ "$SANDBOX" = 1 ] || [ "$NONINTERACTIVE" = 1 ] && echo y || echo n)"; then rm -rf "$CONF"; ok "Configuration deleted."; fi
  ok "WatTunnel removed."
  if [ "$SANDBOX" = 1 ]; then
    if [ "${MGR%/*}" = "/opt/$WAT_PREFIX" ]; then rm -rf "/opt/$WAT_PREFIX"; ok "Removed /opt/$WAT_PREFIX (including this script)"
    else hint "Sandbox: this script ($MGR) was left in place; delete it by hand if you copied it."; fi
  else rm -f "$MGR"; fi
  return 0
}
settings_menu() {
  local heal_on anim_on up_px sd pad psc
  while :; do
    heal_running && heal_on="${GRN}on${RST} " || heal_on="${GRY}off${RST}"
    [ "$(conf_get anim 1)" = 1 ] && anim_on="${GRN}on${RST} " || anim_on="${GRY}off${RST}"
    up_px=$(conf_get update-proxy '')
    sd=$(server_side)
    page "Settings"
    printf '  %s %-15s %s   %srestarts down Iran tunnels & syncs auto%s\n' "$(key_label h)" 'Auto-heal' "$heal_on" "$GRY" "$RST"
    printf '  %s %-15s %s   %sspinners and intro reveal%s\n' "$(key_label a)" 'Animations' "$anim_on" "$GRY" "$RST"
    printf '  %s %-15s %sBBR, fq, 64 MiB buffers%s\n' "$(key_label b)" 'Kernel boost' "$GRY" "$RST"
    printf '  %s %-15s %s%s%s\n' "$(key_label p)" 'Update proxy' "${up_px:+$BOLD}" "${up_px:-${GRY}direct${RST}}" "${up_px:+$RST}"
    printf '  %s %-15s %s%s%s\n' "$(key_label w)" 'Server role' "$BOLD" "${sd:-not set}" "$RST"
    if [ "$sd" = kharej ] || [ -z "$sd" ] || pairing_active; then # Scepter console: Kharej's local pairing panel
      # (3.5.0). An unsaved side must still reach the first-pair path — the CLI gate (scepter_kharej_only)
      # refuses an explicit Iran only, so hiding the entry on '' locked the first pairing out (round-2).
      if pairing_active; then psc="${GRN}paired${RST} ${GRY}($(pairing_get caps))${RST}"; else psc="${GRY}off${RST}"; fi
      printf '  %s %-15s %s\n' "$(key_label c)" 'Pairing' "$psc"
    fi
    echo
    menu_line r 'restart all' v 'roll back'
    hr
    pad=$(( UI_W - 22 )); [ "$pad" -lt 2 ] && pad=2
    printf '  %s back%*s%s %suninstall%s\n' "$(key_label 0)" "$pad" '' "$(key_label x)" "$RED" "$RST"
    printf '  %s▸%s ' "$CYN" "$RST"
    key_read
    case "$KEY" in
      v|V) page "Roll back"; echo; run_flow rollback; pause ;;
      x|X) page "Uninstall"; if run_flow uninstall_all; then exit 0; fi; pause ;;
      h|H) echo; if heal_running; then heal_disable; else heal_enable; fi; sleep 1 ;;
      r|R) echo; if confirm "Restart all tunnels? Open connections drop." n; then restart_all; sleep 1; fi ;;
      a|A) if [ "$(conf_get anim 1)" = 1 ]; then conf_set anim 0; ANIM=0; else conf_set anim 1; [ "$IS_TTY" = 1 ] && [ "${WAT_NO_ANIM:-0}" != 1 ] && ANIM=1; fi ;;
      b|B) boost_menu ;;
      c|C) { [ "$sd" = kharej ] || [ -z "$sd" ] || pairing_active; } || { warn "Pairing is managed on the exit server."; sleep 1; continue; }
           echo; scepter_menu ;;
      p|P)
        echo
        hint "https://ghproxy.net/ · socks5h://127.0.0.1:1080 · '-' to clear"
        ask "Update proxy / mirror URL" "$up_px"
        if [ "$REPLY_V" = "-" ]; then sed -i '/^update-proxy=/d' "$MCONF" 2>/dev/null || true; ok "Cleared update proxy."
        elif [ -n "$REPLY_V" ]; then conf_set update-proxy "$REPLY_V"; ok "Saved update proxy: $REPLY_V"; fi
        sleep 1 ;;
      w|W) ask_side || true ;;
      0|q|enter|esc) return 0 ;;
      *) : ;;
    esac
  done
}

# ======================================================================================
#  Main dashboard
# ======================================================================================
need_tunnel() { [ -f "$CONF/$1.yml" ] || { err "No tunnel named '$1'. See: $SELF status"; return 1; }; }
main_menu() {
  local num d rest rp
  while :; do
    local tn; tn=$(tunnels | wc -l); page_full "Tunnels" "$tn total"
    auto_migrate_all 1
    dash_table
    local st; st=$(stale_tunnels)
    [ -n "$st" ] && printf '\n  %s!%s old binary running on %s — open and press %s to load v%s\n' \
      "$YEL" "$RST" "${st% }" "$(key_label r)" "$VER"
    st=''; for rp in "$CONF"/*.repaste; do [ -e "$rp" ] && { rp=${rp##*/}; st="$st${rp%.repaste} "; }; done
    [ -n "$st" ] && printf '\n  %s!%s new token on %s — open, press %s and paste it on the entry server\n' \
      "$YEL" "$RST" "${st% }" "$(key_label t)"
    dash_actions
    while :; do
      printf '\r%s  %s▸%s %s%s%s' "$EL" "$CYN" "$RST" "$YEL" "$PMSG" "$RST"; PMSG=''
      key_read
      printf '\r%s' "$EL"
      [ "$IS_TTY" = 1 ] || echo
      case "$KEY" in
        [1-9])
          num=$KEY
          if [ "${#DASH_N[@]}" -gt 9 ]; then printf '%s' "$KEY"; IFS= read -r -t 5 rest || true; num="$KEY$rest"; fi
          if [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le "${#DASH_N[@]}" ]; then tunnel_page "${DASH_N[$((num-1))]}"; break
          else flash "No tunnel number $num."; fi ;;
        n|N) new_tunnel; break ;;
        a|A) batch_actions_menu; break ;;
        m|M) if [ "${#DASH_N[@]}" -gt 0 ]; then run_flow live_monitor; fi; break ;;
        s|S) settings_menu; break ;;
        u|U) page "Update"; echo; if update; then echo; hint "The manager reloads itself to show the new version."; pause; exec "$MGR"; fi; pause; break ;;
        q|Q) cur_show; echo; exit 0 ;;
        enter) break ;;
        *) if [ "${#DASH_N[@]}" -gt 0 ]; then
             flash "Unknown key '$KEY'. Press a tunnel's number to manage it, or n, a, m, s, u, q."
           else flash "Unknown key '$KEY'. Press n to create your first tunnel."; fi ;;
      esac
    done
  done
}

# Flags of kharej / iran / cdn-tune / auto-test / delete / uninstall -> NI_* presets and NI_POS (positional words).
# Both "--flag value" and "--flag=value" work. A bad value stops here with a message on stderr (rc 1).
ni_parse() {
  local f v hasv
  NI_POS=()
  while [ $# -gt 0 ]; do
    f=$1; shift; hasv=0; v=''
    case "$f" in --*=*) v=${f#*=}; f=${f%%=*}; hasv=1 ;; esac
    case "$f" in
      --yes) NI_YES=1; continue ;;
      --udp-dns) NI_UDPDNS=1; continue ;;
      --extended) NI_EXTENDED=1; continue ;; # B3: opt into the 13 shaped carriers (Kharej 3.3.0, per-shape units)
      --governor)
        if [ "$hasv" = 1 ]; then
          v_governor "$v" || return 1
          case "${v,,}" in on|1|true) NI_GOVERNOR=true ;; *) NI_GOVERNOR=false ;; esac
        elif [ $# -gt 0 ] && [[ "$1" != --* ]]; then
          v=$1; shift; v_governor "$v" || return 1
          case "${v,,}" in on|1|true) NI_GOVERNOR=true ;; *) NI_GOVERNOR=false ;; esac
        else
          NI_GOVERNOR=true
        fi; continue ;;
      --carrier|--name|--listen|--path|--addr|--sni|--cdn-domain|--ports|--max-mbps|--token|--map|--pick|--test|--sessions|--conns|--mtu|--policy|--fake-sni|--fake-mode|--fake-ttl|--pool-rotate|--pool-rotate-bytes|--preset|--ech|--dns-listen|--src-ip)
        if [ "$hasv" = 0 ]; then
          [ $# -gt 0 ] || { err "$f needs a value"; return 1; }
          v=$1; shift
        fi ;;
      --*) err "Unknown option '$f'. See: $SELF help"; return 1 ;;
      *) NI_POS+=("$f"); continue ;;
    esac
    case "$f" in
      --carrier) v_carrier_list "$v" || return 1; NI_CARRIER=$v ;;
      --preset) v_preset "$v" || return 1; NI_PRESET=$(preset_canonical "$v") ;;
      --ech)
        v_ech "$v" || return 1
        case "${v,,}" in
          off|auto|ladder) NI_ECH=${v,,} ;;
          *) NI_ECH=$v ;;
        esac ;;
      --name) v_name_fmt "$v" || return 1; NI_NAME=$v ;;
      --listen) v_port "$v" || return 1; NI_LISTEN=$((10#$v)) ;;
      --path) v_path "$v" || return 1; NI_PATH=$v ;;
      --addr) v_host "$v" || return 1; NI_ADDR=$v ;;
      --sni) v_host "$v" || return 1; NI_SNI=$v ;;
      --cdn-domain) v_domain_opt "$v" || return 1; NI_CDN=$v ;;
      --ports) [ -n "$v" ] || { err "--ports needs a list such as 18999,2000,53/udp"; return 1; }; NI_PORTS=$v ;;
      --max-mbps) v_mbps "$v" || return 1; NI_MBPS=$v ;;
      --fake-sni) v_sni_name "$v" || return 1; NI_FAKESNI=$v ;;
      --fake-mode) v_fake_mode "$v" || return 1; NI_FAKEMODE=$v ;;
      --fake-ttl) [[ "$v" =~ ^[0-9]{1,3}$ ]] && [ "$v" -le 255 ] || { err "--fake-ttl: use a hop count 0-255 (0 = auto, got '$v')"; return 1; }; NI_FAKETTL=$v ;;
      --pool-rotate) v_pool_rotate "$v" || return 1; NI_POOLROT=$v ;;
      --pool-rotate-bytes) v_pool_bytes "$v" || return 1; NI_POOLBYTES=$v ;;
      --test) case "$v" in normal|anti|fast|reverse|extended) NI_TEST=$v ;; *) err "--test: use normal, anti, fast, reverse or extended (got '$v')"; return 1 ;; esac ;;
      --token) v_token "$v" || return 1; NI_TOKEN=$v ;;
      --map) [ -n "$v" ] || { err "--map needs a list such as 39901:18999,8443:443"; return 1; }; NI_MAP=$v ;;
      --pick) case "$v" in best|bond|rbond) NI_PICK=$v ;; *,*|*+*) [[ "$v" =~ ^[0-9]+([,+][0-9]+)+$ ]] || { err "--pick: rows joined with commas or +, such as 1,3 or 1+3 (got '$v')"; return 1; }; NI_PICK=$v ;; *) [[ "$v" =~ ^[0-9]+$ ]] && [ "$v" -ge 1 ] || { err "--pick: use best, bond, a row number or rows such as 1,3 (got '$v')"; return 1; }; NI_PICK=$((10#$v)) ;; esac ;;
      --sessions) v_sessions "$v" || return 1; NI_SESSIONS=$((10#$v)) ;;
      --conns) v_conns "$v" || return 1; NI_CONNS=$((10#$v)) ;;
      --mtu) v_mtu "$v" || return 1; NI_MTU=$((10#$v)) ;;
      --policy) case "$v" in speed|latency|direct|bond) NI_POLICY=$v ;; *) err "--policy: use speed, latency, direct or bond (got '$v')"; return 1 ;; esac ;;
      --dns-listen) v_dns_listen "$v" || return 1; NI_DNSLISTEN=$v ;;
      --src-ip) v_src_ip "$v" || return 1; NI_SRCIP=$v ;;
    esac
  done
  return 0
}
v_name_fmt() { [[ "$1" =~ ^[a-zA-Z0-9_-]{1,32}$ ]] && return 0; err "--name: use 1-32 letters, digits, - or _ (got '$1')"; return 1; }
# Run a command-line flow without a subshell (so ERRN counts) and make sure a failure always says something on stderr.
ni_run() { # fn args...
  local rc
  ERRN=0
  "$@"; rc=$?
  if [ "$rc" -ne 0 ] && [ "$ERRN" -eq 0 ] && [ "$NONINTERACTIVE" = 1 ]; then err "failed (rc $rc), see the output above"; fi
  return "$rc"
}

usage() {
  cat <<EOF
WatTun manager $VER

Usage: $SELF [command]

  (no command)          dashboard: all tunnels; manage one, create, update...
  new [kharej|iran]     create a tunnel (do Kharej FIRST: it makes the token)
  kharej | iran         same as new kharej / new iran
  status | list         one line per tunnel
  monitor               live dashboard (any key exits)
  ports NAME            edit the port mappings of a tunnel
  test NAME             connection doctor + speed test
  speedtest NAME [MB]   speed test only (default 10 MB each way)
  mute NAME PATH        mute one bonded path (PATH = the leg name from /stats, e.g. udp or udp:up)
  unmute NAME PATH      unmute it again; both talk to the running tunnel's metrics server (no root)
  logs NAME             follow the log
  token NAME            print the Kharej token again
  panel [on|off|url|reset|2fa|2fa-reset]   web panel: turn on/off, show its address, new password, 2FA
  scepter [status|pair|rotate|revoke|audit]
                        Kharej's Pairing console: which Iran server may manage this one
                        (watp1: line, key rotation with a 24 h overlap, revocation, audit
                        tail). Both ends need wattun 3.5.0. Unattended: pair/rotate run as-is,
                        revoke needs --yes.
  preset NAME [PRESET]  apply built-in anti-censorship preset (rst-fast, mci, irancell, blackout, conservative)
  test-bypass NAME      automated connectivity & filter bypass test for anti-censorship profile
  profile save|list|show|del|apply   resilience profiles: save one tunnel's fake-sni/pool-rotate combination
                        under a name and re-apply it later (profile save NAME [tunnel])
  blackout NAME [SNI|PRESET] turn on resilience: accepts operator preset (rst-fast, mci, irancell, blackout, conservative)
                        or custom allowlisted SNI (e.g. mci.ir), restarts, tests filter bypass.
                        Fine-tuning (mode, ttl, pool-rotate, ech): tunnel page -> o -> k. Linux only.
  arm-blackout NAME     arm Kharej in Fortress mode (multi-carrier listeners, sysctls, firewall)
                        or arm Iran for autonomous failover (silence detection, heal timer)
  audit-blackout NAME   audit blackout readiness (capabilities, sysctls, port conflicts, DNS relay)
  matrix NAME           anti-censor matrix: test EVERY resilience combination (fake-SNI x mode x ECH)
                        from this Iran server with throw-away clients, apply the best that connects.
                        Bonded tunnels: every pool leg is tested. Kharej is never contacted except
                        through the tunnel itself. Linux only.
  reset-traffic NAME    zero the lifetime traffic counters the dashboard shows for a tunnel (restarts it)
  boost [--status|--undo|--yes]  kernel speed boost (BBR, 64MB buffers, FQ)
  iran-firewall [on|off|status]  accept connections on the client ports only from Iranian addresses
  backup [dest.tar.gz]  backup all tunnel configs and keys to archive
  restore <archive.tar.gz> restore tunnel configs and keys from archive
  start-all | stop-all  bulk start or stop all tunnels
  restart-all           restart all tunnels
  auto-optimize         run off-peak carrier re-evaluation for auto tunnels
  auto-test NAME        test every connection type again for an auto Iran tunnel, offer to switch
  auto-ip NAME IP       auto Kharej tunnel: set Iran's IP by hand (creates internal reverse companion)
  bond-retest NAME      bonded Iran tunnel: re-test every leg plus the last failures and add one that works again
  bond-add-rev NAME C   paired Iran tunnel: add carrier C (tcp/tls/ws/wss/h2/h2c/grpc) as a reverse leg; the exit server dials in
  bond-del-rev NAME C-rev  remove that reverse leg on both servers
  cdn-tune NAME [full]  Iran CDN tunnel (ws/wss/h2/h2c/grpc): find the Cloudflare edges that serve the domain over ECH + TLS settings, apply (needs wattun 2.2.0)
  heal                  restart Iran tunnels whose link is down (used by the timer)
  bundle [amd64|arm64] [OUT.tar.gz]  build a signed offline install/update bundle (e.g. on Kharej for Iran)
  update [--from PATH]  install the latest release (or offline from a verified bundle .tar.gz / directory)
  rollback              go back one version
  delete NAME           stop a tunnel and delete its config, key and token (asks you to type the name)
  uninstall             remove WatTun from this server (asks first)
  help                  this text

Unattended mode (no tty, nothing is asked; --yes turns it on, and so does any --flag when stdin is not a tty;
or NONINTERACTIVE=1). Plain output, errors on stderr, exit code 0 = done, 1 = failed:
  kharej --carrier C --name NAME [--listen PORT] [--path /wat] [--addr HOST] [--udp-dns]
         C = wss|grpc|tcp|tls|ws|h2|h2c|udp|icmp|auto, or one F19 shaped carrier (single carrier only, no + bond):
         sit|6to4|xfrm-ipsec|etherip|l2tpv3 (raw tier: bare-IP peer, Linux + root, no listen port, no reverse) and
         fou-gre|gue-ipip|vxlan|geneve|dnscrypt-udp|ntp-direct|openvpn-dco|srtp-direct (UDP tier: conventional port
         5555/6080/4789/6081/443/123/1194/5004 unless --listen gives one). F19 shapes are wattun-internal: both ends
         need 3.3.0+ and the SAME name, they do not talk to the real protocol.
         [--sni HOST] [--cdn-domain D] [--ports 18999,2000,53/udp] [--max-mbps N] [--extended] --yes
         creates and starts the Kharej tunnel; the last lines are TUNNEL=NAME and TOKEN=wat1:...
         C=auto: the token makes Iran test the standard transports (icmp, udp, tcp/tls/ws/wss/h2/h2c/grpc and
         gre/ipip, which need 3.2.0 on both ends). --extended (needs Kharej 3.3.0) also opens the 13 F19 shaped
         carriers, one hidden single-carrier listener per shape (wattun@NAME-e-<shape>); both ends must run 3.3.0 and
         old Iran ignores them, so their test ports stay open in the background for Iran to probe anytime. Raw tier needs CAP_NET_RAW
         and the cloud firewall to pass IP protocols 41/50/97/115.
         (--addr skips the public-IP detection; --cdn-domain is for auto; --listen/--path/--sni/--max-mbps for the others)
  iran --token TOKEN --map 39901:18999[,8443:443] [--name NAME] [--pick best|bond|N|N,N...] [--test normal|anti|fast|reverse|extended] [--sessions N] [--max-mbps N] --yes
         creates and starts the Iran tunnel. Auto token: runs the test, --pick chooses a row (default best, bond = all
         working direct carriers, 1,3 = join those rows). CDN token: automatic CDN tuning. Ends with LINK=up|down and TUNNEL=NAME; exit 1 if down.
         An extended auto token is tested too; carriers this engine cannot run are skipped with a hint and never written
         into the config.
         --test picks the preset (default normal): normal = direct+CDN+reverse; fast = rst/synrst against
         mci.ir/irancell.ir/cloudflare.com on every direct pool carrier (best row applied); anti = the full
         fake-SNI/fp grid; reverse = only the plan's r= carriers.
         --sessions N writes "sessions: N", 1-16 (only with wattun 2.3.0 or newer and one udp/tcp/tls/ws/wss/h2/h2c/grpc
         carrier: the engine refuses it on icmp/gre/ipip, the F19 shapes, bonds and reverse; otherwise it is ignored with a warning)
         --preset rst-fast|mci|irancell|blackout|conservative applies an operator-tailored anti-censorship preset
          --fake-sni NAME [--fake-mode MODE] [--fake-ttl 0-255] enables the fake-SNI desync on a
          fixed-type token (wattun 2.7.0 or newer; Linux only, needs CAP_NET_RAW; MODE is one of:
          $AC_ALLMODES -- older engines accept fewer, the manager refuses a mode the engine would reject;
          --fake-ttl only with --fake-mode ttl)
         [--pool-rotate 90s|30m|4h] [--pool-rotate-bytes 500MB|4G] recycle each healthy pool connection after this
         long / this much traffic (pool-rotate needs wattun 2.8.0, --pool-rotate-bytes 2.8.1; Linux only)
         [--ech off|auto|ladder] Encrypted Client Hello mode (ladder relays DoH via tunnel port 53; 2.9.0+)
         [--governor on|off] ICMP volume pacer against reroute triggers (2.9.0+)
  cdn-tune NAME [full] --yes      apply the best CDN variant without asking
  auto-test NAME --yes            re-test an auto Iran tunnel, switch to --pick (default best) without asking
  delete NAME --yes               delete a tunnel without asking
  uninstall --yes                 uninstall without asking; also deletes the config directory
  Flags also accept --flag=value.

Environment: WAT_NO_ANIM=1 (no animations)  NO_COLOR=1 (no colours)
  WAT_PROXY=https://ghproxy.net/  WAT_CURL_PROXY=socks5h://127.0.0.1:1080  WAT_OFFLINE_DIR=/path/to/bundle
  WAT_ALLOW_UNSIGNED_UPDATE=1 runs install.sh from main without checking the release signature (not recommended)

Sandbox: WAT_PREFIX=wattest wattun-manager ... keeps everything under /etc/wattest, /opt/wattest and wattest@ units.
  Other overrides: WAT_CONF, WAT_BIN, WAT_RUN, WAT_AUTO_RUN (single paths). The first run needs: WAT_PREFIX=wattest wattun-manager update
EOF
}

main() {
  [ -x "$BIN" ] && VER=$("$BIN" -version 2>/dev/null | awk '{print $2; exit}')
  case "${1:-}" in help|-h|--help) usage; return 0 ;; bundle) shift; bundle_cmd "$@"; return $? ;; esac
  case "${1:-}" in kharej|iran|cdn-tune|auto-test|delete|uninstall|preset|blackout|test-bypass|test-anticensor|matrix|arm-blackout|audit-blackout|scepter) ni_parse "${@:2}" || exit 1 ;; esac
  case "${1:-}" in auto-retest) [ "${2:-}" = --yes ] && NONINTERACTIVE=1 ;; esac
  if [ "$NONINTERACTIVE" = 1 ]; then
    case "${1:-}" in ''|new|monitor|ports|logs) err "'${1:-(no command)}' needs a terminal; unattended use: kharej, iran, cdn-tune, auto-test, delete, uninstall, status, test, token, matrix (see: help)"; exit 1 ;; esac
    case "${1:-}" in delete|uninstall) [ "$NI_YES" = 1 ] || { err "$1 without a terminal needs --yes"; exit 1; } ;; esac
  fi
  case "${1:-}" in mute|unmute) ;; *) [ "$(id -u)" -eq 0 ] || { err "Run as root."; exit 1; } ;; esac
  if [ ! -x "$BIN" ]; then
    if [ "$SANDBOX" = 1 ]; then
      [ "${1:-}" = update ] || { err "Sandbox $WAT_PREFIX: no wattun binary at $BIN yet. Install it with: $SELF update"; exit 1; }
    else err "wattun is not installed. Run install.sh first."; exit 1; fi
  fi
  case "${1:-}" in heal|auto-watch|auto-retest) ;; *)
    [ "$SANDBOX" = 1 ] && hint "Sandbox $WAT_PREFIX: configs $CONF, binary $BIN, units ${WAT_PREFIX}@NAME, runtime $RUN (production wattun is not touched)." ;;
  esac
  mkdir -p "$CONF" "$RUN"; [ "$(id -u)" -eq 0 ] && chmod 700 "$CONF"
  trap on_int INT
  trap cleanup EXIT
  trap 'cleanup; exit 143' TERM HUP
  # Ensure the heal timer runs on Kharej auto hosts too (syncs reverse companion, migrates legacy tunnels, heals helpers).
  case "${1:-}" in uninstall|update|mute|unmute) ;; *) ensure_heal_timer ;; esac
  case "${1:-}" in
    "") main_menu ;;
    new) new_tunnel "${2:-}" ;;
    kharej) if [ "$NONINTERACTIVE" = 1 ]; then ni_run wizard_kharej; else run_flow wizard_kharej; fi ;;
    iran) case " $* " in *" --use "*|*" --use="*) exec env -u WAT_BASH_MGR "$BIN" "$@" ;; esac # 4.5.1: --use (tested rows, no new test) is Go-manager only
      if [ "$NONINTERACTIVE" = 1 ]; then ni_run wizard_iran; else run_flow wizard_iran; fi ;;
    delete) need_tunnel "${NI_POS[0]:?name}" && if [ "$NONINTERACTIVE" = 1 ]; then ni_run delete_tunnel "${NI_POS[0]}"; else run_flow delete_tunnel "${NI_POS[0]}"; fi ;;
    uninstall) if [ "$NONINTERACTIVE" = 1 ]; then ni_run uninstall_all; else run_flow uninstall_all; fi ;;
    status|list) status_all ;;
    start-all) start_all ;;
    stop-all) stop_all ;;
    restart-all) restart_all ;;
    status-all) status_all ;;
    backup) shift; backup_cmd "$@" ;;
    restore) shift; restore_cmd "$@" ;;
    boost) shift; boost_cmd "$@" ;;
    scepter) shift; scepter_cmd "$@" ;;
    auto-optimize) auto_optimize_all ;;
    monitor) live_monitor ;;
    ports) need_tunnel "${2:?name}" && run_flow edit_ports "$2" ;;
    test) need_tunnel "${2:?name}" && test_tunnel "$2" ;;
    speedtest) need_tunnel "${2:?name}" && speed_test "$2" "${3:-10}" ;;
    mute) mute_cmd "${2:-}" "${3:-}" ;;
    unmute) unmute_cmd "${2:-}" "${3:-}" ;;
    logs) need_tunnel "${2:?name}" && journalctl -u "${WAT_PREFIX}@$2" -f -o short-iso ;;
    token) need_tunnel "${2:?name}" && show_token "$2" ;;
    panel) shift; exec env -u WAT_BASH_MGR "$BIN" panel "$@" ;; # the web panel lives in the Go manager (PLAN-panel.md D2)
    rename) shift; exec env -u WAT_BASH_MGR "$BIN" rename "$@" ;; # 4.0.11: one implementation, in the Go manager
    tune-live) shift; exec env -u WAT_BASH_MGR "$BIN" tune-live "$@" ;;
    preset) need_tunnel "${NI_POS[0]:-${2:-}}" && ni_run preset_cmd "${NI_POS[0]:-${2:-}}" "${NI_POS[1]:-${3:-}}" ;;
    test-anticensor|test-bypass) need_tunnel "${NI_POS[0]:-${2:-}}" && ni_run anticensor_test "${NI_POS[0]:-${2:-}}" ;;
    profile) shift; profile_cmd "$@" ;;
    blackout) need_tunnel "${NI_POS[0]:-${2:-}}" && ni_run blackout_cmd "${NI_POS[0]:-${2:-}}" "${NI_POS[1]:-${3:-}}" ;;
    arm-blackout) need_tunnel "${NI_POS[0]:-${2:-}}" && ni_run arm_blackout_cmd "${NI_POS[0]:-${2:-}}" ;;
    audit-blackout) need_tunnel "${NI_POS[0]:-${2:-}}" && ni_run audit_blackout_cmd "${NI_POS[0]:-${2:-}}" ;;
    matrix|anti-censor-matrix) need_tunnel "${NI_POS[0]:-${2:-}}" || return 1; mgr_lock || return 0; ni_run ac_matrix_cmd "${NI_POS[0]:-${2:-}}" ;;
    reset-traffic) need_tunnel "${NI_POS[0]:-${2:-}}" && ni_run reset_traffic "${NI_POS[0]:-${2:-}}" ;;
    heal) mgr_lock || return 0; heal ;;
    auto-test) need_tunnel "${NI_POS[0]:?name}" || return 1; mgr_lock || return 0; ni_run auto_test_cmd "${NI_POS[0]}" ;;
    auto-ip) need_tunnel "${2:?name}" || return 1; mgr_lock || return 0; auto_ip "$2" "${3:-}" ;;
    auto-widen) need_tunnel "${NI_POS[0]:-${2:-}}" || return 1; mgr_lock || return 0; ni_run auto_reopen "${NI_POS[0]:-${2:-}}" ;;
    auto-narrow|auto-prune) hint "Auto carrier lifecycle is automatic now; test carriers stay open in the background." ;;
    auto-watch) need_tunnel "${2:?name}" && auto_watch "$2" ;;
    auto-retest) need_tunnel "${2:?name}" || return 1; mgr_lock || return 0; auto_retest "$2" ;;
    bond-retest) shift; exec env -u WAT_BASH_MGR "$BIN" bond-retest "$@" ;; # 4.5.1: one implementation (reverse bonds too), in the Go manager
    bond-add-rev|bond-del-rev) exec env -u WAT_BASH_MGR "$BIN" "$@" ;; # 4.5.1: reverse bond legs change both servers through the pairing, Go manager only
    cdn-tune) need_tunnel "${NI_POS[0]:?name}" && ni_run cdn_tune_cmd "${NI_POS[0]}" "${NI_POS[1]:-}" ;;
    iran-firewall|anti-access) shift; iran_firewall_cmd "$@" ;;
    update) shift; update "$@" ;;
    rollback) rollback ;;
    *) usage; exit 1 ;;
  esac
}

if [ "$LIB" != 1 ]; then main "$@"; fi
