#!/bin/bash
# Stop SSH tunnel for Proxmox API access

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_PORT="${PROXMOX_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

if [ -f "$TUNNEL_PID_FILE" ]; then
    TUNNEL_PID=$(cat "$TUNNEL_PID_FILE")
    if ps -p "$TUNNEL_PID" > /dev/null 2>&1; then
        echo "Stopping tunnel (PID: $TUNNEL_PID)..."
        kill "$TUNNEL_PID" 2>/dev/null
        sleep 1
        if ps -p "$TUNNEL_PID" > /dev/null 2>&1; then
            echo "Force killing..."
            kill -9 "$TUNNEL_PID" 2>/dev/null
        fi
        rm -f "$TUNNEL_PID_FILE"
        echo "✅ Tunnel stopped"
    else
        echo "Tunnel not running (stale PID file)"
        rm -f "$TUNNEL_PID_FILE"
    fi
else
    echo "No tunnel PID file found"
    echo "Checking for running tunnels..."
    
    # Try to find tunnel by port
    LOCAL_PORT="${PROXMOX_PORT:-8006}"
    PIDS=$(lsof -ti:${LOCAL_PORT} 2>/dev/null)
    if [ -n "$PIDS" ]; then
        echo "Found processes on port $LOCAL_PORT: $PIDS"
        read -p "Kill these processes? (y/N) " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            echo "$PIDS" | xargs kill 2>/dev/null
            echo "✅ Processes killed"
        fi
    else
        echo "No tunnel processes found"
    fi
fi
