#!/usr/bin/env bash
# Install Cloudflare Origin Certificate for VMID 2400
# This configures SSL/TLS between Cloudflare and the origin server
#
# Usage: ./scripts/install-cloudflare-origin-cert-vmid2400.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Configuration
VMID=2400
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
HOSTNAME="thirdweb-rpc-1"
IP="192.168.11.240"
DOMAIN="defi-oracle.io"
FQDN="rpc.public-0138.defi-oracle.io"

# Certificate paths
CERT_DIR="/etc/nginx/ssl"
CERT_FILE="${CERT_DIR}/cloudflare-origin.crt"
KEY_FILE="${CERT_DIR}/cloudflare-origin.key"

# 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 "═══════════════════════════════════════════════════════════"
log_info "  INSTALLING CLOUDFLARE ORIGIN CERTIFICATE FOR VMID 2400"
log_info "═══════════════════════════════════════════════════════════"
echo ""
log_info "VMID: $VMID"
log_info "FQDN: $FQDN"
log_info "Domain: $DOMAIN"
echo ""

# Check SSH access
log_info "Checking SSH access to $PROXMOX_HOST..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "echo 'SSH OK'" &>/dev/null; then
    log_error "Cannot access $PROXMOX_HOST via SSH"
    exit 1
fi
log_success "SSH access confirmed"

# Check container status
log_info "Checking container status..."
CONTAINER_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 [[ "$CONTAINER_STATUS" != "running" ]]; then
    log_error "Container $VMID is not running"
    exit 1
fi
log_success "Container is running"

# Create certificate directory
log_info "Creating certificate directory..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- mkdir -p $CERT_DIR" || {
    log_error "Failed to create certificate directory"
    exit 1
}
log_success "Certificate directory created"

# Install certificate
log_info "Installing Cloudflare Origin Certificate..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" << 'CERT_INSTALL_EOF'
cat > /etc/nginx/ssl/cloudflare-origin.crt << 'CERT_EOF'
-----BEGIN CERTIFICATE-----
MIIEqDCCA5CgAwIBAgIUbQZJXSkiljzN5DxMhWr28C+1wV8wDQYJKoZIhvcNAQEL
BQAwgYsxCzAJBgNVBAYTAlVTMRkwFwYDVQQKExBDbG91ZEZsYXJlLCBJbmMuMTQw
MgYDVQQLEytDbG91ZEZsYXJlIE9yaWdpbiBTU0wgQ2VydGlmaWNhdGUgQXV0aG9y
aXR5MRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMRMwEQYDVQQIEwpDYWxpZm9ybmlh
MB4XDTI2MDEwMjA1MTIwMFoXDTQwMTIyOTA1MTIwMFowYjEZMBcGA1UEChMQQ2xv
dWRGbGFyZSwgSW5jLjEdMBsGA1UECxMUQ2xvdWRGbGFyZSBPcmlnaW4gQ0ExJjAk
BgNVBAMTHUNsb3VkRmxhcmUgT3JpZ2luIENlcnRpZmljYXRlMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqmOyOGVqvvimFUaJ3h57x8JEdrF9EmzvA6UZ
NaM2+EWokdnpRcX2U22dKvfPw8sbsJd3SHmhTDL73Ta6sD7GPLI/b/TmyI3aBSKL
WDOIPG9eUaKvWSL0luMW7sFhWzpY8+ChrexxC555Wu+6TUeZ0jFFG3FuSUcZkJwV
zcBY5+woW1475F0VYKY9ZCrqsWWaPfQp9ufKyIfX6CipP/OfHMl+RhXLkroaD01/
AHEyuXL1pOwiZ5oBjcWlRytxewsZI2GsGoMQPbFPWAfgxavySR62rRSYxdv/L2VH
dzJvEsyW0yp4eLsOgA3HRnrxuTPV+5iWCK6ZquNnAPAnjCrXfQIDAQABo4IBKjCC
ASYwDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcD
ATAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBQPCdcXrgg3UXvAOgcVu3rJL8HCvDAf
BgNVHSMEGDAWgBQk6FNXXXw0QIep65TbuuEWePwppDBABggrBgEFBQcBAQQ0MDIw
MAYIKwYBBQUHMAGGJGh0dHA6Ly9vY3NwLmNsb3VkZmxhcmUuY29tL29yaWdpbl9j
YTArBgNVHREEJDAighAqLmRlZmktb3JhY2xlLmlvgg5kZWZpLW9yYWNsZS5pbzA4
BgNVHR8EMTAvMC2gK6AphidodHRwOi8vY3JsLmNsb3VkZmxhcmUuY29tL29yaWdp
bl9jYS5jcmwwDQYJKoZIhvcNAQELBQADggEBALB+7pxeH+V0esDtV7zvcxcQYXQu
2rmGA2uOHc5CQG9Ap09SWwlDm4T5cct/9MWyifu4IwOtgrAwqyoQ0BSOMTIOewld
Pg5cnhVOdaEhylEz+wSp3b7ZVUNqoHuBXsKt9Yb7t7A88FuwpirF3qMa9T2JMkE1
KUmctNu49H9xYxFnUz55JsEwbZlWvavg/J+IV2Lmy5iTKOjmEFH7HhwAJNNiWBvl
78hSlI6WLkgpp0gKmaIWK47t+xSIbOFuZbM9WnXNtBNbj1riSRVtchTp0OovJ2C0
w3aolHbmriFF2MZYZjnf//1jrUlxIatqvj7C13sSudKv98oiBrCKAMt2r8A=
-----END CERTIFICATE-----
CERT_EOF
CERT_INSTALL_EOF

