#!/usr/bin/env bash
# SOCKS5-туннель для Telegram (и др. приложений) через прокси 149.154.64.19.
# Порт 1081 — отдельно от Cursor (10809). Использование: ./telegram-socks-tunnel.sh [start|stop|status]
# См. connectivity/PROXY_GUIDE.md (в т.ч. цепочка через DigitalOcean: TELEGRAM_SOCKS_VIA_DO=1)

set -e
TELEGRAM_SOCKS_PORT="${TELEGRAM_SOCKS_PORT:-1081}"
SSH_HOST="${TELEGRAM_TUNNEL_HOST:-ahau@149.154.64.19}"
TELEGRAM_SOCKS_VIA_DO="${TELEGRAM_SOCKS_VIA_DO:-0}"
TELEGRAM_SOCKS_JUMP_HOST="${TELEGRAM_SOCKS_JUMP_HOST:-hsites-ahau}"
TELEGRAM_SOCKS_FINAL_HOST="${TELEGRAM_SOCKS_FINAL_HOST:-hunab@209.38.32.21}"
TELEGRAM_SOCKS_FINAL_PORT="${TELEGRAM_SOCKS_FINAL_PORT:-2222}"
TELEGRAM_SOCKS_FINAL_IDENTITY="${TELEGRAM_SOCKS_FINAL_IDENTITY:-$HOME/.ssh/hunab_deploy_key}"
# Пусто = только loopback (по умолчанию в OpenSSH). 0.0.0.0 — слушать на всех интерфейсах (телефон → SOCKS на Mac по хотспоту).
TELEGRAM_SOCKS_BIND="${TELEGRAM_SOCKS_BIND:-}"
# SOCKS держит много соединений (Telegram); без повышения ulimit — «Too many open files».
TELEGRAM_SSH_STABLE_OPTS="-o TCPKeepAlive=yes -o IPQoS=throughput -o ServerAliveInterval=60 -o ServerAliveCountMax=4"

raise_fd_limit() {
  ulimit -n 65536 2>/dev/null || ulimit -n 10240 2>/dev/null || true
}

socks_listening() {
  lsof -i :"$TELEGRAM_SOCKS_PORT" -sTCP:LISTEN -t >/dev/null 2>&1
}

kill_listener_on_port() {
  # PIDs listening on TELEGRAM_SOCKS_PORT (usually ssh -D; LaunchAgent may respawn — loop a few times)
  local i=0
  while socks_listening && [ "$i" -lt 20 ]; do
    lsof -ti :"$TELEGRAM_SOCKS_PORT" -sTCP:LISTEN 2>/dev/null | xargs kill 2>/dev/null || true
    sleep 0.35
    i=$((i + 1))
  done
}

start() {
  if socks_listening; then
    if [ "$TELEGRAM_SOCKS_VIA_DO" = "1" ]; then
      echo "Port $TELEGRAM_SOCKS_PORT busy — replacing with via-DO tunnel..."
      kill_listener_on_port
      if socks_listening; then
        echo "Port $TELEGRAM_SOCKS_PORT still in use. If LaunchAgent keeps respawning the old tunnel, run:"
        echo "  launchctl unload \"\$HOME/Library/LaunchAgents/com.hunab.telegram-socks.plist\" 2>/dev/null"
        echo "  (or ./docs/connectivity/launchd/uninstall.sh) then: TELEGRAM_SOCKS_VIA_DO=1 $0 start"
        return 1
      fi
    else
      echo "SOCKS already listening on port $TELEGRAM_SOCKS_PORT"
      return 0
    fi
  fi
  raise_fd_limit
  local d_spec="$TELEGRAM_SOCKS_PORT"
  if [ -n "$TELEGRAM_SOCKS_BIND" ]; then
    d_spec="${TELEGRAM_SOCKS_BIND}:${TELEGRAM_SOCKS_PORT}"
  fi
  if [ "$TELEGRAM_SOCKS_VIA_DO" = "1" ]; then
    if ! ssh -o BatchMode=yes -o ConnectTimeout=6 -o ConnectionAttempts=1 hsites-ahau "exit 0" 2>/dev/null; then
      echo "Ошибка: hsites-ahau недоступен. TELEGRAM_SOCKS_VIA_DO=1 — только Mac→RU→DO; прямой Mac→DO для SOCKS отключён." >&2
      exit 1
    fi
    # shellcheck disable=SC2086
    ssh -D "$TELEGRAM_SOCKS_PORT" -f -N \
      $TELEGRAM_SSH_STABLE_OPTS \
      telegram-socks-via-do
    echo "SOCKS started: 127.0.0.1:$TELEGRAM_SOCKS_PORT -> hsites-ahau -> DO (telegram-socks-via-do)"
  else
    # shellcheck disable=SC2086
    ssh -D "$TELEGRAM_SOCKS_PORT" -f -N \
      $TELEGRAM_SSH_STABLE_OPTS \
      "$SSH_HOST"
    echo "SOCKS tunnel started: 127.0.0.1:$TELEGRAM_SOCKS_PORT -> $SSH_HOST"
  fi
}

stop() {
  pkill -f "ssh.*-D $TELEGRAM_SOCKS_PORT" 2>/dev/null || true
  echo "Tunnel stopped (if it was running)."
}

status() {
  if lsof -i :"$TELEGRAM_SOCKS_PORT" -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "SOCKS listening on 127.0.0.1:$TELEGRAM_SOCKS_PORT"
    lsof -i :"$TELEGRAM_SOCKS_PORT" -sTCP:LISTEN
  else
    echo "No SOCKS listener on port $TELEGRAM_SOCKS_PORT"
  fi
}

case "${1:-start}" in
  start) start ;;
  stop)  stop ;;
  status) status ;;
  *)
    echo "Usage: $0 {start|stop|status}"
    echo "Env: TELEGRAM_SOCKS_PORT, TELEGRAM_TUNNEL_HOST (default exit: ru proxy)"
    echo "     TELEGRAM_SOCKS_VIA_DO=1 — только Mac→RU→DO (telegram-socks-via-do); без прямого DO"
    exit 1
    ;;
esac
