#!/bin/bash
# vpn-tunnel.sh — 新手包 v16 內置 8 條 SOCKS 隧道管理與自動校整腳本（應 Owner 61142 & 60564）
# 管理共 8 條隧道（讀 vpn-proxies.conf）：
#   ① 11080–11086 七條 WG 出口 SOCKS：以 ssh -N -L 127.0.0.1:<port>:127.0.0.1:<port> 建立（各席隨機共用）
#   ② 11090 SERVER_DIRECT 一條：強制以 ssh -N -D 127.0.0.1:11090 建立動態 SOCKS5（出口＝149.118.48.126；嚴禁用 -L，防 60564 得個聽字唔通陷阱）
#
# 用法：
#   bash vpn-tunnel.sh ensure|start   # 逐條檢查 8 條 listener，邊條唔喺度（或 11090 誤用 -L）即自動拉返起＋寫 log
#   bash vpn-tunnel.sh status         # 列出 8 條隧道 listener 狀態（全部在生 exit 0，缺任何一條 exit 1）
#   bash vpn-tunnel.sh restart        # 全停再起齊 8 條
#   bash vpn-tunnel.sh stop           # 停止全部由本腳本管理嘅隧道
#   bash vpn-tunnel.sh test           # 驗證 8 條 listener + 抽查 SOCKS5 出口 IP 對齊 vpn-proxies.conf
set -uo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
if [ -f "$HERE/env.sh" ]; then
  . "$HERE/env.sh"
elif [ -f "$HOME/workspace/arena-system/env.sh" ]; then
  . "$HOME/workspace/arena-system/env.sh"
fi

ARENA_HOME="${ARENA_HOME:-$HOME/workspace/arena-system}"
VPN_DIR="${VPN_DIR:-$HOME/workspace/vpn-tunnel}"
SSH_WRAPPER="${SSH_WRAPPER:-$HOME/workspace/ssh-newserver.sh}"
[ -x "$SSH_WRAPPER" ] || [ -f "$SSH_WRAPPER" ] || SSH_WRAPPER="$HERE/ssh-newserver.sh"

CONF="$VPN_DIR/vpn-proxies.conf"
[ -f "$CONF" ] || CONF="$HERE/vpn-proxies.conf"

mkdir -p "$ARENA_HOME/logs" "$ARENA_HOME/run" "$VPN_DIR"
LOG="$ARENA_HOME/logs/vpn-tunnel.log"
WD_LOG="$VPN_DIR/watchdog.log"

log_msg() {
  local ts
  ts="$(date '+%F %T')"
  local line="[$ts] [VPN-TUNNEL] $*"
  echo "$line" >> "$LOG"
  echo "$line" >> "$WD_LOG" 2>/dev/null || true
  echo "$line"
}

launch_detached_pid() {
  local pidf="$1" logf="$2"
  shift 2
  ( setsid -f bash -c 'echo $$ > "$1"; shift; exec "$@"' _ "$pidf" "$@" < /dev/null >> "$logf" 2>&1 & )
}

port_listening() {
  local port="$1"
  ss -tln 2>/dev/null | awk '{print $4}' | grep -qE "(127\.0\.0\.1|\*|::1|0\.0\.0\.0):${port}$"
}

# 防 60564 陷阱：檢查 11090 係咪俾錯誤嘅 ssh -L 霸住（SERVER_DIRECT 嚴禁用 -L，必須用 -D）
kill_rogue_11090_local_forward() {
  local port="$1"
  local bad_pids
  bad_pids="$(ps -eo pid=,comm=,args= 2>/dev/null | awk -v port="$port" '$2 ~ /^(ssh|python3)$/ && $0 ~ ("-L[[:space:]]*(127\\.0\\.0\\.1:)?" port ":") {print $1}' || true)"
  if [ -n "$bad_pids" ]; then
    for bp in $bad_pids; do
      log_msg "🚨 [60564-TRAP-FIX] 偵測到 port=${port} 誤用 ssh -L (pid=$bp)，即刻 kill 並改用 ssh -D"
      kill -9 "$bp" 2>/dev/null || true
    done
    sleep 0.3
  fi
}

kill_port_tunnel() {
  local port="$1"
  local pidf="$ARENA_HOME/run/vpn-tunnel-${port}.pid"
  if [ -f "$pidf" ]; then
    local p
    p="$(cat "$pidf" 2>/dev/null || true)"
    if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then
      kill "$p" 2>/dev/null || true
      sleep 0.2
      kill -9 "$p" 2>/dev/null || true
    fi
    rm -f "$pidf"
  fi
  local stray
  stray="$(ps -eo pid=,comm=,args= 2>/dev/null | awk -v port="$port" '$2 ~ /^(ssh|python3)$/ && ($0 ~ ("-L[[:space:]]*(127\\.0\\.0\\.1:)?" port ":") || $0 ~ ("-D[[:space:]]*(127\\.0\\.0\\.1:)?" port "($|[[:space:]])")) {print $1}' || true)"
  for sp in $stray; do
    kill "$sp" 2>/dev/null || true
    sleep 0.1
    kill -9 "$sp" 2>/dev/null || true
  done
}

read_conf_entries() {
  [ -f "$CONF" ] || { log_msg "❌ 找不到 vpn-proxies.conf ($CONF)"; return 1; }
  awk '!/^[[:space:]]*#/ && NF>=2 {print $1, $2, ($3 ? $3 : "-"), ($4 ? $4 : "-")}' "$CONF"
}

