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

set -e
TELEGRAM_SOCKS_PORT="${TELEGRAM_SOCKS_PORT:-1081}"
SSH_HOST="${TELEGRAM_TUNNEL_HOST:-ahau@149.154.64.19}"

start() {
  if lsof -i :"$TELEGRAM_SOCKS_PORT" -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "SOCKS already listening on 127.0.0.1:$TELEGRAM_SOCKS_PORT"
    return 0
  fi
  ssh -D "$TELEGRAM_SOCKS_PORT" -f -N \
    -o ServerAliveInterval=30 \
    -o ServerAliveCountMax=6 \
    "$SSH_HOST"
  echo "SOCKS tunnel started: 127.0.0.1:$TELEGRAM_SOCKS_PORT -> $SSH_HOST"
}

stop() {
  pkill -f "ssh.*-D $TELEGRAM_SOCKS_PORT.*$SSH_HOST" 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_SOCKS_PORT, TELEGRAM_TUNNEL_HOST=$SSH_HOST"
    exit 1
    ;;
esac
