#!/bin/bash
# Setup Central Nginx Routing for All Services
# Routes all Cloudflare tunnel traffic through VMID 105 to internal services

set -e

NGINX_VMID=105
NGINX_IP=192.168.11.21
PROXMOX_HOST=192.168.11.12

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

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

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  SETTING UP CENTRAL NGINX ROUTING (VMID $NGINX_VMID)"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Check container status
log_info "Checking container status..."
CONTAINER_STATUS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct status $NGINX_VMID 2>/dev/null | awk '{print \$2}'" || echo "unknown")

if [ "$CONTAINER_STATUS" != "running" ]; then
    log_error "Container $NGINX_VMID is not running (status: $CONTAINER_STATUS)"
    exit 1
fi
log_success "Container $NGINX_VMID is running"

# Check Nginx installation
log_info "Checking Nginx installation..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $NGINX_VMID -- which nginx >/dev/null 2>&1"; then
    log_error "Nginx is not installed on VMID $NGINX_VMID"
    exit 1
fi
log_success "Nginx is installed"

# Create Nginx configuration
log_info "Creating Nginx configuration..."

ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
    "pct exec $NGINX_VMID -- bash" << 'NGINX_EOF'
cat > /etc/nginx/sites-available/all-services << 'CONFIG_EOF'
# Central Nginx Configuration for All Services
# VMID 105 - Routes all Cloudflare tunnel traffic to internal services
# Generated: $(date)

# Explorer / Blockscout
server {
    listen 80;
    server_name explorer.d-bis.org;
    
    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;
    
    # Increase timeouts for long-running requests
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    
    location / {
        proxy_pass http://192.168.11.280:80;
    }
}

# RPC Public HTTP
server {
    listen 80;
    server_name rpc-http-pub.d-bis.org;
    
    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;
    
    # Increase timeouts for RPC calls
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    
    location / {
        proxy_pass https://192.168.11.252:443;
        proxy_ssl_verify off;
    }
}

# RPC Public WebSocket
server {
    listen 80;
    server_name rpc-ws-pub.d-bis.org;
    
    proxy_http_version 1.1;
    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;
    
    # Increase timeouts for WebSocket connections
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    
    location / {
        proxy_pass https://192.168.11.252:443;
        proxy_ssl_verify off;
    }
}

# RPC Private HTTP
server {
    listen 80;
    server_name rpc-http-prv.d-bis.org;
    
    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;
    
    # Increase timeouts for RPC calls
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    
    location / {
        proxy_pass https://192.168.11.251:443;
        proxy_ssl_verify off;
    }
}

# RPC Private WebSocket
server {
    listen 80;
    server_name rpc-ws-prv.d-bis.org;
    
    proxy_http_version 1.1;
    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;
    
    # Increase timeouts for WebSocket connections
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    
    location / {
        proxy_pass https://192.168.11.251:443;
        proxy_ssl_verify off;
    }
}

# DBIS Admin Frontend
server {
    listen 80;
    server_name dbis-admin.d-bis.org;
    
    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;
    
    location / {
        proxy_pass http://192.168.11.130:80;
    }
}

# DBIS API Primary
server {
    listen 80;
    server_name dbis-api.d-bis.org;
    
    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;
    
    location / {
        proxy_pass http://192.168.11.290:3000;
    }
}

# DBIS API Secondary
server {
    listen 80;
    server_name dbis-api-2.d-bis.org;
    
    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;
    
    location / {
        proxy_pass http://192.168.11.291:3000;
    }
}

# Miracles In Motion
server {
    listen 80;
    server_name mim4u.org www.mim4u.org;
    
    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;
    
    location / {
        proxy_pass http://192.168.11.19:80;
    }
}

# Default catch-all
server {
    listen 80 default_server;
    server_name _;
    
    location / {
        return 404 "Service not found for host: $host";
    }
}
CONFIG_EOF

# Enable the site
log_info "Enabling Nginx site..."
ln -sf /etc/nginx/sites-available/all-services /etc/nginx/sites-enabled/all-services

# Remove default site if it conflicts
rm -f /etc/nginx/sites-enabled/default 2>/dev/null || true

# Test configuration
log_info "Testing Nginx configuration..."
if nginx -t 2>&1; then
    log_success "Nginx configuration is valid"
else
    log_error "Nginx configuration test failed"
    exit 1
fi

# Reload Nginx
log_info "Reloading Nginx..."
systemctl reload nginx
log_success "Nginx reloaded successfully"

NGINX_EOF

log_success "Nginx configuration deployed to VMID $NGINX_VMID"

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  NGINX CONFIGURATION COMPLETE"
log_info "═══════════════════════════════════════════════════════════"
echo ""
log_info "Next: Update Cloudflare tunnel to route all traffic to:"
log_info "  http://${NGINX_IP}:80"
echo ""

