#!/usr/bin/env bash
# Configure Nginx for Public RPC Endpoints on VMID 2500
# Adds public endpoints (rpc-http-pub.d-bis.org and rpc-ws-pub.d-bis.org) WITHOUT JWT authentication

set -euo pipefail

VMID=2500
IP="192.168.11.250"
PROXMOX_HOST="${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 Public RPC Endpoints on VMID $VMID"
log_info "Endpoints: rpc-http-pub.d-bis.org, rpc-ws-pub.d-bis.org"
log_info "NO JWT authentication will be required"
echo ""

# Check if container is running
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
    log_error "Container $VMID is not running (status: $STATUS)"
    exit 1
fi

# Create Nginx configuration for public endpoints
log_info "Creating Nginx configuration for public endpoints..."

ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" <<'NGINX_CONFIG_EOF'
cat > /etc/nginx/sites-available/rpc-public <<'EOF'
# Public HTTP RPC endpoint - NO authentication required
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name rpc-http-pub.d-bis.org;

    # SSL configuration (use Let's Encrypt certificate if available, otherwise fallback)
    ssl_certificate /etc/letsencrypt/live/rpc-core.d-bis.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/rpc-core.d-bis.org/privkey.pem;
    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;

    # Trust Cloudflare IPs for real IP
    set_real_ip_from 173.245.48.0/20;
    set_real_ip_from 103.21.244.0/22;
    set_real_ip_from 103.22.200.0/22;
    set_real_ip_from 103.31.4.0/22;
    set_real_ip_from 141.101.64.0/18;
    set_real_ip_from 108.162.192.0/18;
    set_real_ip_from 190.93.240.0/20;
    set_real_ip_from 188.114.96.0/20;
    set_real_ip_from 197.234.240.0/22;
    set_real_ip_from 198.41.128.0/17;
    set_real_ip_from 162.158.0.0/15;
    set_real_ip_from 104.16.0.0/13;
    set_real_ip_from 104.24.0.0/14;
    set_real_ip_from 172.64.0.0/13;
    set_real_ip_from 131.0.72.0/22;
    real_ip_header CF-Connecting-IP;

    # 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-http-pub-access.log;
    error_log /var/log/nginx/rpc-http-pub-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 - NO JWT authentication
    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 (for web apps and MetaMask)
        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;
        }
        
        # NO JWT authentication here - this is a public endpoint!
    }

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

# Public WebSocket RPC endpoint - NO authentication required
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name rpc-ws-pub.d-bis.org;

    # 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;

    # Trust Cloudflare IPs for real IP
    set_real_ip_from 173.245.48.0/20;
    set_real_ip_from 103.21.244.0/22;
    set_real_ip_from 103.22.200.0/22;
    set_real_ip_from 103.31.4.0/22;
    set_real_ip_from 141.101.64.0/18;
    set_real_ip_from 108.162.192.0/18;
    set_real_ip_from 190.93.240.0/20;
    set_real_ip_from 188.114.96.0/20;
    set_real_ip_from 197.234.240.0/22;
    set_real_ip_from 198.41.128.0/17;
    set_real_ip_from 162.158.0.0/15;
    set_real_ip_from 104.16.0.0/13;
    set_real_ip_from 104.24.0.0/14;
    set_real_ip_from 172.64.0.0/13;
    set_real_ip_from 131.0.72.0/22;
    real_ip_header CF-Connecting-IP;

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

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

    # WebSocket RPC endpoint - NO JWT authentication
    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;
        
        # NO JWT authentication here - this is a public endpoint!
    }

    # 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-public /etc/nginx/sites-enabled/

# Test configuration
log_info "Testing Nginx configuration..."
if nginx -t; then
    echo "✓ Nginx configuration is valid"
else
    echo "✗ Nginx configuration test failed"
    exit 1
fi

# Reload Nginx
log_info "Reloading Nginx..."
systemctl reload nginx || systemctl restart nginx

echo "✓ Public endpoints configured successfully"
NGINX_CONFIG_EOF

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

# Verify Nginx is running
log_info "Verifying Nginx status..."
if ssh -o ConnectTimeout=5 -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

# Test the endpoint
log_info "Testing public RPC endpoint..."
sleep 2
RPC_TEST=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- timeout 5 curl -k -s -X POST https://localhost \
    -H 'Host: rpc-http-pub.d-bis.org' \
    -H 'Content-Type: application/json' \
    -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_chainId\",\"params\":[],\"id\":1}' 2>&1 || echo 'FAILED'")

if echo "$RPC_TEST" | grep -q '"result":"0x8a"'; then
    log_success "Public RPC endpoint is working correctly!"
    log_info "Response: $RPC_TEST"
else
    log_warn "RPC endpoint test had unexpected response"
    log_info "Response: $RPC_TEST"
fi

echo ""
log_success "Public RPC endpoints configuration complete!"
echo ""
log_info "Configuration Summary:"
log_info "  - Public HTTP RPC: https://rpc-http-pub.d-bis.org (port 443 → 8545, NO auth)"
log_info "  - Public WebSocket RPC: wss://rpc-ws-pub.d-bis.org (port 443 → 8546, NO auth)"
log_info "  - Both endpoints are publicly accessible without JWT tokens"
echo ""
log_info "Next steps:"
log_info "  1. Test from external: curl -X POST https://rpc-http-pub.d-bis.org -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_chainId\",\"params\":[],\"id\":1}'"
log_info "  2. Verify MetaMask can connect without authentication"
log_info "  3. Ensure Cloudflared tunnel is routing correctly to VMID 2500"

