#!/bin/bash

# =============================================================================
# Aurora Remote Tunnel Script
# =============================================================================
# Establishes secure SSH tunnels to remote Aurora services.
# Uses autossh for automatic reconnection if available.
#
# Usage: ./remote.sh
# =============================================================================

# Load environment variables safely
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/lib/load-env.sh"
load_env

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 ""

# 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

# 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
