#!/bin/bash
# Alternative fix script - to be run from within Proxmox network
# Or via SSH tunnel

set -e

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.12}"
VMID="${VMID:-102}"
TUNNEL_ID="10ab22da-8ea3-4e2e-a896-27ece2211a05"
NGINX_TARGET="192.168.11.21:80"

echo "═══════════════════════════════════════════════════════════"
echo "  Fix Shared Cloudflare Tunnel (Remote Method)"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "This script can be run:"
echo "  1. From a machine on 192.168.11.0/24 network"
echo "  2. Via SSH tunnel (after running setup_ssh_tunnel.sh)"
echo "  3. Directly on Proxmox host"
echo ""
echo "Tunnel ID: ${TUNNEL_ID}"
echo "Target: http://${NGINX_TARGET}"
echo "Container: VMID ${VMID} on ${PROXMOX_HOST}"
echo ""

# Check connection
echo "Testing connection..."
if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "pct exec ${VMID} -- echo 'Connected'" 2>/dev/null; then
    echo "✅ Connection successful"
    echo ""
    
    # Run the original fix script logic
    exec ./fix-shared-tunnel.sh
else
    echo "❌ Cannot connect"
    echo ""
    echo "If running via SSH tunnel, ensure:"
    echo "  1. SSH tunnel is active: ./setup_ssh_tunnel.sh"
    echo "  2. Use: PROXMOX_HOST=localhost ./fix-shared-tunnel-remote.sh"
    echo ""
    echo "If running from Proxmox network, ensure:"
    echo "  1. You're on 192.168.11.0/24 network"
    echo "  2. SSH access to ${PROXMOX_HOST} is configured"
    echo ""
    exit 1
fi
