#!/bin/bash

# Load environment variables
if [ -f .env ]; then
  set -a
  source .env
  set +a
fi

if [ -z "$VPS_HOST" ] || [ -z "$VPS_USER" ]; then
  echo "Error: VPS_HOST and VPS_USER must be set in .env"
  echo "Please add them to your .env file:"
  echo "VPS_USER=your-username"
  echo "VPS_HOST=your-ip-address"
  exit 1
fi

DASHBOARD_PORT=${DASHBOARD_PORT:-3000}
STUDIO_PORT=${STUDIO_PORT:-4983}

echo "🚀 Establishing secure tunnels to Aurora services..."
echo ""
echo "📊 Dashboard: http://localhost:$DASHBOARD_PORT"
echo "🔮 Studio:    http://localhost:$STUDIO_PORT (https://local.drizzle.studio)"
echo ""
echo "Press Ctrl+C to stop all connections."
echo ""

# Function to open browser (cross-platform)
open_browser() {
  sleep 2  # Wait for tunnel to establish
  if command -v open &> /dev/null; then
    # macOS
    open "http://localhost:$DASHBOARD_PORT"
  elif command -v xdg-open &> /dev/null; then
    # Linux
    xdg-open "http://localhost:$DASHBOARD_PORT"
  elif command -v start &> /dev/null; then
    # Windows (Git Bash)
    start "http://localhost:$DASHBOARD_PORT"
  fi
}

# Check if autossh is available for auto-reconnection
if command -v autossh &> /dev/null; then
  echo "✅ Using autossh for automatic reconnection"
  SSH_CMD="autossh -M 0 -o ServerAliveInterval=30 -o ServerAliveCountMax=3"
else
  echo "💡 Tip: Install autossh for automatic reconnection (brew install autossh)"
  SSH_CMD="ssh -o ServerAliveInterval=30 -o ServerAliveCountMax=3"
fi

# Open browser in background
open_browser &

# Start both tunnels
# -N means "Do not execute a remote command". -L is for local port forwarding.
$SSH_CMD -N \
  -L $DASHBOARD_PORT:127.0.0.1:$DASHBOARD_PORT \
  -L $STUDIO_PORT:127.0.0.1:$STUDIO_PORT \
  $VPS_USER@$VPS_HOST
