#!/bin/bash

# Remote fix for explorer.d-bis.org
# This script uses SSH to deploy the fix to VMID 5000
# Can work from any machine with SSH access to Proxmox host or VMID 5000

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_NODE="${PROXMOX_NODE:-r630-2}"
VMID_5000="${VMID_5000:-5000}"
VM_IP="${VM_IP:-192.168.11.140}"
FRONTEND_SOURCE="/home/intlc/projects/proxmox/explorer-monorepo/frontend/public/index.html"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

echo "=========================================="
echo "Remote Explorer Fix"
echo "=========================================="
echo "Proxmox Host: $PROXMOX_HOST"
echo "Proxmox Node: $PROXMOX_NODE"
echo "VMID: $VMID_5000"
echo "VM IP: $VM_IP"
echo "Frontend Source: $FRONTEND_SOURCE"
echo "=========================================="
echo ""

# Step 1: Verify frontend file exists
echo "=== Step 1: Verifying frontend file ==="
if [ ! -f "$FRONTEND_SOURCE" ]; then
    echo "❌ Frontend file not found: $FRONTEND_SOURCE"
    exit 1
fi
echo "✅ Frontend file found"
echo ""

# Step 2: Try direct SSH to VMID 5000, node, or Proxmox host
echo "=== Step 2: Attempting SSH access ==="
if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@"$VM_IP" "echo test" 2>/dev/null; then
    echo "✅ Direct SSH access to VMID 5000 available"
    DEPLOY_METHOD="direct_ssh"
elif ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@"$PROXMOX_NODE" "echo test" 2>/dev/null; then
    echo "✅ Direct SSH access to Proxmox node $PROXMOX_NODE available"
    DEPLOY_METHOD="node_ssh"
elif ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "echo test" 2>/dev/null; then
    echo "✅ SSH access to Proxmox host available"
    DEPLOY_METHOD="proxmox_ssh"
else
    echo "❌ Cannot access Proxmox host, node, or VMID 5000 via SSH"
    echo ""
    echo "Please ensure SSH access is configured:"
    echo "  - To Proxmox node: ssh root@$PROXMOX_NODE"
    echo "  - To Proxmox host: ssh root@$PROXMOX_HOST"
    echo "  - To VMID 5000: ssh root@$VM_IP"
    exit 1
fi
echo ""

# Step 3: Deploy based on method
if [ "$DEPLOY_METHOD" = "node_ssh" ]; then
    echo "=== Step 3: Deploying directly to Proxmox node $PROXMOX_NODE ==="
    
    # Copy frontend file to node
    echo "Copying frontend file to node..."
    scp -o StrictHostKeyChecking=no "$FRONTEND_SOURCE" root@"$PROXMOX_NODE":/tmp/index.html
    
    # Deploy using pct on the node
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_NODE" bash << DEPLOY_SCRIPT_EOF
set +e

echo "Checking container VMID $VMID_5000..."
if ! pct list | grep -q "^$VMID_5000 "; then
    echo "❌ Container VMID $VMID_5000 not found on this node"
    exit 1
fi

# Check if container is running
CONTAINER_STATUS=\$(pct status $VMID_5000 2>/dev/null | awk '{print \$2}' || echo "stopped")

if [ "\$CONTAINER_STATUS" != "running" ]; then
    echo "⚠️  Container VMID $VMID_5000 is not running (\$CONTAINER_STATUS), starting..."
    pct start $VMID_5000
    sleep 5
    echo "✅ Container started"
else
    echo "✅ Container is already running"
fi

# Deploy frontend
echo "Deploying frontend..."
pct push $VMID_5000 /tmp/index.html /var/www/html/index.html
pct exec $VMID_5000 -- chown www-data:www-data /var/www/html/index.html

# Update nginx config
echo "Updating nginx configuration..."
pct exec $VMID_5000 -- bash -c 'cp /etc/nginx/sites-available/blockscout /etc/nginx/sites-available/blockscout.backup.\$(date +%Y%m%d_%H%M%S) 2>/dev/null || true'
pct exec $VMID_5000 -- bash -c 'grep -q "location = / {" /etc/nginx/sites-available/blockscout || sed -i "/server_name.*explorer.d-bis.org/a\\    # Serve custom frontend for root path\\    location = / {\\        root /var/www/html;\\        try_files /index.html =404;\\    }" /etc/nginx/sites-available/blockscout'
pct exec $VMID_5000 -- systemctl reload nginx 2>/dev/null || pct exec $VMID_5000 -- systemctl restart nginx 2>/dev/null || true

echo "✅ Deployment complete"
DEPLOY_SCRIPT_EOF

elif [ "$DEPLOY_METHOD" = "direct_ssh" ]; then
    echo "=== Step 3: Deploying directly to VMID 5000 ==="
    
    # Copy frontend file
    echo "Copying frontend file..."
    scp -o StrictHostKeyChecking=no "$FRONTEND_SOURCE" root@"$VM_IP":/tmp/index.html
    
    # Deploy and configure
    ssh -o StrictHostKeyChecking=no root@"$VM_IP" << 'DEPLOY_SCRIPT'
