#!/bin/bash
# Fix all Cloudflare tunnels - restart services and verify

set -e

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.12}"
VMID="${VMID:-102}"

echo "═══════════════════════════════════════════════════════════"
echo "  Fix All Cloudflare Tunnels"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "Target: VMID ${VMID} on ${PROXMOX_HOST}"
echo ""

# Test connection
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "pct exec ${VMID} -- echo 'Connected'" 2>/dev/null; then
    echo "❌ Cannot connect to VMID ${VMID} on ${PROXMOX_HOST}"
    echo ""
    echo "Use SSH tunnel:"
    echo "  ./setup_ssh_tunnel.sh"
    echo "  PROXMOX_HOST=localhost ./fix-all-tunnels.sh"
    exit 1
fi

echo "✅ Connected to container"
echo ""

# Step 1: Ensure container is running
echo "Step 1: Checking container status..."
CONTAINER_STATUS=$(ssh root@${PROXMOX_HOST} "pct status ${VMID}" 2>/dev/null || echo "stopped")
if [[ "$CONTAINER_STATUS" != *"running"* ]]; then
    echo "⚠️  Container is not running. Starting..."
    ssh root@${PROXMOX_HOST} "pct start ${VMID}"
    sleep 5
    echo "✅ Container started"
else
    echo "✅ Container is running"
fi
echo ""

# Step 2: Check cloudflared installation
echo "Step 2: Checking cloudflared installation..."
if ! ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- which cloudflared" >/dev/null 2>&1; then
    echo "⚠️  cloudflared not installed. Installing..."
    ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash -c 'apt update && apt install -y cloudflared'" || {
        echo "❌ Failed to install cloudflared"
        exit 1
    }
    echo "✅ cloudflared installed"
else
    echo "✅ cloudflared is installed"
fi
echo ""

# Step 3: Fix credential permissions
echo "Step 3: Fixing credential file permissions..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash -c 'chmod 600 /etc/cloudflared/credentials-*.json 2>/dev/null || true'"
echo "✅ Permissions fixed"
echo ""

# Step 4: Enable all services
echo "Step 4: Enabling tunnel services..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl daemon-reload"
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash -c 'systemctl enable cloudflared-* 2>/dev/null || true'"
echo "✅ Services enabled"
echo ""

# Step 5: Restart all services
echo "Step 5: Restarting all tunnel services..."
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- bash -c 'systemctl restart cloudflared-* 2>/dev/null || systemctl start cloudflared-*'"
sleep 5
echo "✅ Services restarted"
echo ""

# Step 6: Check status
echo "Step 6: Checking service status..."
echo ""
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- systemctl status cloudflared-* --no-pager -l" || true
echo ""

# Step 7: Show recent logs
echo "Step 7: Recent logs (last 10 lines per service)..."
echo ""
ssh root@${PROXMOX_HOST} "pct exec ${VMID} -- journalctl -u cloudflared-* -n 10 --no-pager" || true
echo ""

echo "═══════════════════════════════════════════════════════════"
echo "  Fix Complete"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "Next steps:"
echo "  1. Wait 1-2 minutes for tunnels to connect"
echo "  2. Check Cloudflare Dashboard for tunnel status"
echo "  3. Verify services are accessible:"
echo "     curl -I https://ml110-01.d-bis.org"
echo "     curl -I https://r630-01.d-bis.org"
echo "     curl -I https://explorer.d-bis.org"
echo ""
echo "If tunnels are still DOWN:"
echo "  1. Check logs: ssh root@${PROXMOX_HOST} 'pct exec ${VMID} -- journalctl -u cloudflared-* -f'"
echo "  2. Verify credentials are valid"
echo "  3. Check network connectivity from container"
echo ""
