#!/usr/bin/env bash
# Configure Nginx for Core RPC Node (VMID 2500)
# This configures Nginx as a reverse proxy for Besu RPC endpoints

set -e

VMID=2500
HOSTNAME="besu-rpc-1"
IP="192.168.11.250"
PROXMOX_HOST="192.168.11.10"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "Configuring Nginx for Core RPC Node (VMID $VMID)"
log_info "Hostname: $HOSTNAME"
log_info "IP: $IP"
echo ""

# Create Nginx configuration
sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'NGINX_CONFIG_EOF'
cat > /etc/nginx/sites-available/rpc-core <<'EOF'
# HTTP to HTTPS redirect
server {
    listen 80;
    listen [::]:80;
    server_name besu-rpc-1 192.168.11.250 rpc-core.besu.local rpc-core.chainid138.local;
    
    # Redirect all HTTP to HTTPS
    return 301 https://$host$request_uri;
}

# HTTPS server - HTTP RPC API (port 8545)
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name besu-rpc-1 192.168.11.250 rpc-core.besu.local rpc-core.chainid138.local;

    # SSL configuration
    ssl_certificate /etc/nginx/ssl/rpc.crt;
    ssl_certificate_key /etc/nginx/ssl/rpc.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # Security headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Logging
    access_log /var/log/nginx/rpc-core-http-access.log;
    error_log /var/log/nginx/rpc-core-http-error.log;

    # Increase timeouts for RPC calls
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    send_timeout 300s;
    client_max_body_size 10M;

    # HTTP RPC endpoint (port 8545)
    location / {
        proxy_pass http://127.0.0.1:8545;
        proxy_http_version 1.1;
        
        # Headers
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Connection "";
        
        # Buffer settings (disable for RPC)
        proxy_buffering off;
        proxy_request_buffering off;
        
        # CORS headers (if needed for web apps)
        add_header Access-Control-Allow-Origin * always;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;
        
        # Handle OPTIONS requests
        if ($request_method = OPTIONS) {
            return 204;
        }
    }

    # Health check endpoint
    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }

    # Metrics endpoint (if exposed)
    location /metrics {
        proxy_pass http://127.0.0.1:9545;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

# HTTPS server - WebSocket RPC API (port 8546)
server {
    listen 8443 ssl http2;
    listen [::]:8443 ssl http2;
    server_name besu-rpc-1 192.168.11.250 rpc-core-ws.besu.local rpc-core-ws.chainid138.local;

    # SSL configuration
    ssl_certificate /etc/nginx/ssl/rpc.crt;
    ssl_certificate_key /etc/nginx/ssl/rpc.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # Security headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # Logging
    access_log /var/log/nginx/rpc-core-ws-access.log;
    error_log /var/log/nginx/rpc-core-ws-error.log;

    # WebSocket RPC endpoint (port 8546)
    location / {
        proxy_pass http://127.0.0.1:8546;
        proxy_http_version 1.1;
        
        # WebSocket headers
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # Long timeouts for WebSocket connections
        proxy_read_timeout 86400;
        proxy_send_timeout 86400;
        proxy_connect_timeout 300s;
    }

    # Health check endpoint
    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }
}
EOF

# Enable the site
ln -sf /etc/nginx/sites-available/rpc-core /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Test configuration
nginx -t

# Reload Nginx
systemctl enable nginx
systemctl restart nginx
NGINX_CONFIG_EOF

if [ $? -eq 0 ]; then
    log_success "Nginx configuration created"
else
    log_error "Failed to create Nginx configuration"
    exit 1
fi

# Verify Nginx is running
log_info "Verifying Nginx status..."
if sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl is-active nginx >/dev/null 2>&1"; then
    log_success "Nginx service is active"
else
    log_error "Nginx service is not active"
    exit 1
fi

# Check if ports are listening
log_info "Checking listening ports..."
PORTS=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- ss -tlnp 2>&1 | grep -E ':80|:443|:8443' || echo ''")

if echo "$PORTS" | grep -q ':80'; then
    log_success "Port 80 is listening"
else
    log_warn "Port 80 may not be listening"
fi

if echo "$PORTS" | grep -q ':443'; then
    log_success "Port 443 is listening"
else
    log_warn "Port 443 may not be listening"
fi

if echo "$PORTS" | grep -q ':8443'; then
    log_success "Port 8443 is listening"
else
    log_warn "Port 8443 may not be listening"
fi

# Test RPC endpoint through Nginx
log_info "Testing RPC endpoint through Nginx..."
RPC_TEST=$(sshpass -p 'L@kers2010' ssh -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- timeout 5 curl -k -s -X POST https://localhost:443 \
    -H 'Content-Type: application/json' \
    -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}' 2>&1 || echo 'FAILED'")

if echo "$RPC_TEST" | grep -q "result"; then
    BLOCK_NUM=$(echo "$RPC_TEST" | grep -oP '"result":"\K[^"]+' | head -1)
    log_success "RPC endpoint is responding through Nginx!"
    log_info "Current block: $BLOCK_NUM"
else
    log_warn "RPC endpoint test failed or needs more time"
    log_info "Response: $RPC_TEST"
fi

echo ""
log_success "Nginx configuration complete!"
echo ""
log_info "Configuration Summary:"
log_info "  - HTTP RPC: https://$IP:443 (proxies to localhost:8545)"
log_info "  - WebSocket RPC: https://$IP:8443 (proxies to localhost:8546)"
log_info "  - HTTP redirect: http://$IP:80 → https://$IP:443"
log_info "  - Health check: https://$IP:443/health"
echo ""
log_info "Next steps:"
log_info "  1. Test from external: curl -k https://$IP:443/health"
log_info "  2. Test RPC: curl -k -X POST https://$IP:443 -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'"
log_info "  3. Replace self-signed certificate with Let's Encrypt if needed"
log_info "  4. Configure firewall rules if needed"