set +e
mkdir -p /var/www/html
cp /tmp/index.html /var/www/html/index.html
chown www-data:www-data /var/www/html/index.html

# Update nginx config if needed
NGINX_CONFIG="/etc/nginx/sites-available/blockscout"
if [ -f "$NGINX_CONFIG" ]; then
    # Backup
    cp "$NGINX_CONFIG" "${NGINX_CONFIG}.backup.$(date +%Y%m%d_%H%M%S)" 2>/dev/null || true
    
    # Check if already configured
    if ! grep -q "location = / {" "$NGINX_CONFIG"; then
        # Add location block for root path
        sed -i '/server_name.*explorer.d-bis.org/a\
    # Serve custom frontend for root path\
    location = / {\
        root /var/www/html;\
        try_files /index.html =404;\
    }' "$NGINX_CONFIG"
    fi
fi

# Ensure nginx is running
systemctl start nginx 2>/dev/null || true
systemctl reload nginx 2>/dev/null || true

echo "✅ Deployment complete on VMID 5000"
DEPLOY_SCRIPT

elif [ "$DEPLOY_METHOD" = "proxmox_ssh" ]; then
    echo "=== Step 3: Deploying via Proxmox host ==="
    
    # Copy frontend file to Proxmox host first
    echo "Copying frontend file to Proxmox host..."
    scp -o StrictHostKeyChecking=no "$FRONTEND_SOURCE" root@"$PROXMOX_HOST":/tmp/index.html
    
    # Deploy using pct on correct node
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" bash << DEPLOY_SCRIPT_EOF
set +e

# Get node name from cluster - pvecm nodes outputs: Nodeid Votes Name
NODE_NAME=\$(pvecm nodes | grep -v "^Nodeid\|^-\|^Membership" | grep -i "$PROXMOX_NODE" | awk '{print \$3}' | head -1)
if [ -z "\$NODE_NAME" ]; then
    # Try using the node name directly
    NODE_NAME="$PROXMOX_NODE"
fi

echo "Using node: \$NODE_NAME"
NODE_IP=\$NODE_NAME

# Check if container exists on the correct node - try multiple ways
CONTAINER_FOUND=false
if [ "\$NODE_IP" = "localhost" ] || [ "\$NODE_IP" = "$PROXMOX_HOST" ]; then
    # On local node
    if pct list | grep -q "^$VMID_5000 "; then
        CONTAINER_FOUND=true
        NODE_TARGET=""
    fi
elif ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@\$NODE_IP "pct list | grep -q '^$VMID_5000 '" 2>/dev/null; then
    echo "✅ Container found on node $PROXMOX_NODE"
    CONTAINER_FOUND=true
    NODE_TARGET="root@\$NODE_IP"
fi

if [ "\$CONTAINER_FOUND" = false ]; then
    echo "❌ Container VMID $VMID_5000 not found on node $PROXMOX_NODE (\$NODE_NAME)"
    echo "Checking all nodes..."
    pvecm nodes | grep -v "^Nodeid\|^-\|^Membership" | while read line; do
        CHECK_NODE=\$(echo \$line | awk '{print \$3}')
        if [ -n "\$CHECK_NODE" ] && [ "\$CHECK_NODE" != "Name" ]; then
            echo "  Checking node: \$CHECK_NODE"
            if ssh -o ConnectTimeout=3 -o StrictHostKeyChecking=no root@\$CHECK_NODE "pct list | grep -q '^$VMID_5000 '" 2>/dev/null; then
                echo "  ✅ Found on node: \$CHECK_NODE"
                NODE_NAME=\$CHECK_NODE
                NODE_IP=\$CHECK_NODE
                CONTAINER_FOUND=true
                NODE_TARGET="root@\$NODE_IP"
                break
            fi
        fi
    done
fi

if [ "\$CONTAINER_FOUND" = false ]; then
    echo "❌ Container VMID $VMID_5000 not found on any node"
    exit 1
fi

echo "✅ Container found on node: \$NODE_IP"

# Determine command prefix
if [ -z "\$NODE_TARGET" ]; then
    PCT_CMD="pct"
    SCP_CMD=""
else
    PCT_CMD="ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no \$NODE_TARGET pct"
    SCP_CMD="scp -o ConnectTimeout=5 -o StrictHostKeyChecking=no"
fi

# Check if container is running
CONTAINER_STATUS=\$(\$PCT_CMD status $VMID_5000 2>/dev/null | awk '{print \$2}' || echo "stopped")

if [ "\$CONTAINER_STATUS" != "running" ]; then
    echo "⚠️  Container VMID $VMID_5000 is not running (\$CONTAINER_STATUS), starting..."
    \$PCT_CMD start $VMID_5000
    sleep 5
    echo "✅ Container started"
else
    echo "✅ Container is already running"
fi

# Copy frontend file to the node if needed
if [ -n "\$SCP_CMD" ]; then
    echo "Copying frontend file to node..."
    \$SCP_CMD /tmp/index.html \$NODE_TARGET:/tmp/index.html