ensure_one_tunnel() {
  local name="$1" port="$2" expected_ip="$3" desc="$4"
  local pidf="$ARENA_HOME/run/vpn-tunnel-${port}.pid"
  local is_direct=0
  if [ "$name" = "SERVER_DIRECT" ] || [ "$port" = "11090" ]; then
    is_direct=1
    kill_rogue_11090_local_forward "$port"
  fi

  if port_listening "$port"; then
    return 0
  fi

  if [ -f "$pidf" ]; then
    local oldp
    oldp="$(cat "$pidf" 2>/dev/null || true)"
    [ -n "$oldp" ] && kill "$oldp" 2>/dev/null || true
    rm -f "$pidf"
  fi

  if [ "$is_direct" -eq 1 ]; then
    log_msg "PULL-UP $name port=$port mode=ssh_-D (expected_exit=$expected_ip, 嚴禁 -L)"
    launch_detached_pid "$pidf" "$LOG" bash "$SSH_WRAPPER" \
      -o ExitOnForwardFailure=yes -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o TCPKeepAlive=yes \
      -N -D "127.0.0.1:${port}"
  else
    log_msg "PULL-UP $name port=$port mode=ssh_-L (expected_exit=$expected_ip)"
    launch_detached_pid "$pidf" "$LOG" bash "$SSH_WRAPPER" \
      -o ExitOnForwardFailure=yes -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o TCPKeepAlive=yes \
      -N -L "127.0.0.1:${port}:127.0.0.1:${port}"
  fi

  local i=0
  while [ "$i" -lt 15 ]; do
    if port_listening "$port"; then
      local new_pid
      new_pid="$(cat "$pidf" 2>/dev/null || echo "?")"
      if [ "$is_direct" -eq 1 ]; then
        log_msg "RESTART_OK $name port=$port mode=ssh_-D pid=$new_pid listen=127.0.0.1:$port"
      else
        log_msg "RESTART_OK $name port=$port mode=ssh_-L pid=$new_pid listen=127.0.0.1:$port"
      fi
      return 0
    fi
    sleep 0.2
    i=$((i + 1))
  done

  log_msg "❌ RESTART_FAIL $name port=$port — 3 秒內未見 127.0.0.1:$port LISTEN（請查 $LOG 及 $SSH_WRAPPER）"
  return 1
}

cmd_ensure() {
  local fail=0 total=0
  while read -r name port expected_ip desc; do
    [ -n "${name:-}" ] || continue
    total=$((total + 1))
    ensure_one_tunnel "$name" "$port" "$expected_ip" "$desc" || fail=$((fail + 1))
  done < <(read_conf_entries)
  if [ "$total" -lt 8 ]; then
    log_msg "⚠️ vpn-proxies.conf 條目數 ($total) 少於標準 8 條（11080–11086 + 11090）"
    return 1
  fi
  return $([ "$fail" -eq 0 ] && echo 0 || echo 1)
}

cmd_status() {
  local ok=0 miss=0
  while read -r name port expected_ip desc; do
    [ -n "${name:-}" ] || continue
    local mode="ssh -L (WG)"
    if [ "$name" = "SERVER_DIRECT" ] || [ "$port" = "11090" ]; then
      mode="ssh -D (SERVER_DIRECT)"
    fi
    if port_listening "$port"; then
      echo "✅ $name | 127.0.0.1:$port | $mode | expected=$expected_ip ($desc) | LISTEN"
      ok=$((ok + 1))
    else
      echo "❌ $name | 127.0.0.1:$port | $mode | expected=$expected_ip ($desc) | DOWN"
      miss=$((miss + 1))
    fi
  done < <(read_conf_entries)
  echo "=== TUNNEL STATUS: $ok UP / $miss DOWN ==="
  return $([ "$miss" -eq 0 ] && [ "$ok" -ge 8 ] && echo 0 || echo 1)
}

cmd_stop() {
  while read -r name port expected_ip desc; do
    [ -n "${name:-}" ] || continue
    kill_port_tunnel "$port"
    log_msg "STOPPED $name port=$port"
  done < <(read_conf_entries)
}

cmd_test() {
  cmd_status || return 1
  local fail=0
  while read -r name port expected_ip desc; do
    [ -n "${name:-}" ] || continue
    if [ "$expected_ip" != "-" ]; then
      local got_ip
      got_ip="$(curl -fsS --socks5-hostname "127.0.0.1:${port}" --max-time 8 https://api.ipify.org 2>/dev/null || true)"
      if [ "$got_ip" = "$expected_ip" ]; then
        echo "✅ EXIT_IP_OK $name (127.0.0.1:$port) -> $got_ip"
      else
        echo "❌ EXIT_IP_MISMATCH $name (127.0.0.1:$port) -> got='${got_ip:-NONE}' expected='$expected_ip'"
        fail=$((fail + 1))
      fi
    fi
  done < <(read_conf_entries)
  return $([ "$fail" -eq 0 ] && echo 0 || echo 1)
}

ACTION="${1:-ensure}"
case "$ACTION" in
  ensure|start|watchdog)
    cmd_ensure
    ;;
  status)
    cmd_status
    ;;
  stop)
    cmd_stop
    ;;
  restart)
    cmd_stop
    sleep 0.5
    cmd_ensure
    ;;
  test)
    cmd_test
    ;;
  *)
    echo "Usage: $0 {ensure|start|status|stop|restart|test}" >&2
    exit 2
    ;;
esac
