#!/bin/bash

# ============================================
# Script to start Snowflake RG Barry proxy
# ============================================

# Check if running with sudo
if [ "$EUID" -eq 0 ]; then
    echo "⚠️  This script should NOT be run with sudo"
    echo "   Run directly: ./start-proxy.sh"
    echo "   Or with bash: bash start-proxy.sh"
    exit 1
fi

echo "🚀 Starting proxy for Snowflake RG Barry..."
echo ""

# Check if hpts is installed
if ! command -v hpts &> /dev/null; then
    echo "❌ Error: hpts is not installed or not in PATH."
    echo ""
    echo "   Options:"
    echo "   1. Install it with: npm install -g http-proxy-to-socks"
    echo "   2. If already installed, check your PATH"
    echo "   3. DO NOT use 'sudo' to run this script"
    echo ""
    echo "   Run the script like this:"
    echo "   ./start-proxy.sh    (recommended)"
    echo "   bash start-proxy.sh (alternative)"
    exit 1
fi

# Check if gcloud is installed
if ! command -v gcloud &> /dev/null; then
    echo "❌ Error: gcloud CLI is not installed."
    echo "   Download from: https://cloud.google.com/sdk/docs/install"
    exit 1
fi

# Check if port 8080 is in use
if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "⚠️  Warning: Port 8080 is already in use."
    echo "   Do you want to continue anyway? (y/n)"
    read -r response
    if [[ ! "$response" =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo "📡 Starting HTTP-to-SOCKS proxy on 127.0.0.1:8080..."
hpts -s 127.0.0.1:5001 -p 8080 &
HPTS_PID=$!

echo "✅ HPTS started (PID: $HPTS_PID)"
echo ""

# Wait 2 seconds for HPTS to start
sleep 2

echo "🔐 Starting SSH tunnel to GCP..."
echo "   (This will keep the terminal busy. Press Ctrl+C to stop both services)"
echo ""

# Cleanup function
cleanup() {
    echo ""
    echo "🛑 Stopping services..."
    kill $HPTS_PID 2>/dev/null
    echo "✅ Proxy stopped successfully"
    exit 0
}

# Configure trap to handle Ctrl+C
trap cleanup SIGINT SIGTERM

# Start SSH tunnel (this blocks until Ctrl+C)
gcloud compute ssh william.beltran@suitex --ssh-flag="-D:5001" --ssh-flag="-N" --ssh-flag="-n"

# If SSH tunnel fails, cleanup
cleanup