fi

# Deploy frontend using pct
echo "Deploying frontend to container..."
\$PCT_CMD push $VMID_5000 /tmp/index.html /var/www/html/index.html
\$PCT_CMD exec $VMID_5000 -- chown www-data:www-data /var/www/html/index.html

# Update nginx config
echo "Updating nginx configuration..."
\$PCT_CMD exec $VMID_5000 -- bash -c 'cp /etc/nginx/sites-available/blockscout /etc/nginx/sites-available/blockscout.backup.\$(date +%Y%m%d_%H%M%S) 2>/dev/null || true'
\$PCT_CMD exec $VMID_5000 -- bash -c 'grep -q "location = / {" /etc/nginx/sites-available/blockscout || sed -i "/server_name.*explorer.d-bis.org/a\\    # Serve custom frontend for root path\\    location = / {\\        root /var/www/html;\\        try_files /index.html =404;\\    }" /etc/nginx/sites-available/blockscout'
\$PCT_CMD exec $VMID_5000 -- systemctl reload nginx 2>/dev/null || \$PCT_CMD exec $VMID_5000 -- systemctl restart nginx 2>/dev/null || true

echo "✅ Deployment complete via node: \$NODE_IP"
DEPLOY_SCRIPT_EOF
fi

# Step 4: Verify deployment
echo ""
echo "=== Step 4: Verifying deployment ==="
sleep 2

if [ "$DEPLOY_METHOD" = "node_ssh" ]; then
    # Check file
    if ssh -o StrictHostKeyChecking=no root@"$PROXMOX_NODE" "pct exec $VMID_5000 -- test -f /var/www/html/index.html"; then
        echo "✅ Frontend file deployed"
    else
        echo "❌ Frontend file not found"
    fi
    
    # Test HTTP
    HTTP_TEST=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_NODE" "pct exec $VMID_5000 -- curl -s -o /dev/null -w '%{http_code}' http://localhost/ 2>/dev/null || echo '000'")
    if [ "$HTTP_TEST" = "200" ]; then
        echo "✅ HTTP endpoint responding (200)"
    else
        echo "⚠️  HTTP endpoint returned: $HTTP_TEST"
    fi

elif [ "$DEPLOY_METHOD" = "direct_ssh" ]; then
    # Check file
    if ssh -o StrictHostKeyChecking=no root@"$VM_IP" "test -f /var/www/html/index.html"; then
        echo "✅ Frontend file deployed"
    else
        echo "❌ Frontend file not found"
    fi
    
    # Test HTTP
    HTTP_TEST=$(ssh -o StrictHostKeyChecking=no root@"$VM_IP" "curl -s -o /dev/null -w '%{http_code}' http://localhost/ 2>/dev/null || echo '000'")
    if [ "$HTTP_TEST" = "200" ]; then
        echo "✅ HTTP endpoint responding (200)"
    else
        echo "⚠️  HTTP endpoint returned: $HTTP_TEST"
    fi

elif [ "$DEPLOY_METHOD" = "proxmox_ssh" ]; then
    # Check file
    if ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "ssh -o ConnectTimeout=5 root@$PROXMOX_NODE 'pct exec $VMID_5000 -- test -f /var/www/html/index.html'"; then
        echo "✅ Frontend file deployed"
    else
        echo "❌ Frontend file not found"
    fi
    
    # Test HTTP
    HTTP_TEST=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "ssh -o ConnectTimeout=5 root@$PROXMOX_NODE 'pct exec $VMID_5000 -- curl -s -o /dev/null -w \"%{http_code}\" http://localhost/ 2>/dev/null || echo \"000\"'")
    if [ "$HTTP_TEST" = "200" ]; then
        echo "✅ HTTP endpoint responding (200)"
    else
        echo "⚠️  HTTP endpoint returned: $HTTP_TEST"
    fi
fi

# Step 5: Test external access
echo ""
echo "=== Step 5: Testing external access ==="
sleep 3
EXTERNAL_TEST=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 10 "https://explorer.d-bis.org" 2>/dev/null || echo "000")
if [ "$EXTERNAL_TEST" = "200" ] || [ "$EXTERNAL_TEST" = "301" ] || [ "$EXTERNAL_TEST" = "302" ]; then
    echo "✅ External access working (HTTP $EXTERNAL_TEST)"
    echo "✅ Explorer is FIXED!"
else
    echo "⚠️  External access returned: $EXTERNAL_TEST"
    echo "   This may be due to Cloudflare tunnel or DNS configuration"
fi

echo ""
echo "=========================================="
echo "Fix Complete"
echo "=========================================="
echo ""
echo "Summary:"
echo "- Frontend deployed to /var/www/html/index.html"
echo "- Nginx configuration updated"
echo "- Services verified"
echo ""
echo "Test the explorer:"
echo "  curl -I https://explorer.d-bis.org"
echo "  Or visit in browser: https://explorer.d-bis.org"
echo ""
