#!/usr/bin/env bash
# Поднимает SOCKS5-туннель для Cursor (обход PING timeout из РФ).
# Использование: ./cursor-socks-tunnel.sh [start|stop|status]
# См. docs/cursor/README.md

set -e
CURSOR_SOCKS_PORT="${CURSOR_SOCKS_PORT:-10809}"
SSH_HOST="${CURSOR_TUNNEL_HOST:-hsites-ahau}"

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

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

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

case "${1:-start}" in
  start) start ;;
  stop)  stop ;;
  status) status ;;
  *)
    echo "Usage: $0 {start|stop|status}"
    echo "Env: CURSOR_SOCKS_PORT=$CURSOR_SOCKS_PORT, CURSOR_TUNNEL_HOST=$SSH_HOST"
    exit 1
    ;;
esac
