#!/bin/bash
# Setup SSH tunnel for Proxmox API access
# This allows list_vms.py to work from different network segments

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_PORT="${PROXMOX_PORT:-8006}"
SSH_USER="${SSH_USER:-root}"
LOCAL_PORT="${LOCAL_PORT:-8006}"
TUNNEL_PID_FILE="/tmp/proxmox-tunnel-${PROXMOX_HOST}-${PROXMOX_PORT}.pid"

# Load from .env if available
if [ -f ~/.env ]; then
    export $(grep -E "^PROXMOX_" ~/.env | grep -v "^#" | xargs)
    PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
    PROXMOX_PORT="${PROXMOX_PORT:-8006}"
fi

echo "═══════════════════════════════════════════════════════════"
echo "  Proxmox SSH Tunnel Setup"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "Configuration:"
echo "  Proxmox Host: $PROXMOX_HOST"
echo "  Proxmox Port: $PROXMOX_PORT"
echo "  SSH User: $SSH_USER"
echo "  Local Port: $LOCAL_PORT"
echo ""

# Check if tunnel already exists
if [ -f "$TUNNEL_PID_FILE" ]; then
    OLD_PID=$(cat "$TUNNEL_PID_FILE")
    if ps -p "$OLD_PID" > /dev/null 2>&1; then
        echo "⚠️  Tunnel already running (PID: $OLD_PID)"
        echo "   Use: ./stop_ssh_tunnel.sh to stop it"
        exit 1
    else
        rm -f "$TUNNEL_PID_FILE"
    fi
fi

# Test SSH connection
echo "Testing SSH connection to $SSH_USER@$PROXMOX_HOST..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$SSH_USER@$PROXMOX_HOST" "echo 'SSH OK'" 2>/dev/null; then
    echo "❌ SSH connection failed"
    echo ""
    echo "Troubleshooting:"
    echo "  1. Check if host is reachable: ping $PROXMOX_HOST"
    echo "  2. Verify SSH access is configured"
    echo "  3. Check if you're on the correct network/VPN"
    echo ""
    echo "Alternative: Use Cloudflare tunnel for web access:"
    case "$PROXMOX_HOST" in
        192.168.11.10)
            echo "  https://ml110-01.d-bis.org"
            ;;
        192.168.11.11)
            echo "  https://r630-01.d-bis.org"
            ;;
        192.168.11.12)
            echo "  https://r630-02.d-bis.org"
            ;;
    esac
    exit 1
fi

echo "✅ SSH connection successful"
echo ""

# Create tunnel
echo "Creating SSH tunnel..."
echo "  Local: localhost:$LOCAL_PORT"
echo "  Remote: $PROXMOX_HOST:$PROXMOX_PORT"
echo ""

ssh -N -L ${LOCAL_PORT}:${PROXMOX_HOST}:${PROXMOX_PORT} \
    -o StrictHostKeyChecking=no \
    -o ServerAliveInterval=60 \
    -o ServerAliveCountMax=3 \
    "$SSH_USER@$PROXMOX_HOST" &
    
TUNNEL_PID=$!
echo $TUNNEL_PID > "$TUNNEL_PID_FILE"

# Wait a moment for tunnel to establish
sleep 2

# Verify tunnel is running
if ps -p "$TUNNEL_PID" > /dev/null 2>&1; then
    echo "✅ Tunnel established (PID: $TUNNEL_PID)"
    echo ""
    echo "═══════════════════════════════════════════════════════════"
    echo "  Tunnel Active"
    echo "═══════════════════════════════════════════════════════════"
    echo ""
    echo "You can now use:"
    echo "  PROXMOX_HOST=localhost python3 list_vms.py"
    echo ""
    echo "Or set in environment:"
    echo "  export PROXMOX_HOST=localhost"
    echo "  python3 list_vms.py"
    echo ""
    echo "To stop the tunnel:"
    echo "  ./stop_ssh_tunnel.sh"
    echo "  # or"
    echo "  kill $TUNNEL_PID"
    echo ""
    echo "Tunnel will run in background. Press Ctrl+C to stop monitoring."
    echo ""
    
    # Keep script running to maintain tunnel
    trap "kill $TUNNEL_PID 2>/dev/null; rm -f $TUNNEL_PID_FILE; exit" INT TERM
    wait $TUNNEL_PID
else
    echo "❌ Failed to establish tunnel"
    rm -f "$TUNNEL_PID_FILE"
    exit 1
fi
