#!/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}

echo "🌐 Establishing secure tunnel to Aurora Dashboard..."
echo "📊 Dashboard will be accessible at: http://localhost:$DASHBOARD_PORT"
echo "Press Ctrl+C to stop the connection."
echo ""

# Function to open browser (cross-platform)
open_browser() {
  sleep 2
  if command -v open &> /dev/null; then
    open "http://localhost:$DASHBOARD_PORT"
  elif command -v xdg-open &> /dev/null; then
    xdg-open "http://localhost:$DASHBOARD_PORT"
  fi
}

# Check if autossh is available
if command -v autossh &> /dev/null; then
  SSH_CMD="autossh -M 0 -o ServerAliveInterval=30 -o ServerAliveCountMax=3"
else
  SSH_CMD="ssh -o ServerAliveInterval=30 -o ServerAliveCountMax=3"
fi

open_browser &
$SSH_CMD -N -L $DASHBOARD_PORT:127.0.0.1:$DASHBOARD_PORT $VPS_USER@$VPS_HOST