if [[ $? -eq 0 ]]; then
    log_success "Certificate installed"
else
    log_error "Failed to install certificate"
    exit 1
fi

# Install private key
log_info "Installing Cloudflare Origin Private Key..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" << 'KEY_INSTALL_EOF'
cat > /etc/nginx/ssl/cloudflare-origin.key << 'KEY_EOF'
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCqY7I4ZWq++KYV
RoneHnvHwkR2sX0SbO8DpRk1ozb4RaiR2elFxfZTbZ0q98/Dyxuwl3dIeaFMMvvd
NrqwPsY8sj9v9ObIjdoFIotYM4g8b15Roq9ZIvSW4xbuwWFbOljz4KGt7HELnnla
77pNR5nSMUUbcW5JRxmQnBXNwFjn7ChbXjvkXRVgpj1kKuqxZZo99Cn258rIh9fo
KKk/858cyX5GFcuSuhoPTX8AcTK5cvWk7CJnmgGNxaVHK3F7CxkjYawagxA9sU9Y
B+DFq/JJHratFJjF2/8vZUd3Mm8SzJbTKnh4uw6ADcdGevG5M9X7mJYIrpmq42cA
8CeMKtd9AgMBAAECggEAHzRhbgMizMUoU3Km6pseE6wgEjW4oGB7WGlKx+Azf73w
HH/yQQE7drV3KGiYb/TZRhrDMW53DAe1SSLOB1uDvhdt10DcaCPUZwbXyqgrXdgO
h7hZ0SL99MkziLe5LvYtVsKPkZTg8h4MfwsyzRbdFJnJ3HgGWNyw0aNIOfVtQtHY
LXsPosAx/xR7loyOs3bG+ObXXgC/SCtPkW7qkpe4YwyvQOM/8p/MzHbQyd4/tUqN
UmQT6KwUu1jNtFyCaPYI5WE9Nl4HSF9ZeBKmbMW598Jx91I7ZW9MZcNwQlJV0t6J
N18zGLa66GAI9reY56qW6reCPnhjr5H4smNNsTTd0QKBgQDhRS96/XToG7S1P1Yz
aqFlre5Pwt+o4Hstf2f2aa1BD2ez0XTOt3hY67SoaQQ/qn4trkpgmT6bEcUPbzWW
ljm7fMLMvhLmAOy3qhZYd0dm5SaOV/K0k5wNmeio0+vVIp1AVUj7DUmFIWOJCdrj
VZEuWtjLGNk/lT5eWY2/JQIPcQKBgQDBofsMec+dvQR1QDAiKaAtFTULCOVlminW
0SZEzH03WYrM+epxsifAE96Z4mGjUAFN6a/luCdGAxMq24MxhKk6IPECgnJ8l5Bo
iFpzlMKk9vT9nAr5RX1x7+06OBVNARjDpuIHdwopUPOTqSckl744n6Aq4GuMu17H
qpbRT6MazQKBgQDFj+uoLYjN1x6Qpk9vIGETz4plIT8N2HGu4UHH9b4ghOYp6dRL
RtShB3aVDCTRwTCP138bYMprLRZqBto0iuNu7mfZMAla9gyktuKKC3HvZ6B8zdzp
SVtfAk/tYI4/ie/nb+RlaK3FuBaXJLF3FqAQy1O+Kri87qKYFGof7ND1wQKBgGX9
xBaWMt2LKkX4QWI9OrmEaiQd03bo9RDJqbajX3FAIPRGz06D4Jwz2xSDQZqcEZPQ
e24sycL+66GvbjMvBVQw9cG0pEksLExjRgGLYdsymWjcQIt8Js9U6Ue5Mr8UzM6B
oJz9/sQ0d5hXiN6lbvS0X9E11HCUYSAaosYthGQhAoGBANpOUCCG/zL/mt5t9Yac
Skb45HmePIXLDSO4a2exJS+cf+JLesFS4HNfA9rdeiU7tgt36iWdQQs1mQMl/0S/
Q/RAl/5fRi8GeJVqhHnMsFwccQi0Z0U5h87cuJrRMarKzyxqh4FQCtCKp/1r2haO
o66qLCliW8n8+5wJJUi9P+6M
-----END PRIVATE KEY-----
KEY_EOF
KEY_INSTALL_EOF

