#!/usr/bin/env bash
# Pre-flight check before running JWT authentication setup
# Verifies current state and identifies any issues

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID=2501

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info() { echo -e "${GREEN}[✓]${NC} $1"; }
warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
error() { echo -e "${RED}[✗]${NC} $1"; }
check() { echo -e "${BLUE}[?]${NC} $1"; }

echo "=========================================="
echo "Pre-Flight Check for JWT Setup"
echo "=========================================="
echo ""

ISSUES=0
WARNINGS=0

# Check 1: Container status
check "Checking VMID $VMID status..."
STATUS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct status $VMID 2>/dev/null | awk '{print \$2}'" 2>/dev/null || echo "unknown")

if [[ "$STATUS" == "running" ]]; then
    info "VMID $VMID is running"
else
    error "VMID $VMID is not running (status: $STATUS)"
    ISSUES=$((ISSUES + 1))
fi
echo ""

# Check 2: Nginx installation
check "Checking Nginx installation..."
NGINX_INSTALLED=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- command -v nginx >/dev/null 2>&1 && echo yes || echo no" 2>/dev/null || echo "no")

if [[ "$NGINX_INSTALLED" == "yes" ]]; then
    info "Nginx is installed"
else
    warn "Nginx is not installed (will be installed by script)"
    WARNINGS=$((WARNINGS + 1))
fi
echo ""

# Check 3: Existing Nginx config
check "Checking existing Nginx configuration..."
EXISTING_CONFIG=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- test -f /etc/nginx/sites-available/rpc && echo yes || echo no" 2>/dev/null || echo "no")

if [[ "$EXISTING_CONFIG" == "yes" ]]; then
    warn "Existing Nginx config found (/etc/nginx/sites-available/rpc)"
    check "Checking domain mappings in existing config..."
    DOMAINS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- grep -E 'server_name.*rpc-' /etc/nginx/sites-available/rpc 2>/dev/null | head -3" || echo "")
    
    if echo "$DOMAINS" | grep -q "rpc-http-pub\|rpc-ws-pub"; then
        warn "Existing config uses rpc-http-pub/rpc-ws-pub (should be on VMID 2502)"
        warn "Script will create new config 'rpc-perm' for rpc-http-prv/rpc-ws-prv"
        warn "Old config will be disabled but not deleted"
    fi
else
    info "No existing Nginx config found (clean setup)"
fi
echo ""

# Check 4: Besu configuration
check "Checking Besu configuration..."
BESU_CONFIG=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- test -f /etc/besu/config-rpc-perm.toml && echo yes || echo no" 2>/dev/null || echo "no")

if [[ "$BESU_CONFIG" == "yes" ]]; then
    info "Besu permissioned config exists (config-rpc-perm.toml)"
else
    error "Besu permissioned config not found (config-rpc-perm.toml)"
    ISSUES=$((ISSUES + 1))
fi
echo ""

# Check 5: SSL certificates
check "Checking SSL certificates..."
SSL_EXISTS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- test -f /etc/nginx/ssl/rpc.crt && echo yes || echo no" 2>/dev/null || echo "no")

if [[ "$SSL_EXISTS" == "yes" ]]; then
    info "SSL certificates exist"
else
    warn "SSL certificates not found (will be generated by script if needed)"
    WARNINGS=$((WARNINGS + 1))
fi
echo ""

# Check 6: JWT secret (should not exist yet)
check "Checking for existing JWT secret..."
JWT_EXISTS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- test -f /etc/nginx/jwt_secret && echo yes || echo no" 2>/dev/null || echo "no")

if [[ "$JWT_EXISTS" == "yes" ]]; then
    warn "JWT secret already exists (will be reused, not regenerated)"
    WARNINGS=$((WARNINGS + 1))
else
    info "No existing JWT secret (will be generated)"
fi
echo ""

# Check 7: Network connectivity
check "Checking network connectivity to Proxmox host..."
if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "echo test" >/dev/null 2>&1; then
    info "Can connect to Proxmox host ($PROXMOX_HOST)"
else
    error "Cannot connect to Proxmox host ($PROXMOX_HOST)"
    ISSUES=$((ISSUES + 1))
fi
echo ""

# Summary
echo "=========================================="
echo "Summary"
echo "=========================================="

if [ $ISSUES -eq 0 ] && [ $WARNINGS -eq 0 ]; then
    info "All checks passed! Ready to run configure-nginx-jwt-auth.sh"
    exit 0
elif [ $ISSUES -eq 0 ]; then
    warn "$WARNINGS warning(s) found, but setup can proceed"
    echo ""
    info "Ready to run configure-nginx-jwt-auth.sh"
    exit 0
else
    error "$ISSUES issue(s) found that must be resolved first"
    echo ""
    error "Please fix the issues above before running configure-nginx-jwt-auth.sh"
    exit 1
fi