if [[ $? -eq 0 ]]; then
    log_success "Private key installed"
else
    log_error "Failed to install private key"
    exit 1
fi

# Set proper permissions
log_info "Setting certificate permissions..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- chmod 644 $CERT_FILE && chmod 600 $KEY_FILE && chown root:root $CERT_FILE $KEY_FILE" || {
    log_error "Failed to set permissions"
    exit 1
}
log_success "Permissions set"

# Verify certificate
log_info "Verifying certificate..."
CERT_INFO=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- openssl x509 -in $CERT_FILE -text -noout 2>/dev/null | grep -E 'Subject:|Issuer:|DNS:' | head -5" || echo "")

if [[ -n "$CERT_INFO" ]]; then
    log_success "Certificate verified"
    echo "$CERT_INFO" | sed 's/^/  /'
else
    log_warn "Could not verify certificate (may still be valid)"
fi

# Check if Nginx is installed
log_info "Checking Nginx installation..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- command -v nginx >/dev/null 2>&1"; then
    log_warn "Nginx not installed. Installing..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- apt update -qq && apt install -y nginx" || {
        log_error "Failed to install Nginx"
        exit 1
    }
    log_success "Nginx installed"
else
    log_success "Nginx is installed"
fi

# Create/Update Nginx configuration
log_info "Creating Nginx configuration for $FQDN..."
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- bash" << 'NGINX_CONFIG_EOF'
cat > /etc/nginx/sites-available/rpc-thirdweb << 'NGINX_EOF'
# HTTP to HTTPS redirect
server {
    listen 80;
    listen [::]:80;
    server_name rpc.public-0138.defi-oracle.io;
    
    # 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 rpc.public-0138.defi-oracle.io;
    
    # Cloudflare Origin Certificate
    ssl_certificate /etc/nginx/ssl/cloudflare-origin.crt;
    ssl_certificate_key /etc/nginx/ssl/cloudflare-origin.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    
    # 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;
    
    # 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;
    
    # Logging
    access_log /var/log/nginx/rpc-thirdweb-access.log;
    error_log /var/log/nginx/rpc-thirdweb-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;
        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 CF-Connecting-IP $http_cf_connecting_ip;
        proxy_set_header CF-Ray $http_cf_ray;
        proxy_set_header Connection "";
        proxy_buffering off;
        proxy_request_buffering off;
        
        # CORS headers (for ThirdWeb 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;
    }
}

# HTTPS server - WebSocket RPC API (port 8546)
server {
    listen 8443 ssl http2;
    listen [::]:8443 ssl http2;
    server_name rpc.public-0138.defi-oracle.io;
    
    # Cloudflare Origin Certificate
    ssl_certificate /etc/nginx/ssl/cloudflare-origin.crt;
    ssl_certificate_key /etc/nginx/ssl/cloudflare-origin.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    
    # Security headers
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # Logging
    access_log /var/log/nginx/rpc-thirdweb-ws-access.log;
    error_log /var/log/nginx/rpc-thirdweb-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;
        proxy_set_header CF-Connecting-IP $http_cf_connecting_ip;
        
        # 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;
    }
}
NGINX_EOF

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

# Test configuration
nginx -t

# Reload Nginx
systemctl reload nginx
NGINX_CONFIG_EOF

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

# Verify Nginx is running
log_info "Verifying Nginx status..."
NGINX_STATUS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $VMID -- systemctl is-active nginx 2>/dev/null || echo 'inactive'")

if [[ "$NGINX_STATUS" == "active" ]]; then
    log_success "Nginx is running"
else
    log_warn "Nginx status: $NGINX_STATUS"
    log_info "Starting Nginx..."
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct exec $VMID -- systemctl start nginx" || log_warn "Failed to start Nginx"
fi

# Summary
echo ""
log_success "═══════════════════════════════════════════════════════════"
log_success "  CLOUDFLARE ORIGIN CERTIFICATE INSTALLATION COMPLETE"
log_success "═══════════════════════════════════════════════════════════"
echo ""
log_info "Certificate installed: $CERT_FILE"
log_info "Private key installed: $KEY_FILE"
log_info "Nginx configured for: $FQDN"
echo ""
log_info "Next steps:"
echo ""
echo "1. Update Cloudflare Tunnel Route:"
echo "   - Go to: Zero Trust → Networks → Tunnels"
echo "   - Select tunnel: 26138c21-db00-4a02-95db-ec75c07bda5b"
echo "   - Configure → Public Hostname"
echo "   - Update URL to: https://127.0.0.1:443"
echo "   - (Or keep http://127.0.0.1:8545 if using HTTP internally)"
echo ""
echo "2. Test HTTPS endpoint:"
echo "   curl -k https://rpc.public-0138.defi-oracle.io/health"
echo ""
echo "3. Test RPC endpoint:"
echo "   curl -k https://rpc.public-0138.defi-oracle.io \\"
echo "     -X POST -H 'Content-Type: application/json' \\"
echo "     -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'"
echo ""
