#!/bin/bash
# Fix Nginx Configuration for Blockscout Explorer
# Ensures Nginx is properly configured to proxy to Blockscout on port 4000

set -e

VMID="${1:-5000}"
IP="${2:-192.168.11.140}"
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}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

# Function to execute command in container
exec_container() {
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct exec $VMID -- bash -c '$1'" 2>&1
}

log_info "Fixing Nginx Configuration for Blockscout"
log_info "VMID: $VMID"
log_info "IP: $IP"
echo ""

# Step 1: Check Nginx configuration
log_info "Step 1: Checking current Nginx configuration..."
NGINX_TEST=$(exec_container "nginx -t 2>&1" || echo "FAILED")
if echo "$NGINX_TEST" | grep -q "syntax is ok\|test is successful"; then
    log_success "Nginx configuration is valid"
    echo "$NGINX_TEST"
else
    log_warn "Nginx configuration has errors:"
    echo "$NGINX_TEST"
    echo ""
    
    # Step 2: Create/update Nginx configuration
    log_info "Step 2: Creating/updating Nginx configuration..."
    
    NGINX_CONFIG='server {
    listen 80;
    listen [::]:80;
    server_name explorer.d-bis.org;

    # Redirect HTTP to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name explorer.d-bis.org;

    # SSL certificates (self-signed or Let'\''s Encrypt)
    ssl_certificate /etc/nginx/ssl/blockscout.crt;
    ssl_certificate_key /etc/nginx/ssl/blockscout.key;
    
    # SSL configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # Logging
    access_log /var/log/nginx/blockscout-access.log;
    error_log /var/log/nginx/blockscout-error.log;

    # Increase timeouts for Blockscout
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    send_timeout 300s;

    # Proxy settings
    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 X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Port $server_port;

    # WebSocket support
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    # Health check endpoint
    location /health {
        proxy_pass http://127.0.0.1:4000/api/v2/status;
        proxy_set_header Host $host;
    }

    # API endpoints
    location /api/ {
        proxy_pass http://127.0.0.1:4000/api/;
        proxy_set_header Host $host;
    }

    # Main application
    location / {
        proxy_pass http://127.0.0.1:4000;
        proxy_set_header Host $host;
    }
}'

    # Write configuration to container
    log_info "Writing Nginx configuration..."
    exec_container "mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled /etc/nginx/ssl" || true
    
    # Create config file
    echo "$NGINX_CONFIG" | exec_container "cat > /etc/nginx/sites-available/blockscout"
    
    # Enable site
    exec_container "ln -sf /etc/nginx/sites-available/blockscout /etc/nginx/sites-enabled/blockscout" || true
    
    # Remove default site if it conflicts
    exec_container "rm -f /etc/nginx/sites-enabled/default" || true
    
    # Ensure SSL certificates exist (create self-signed if needed)
    log_info "Checking SSL certificates..."
    if ! exec_container "test -f /etc/nginx/ssl/blockscout.crt"; then
        log_warn "SSL certificates not found, creating self-signed certificates..."
        exec_container "openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/blockscout.key -out /etc/nginx/ssl/blockscout.crt -subj '/CN=explorer.d-bis.org'" || {
            log_error "Failed to create SSL certificates"
        }
    fi
    
    # Test configuration
    log_info "Testing new Nginx configuration..."
    NGINX_TEST=$(exec_container "nginx -t 2>&1" || echo "FAILED")
    if echo "$NGINX_TEST" | grep -q "syntax is ok\|test is successful"; then
        log_success "Nginx configuration is now valid"
        echo "$NGINX_TEST"
    else
        log_error "Nginx configuration still has errors:"
        echo "$NGINX_TEST"
        exit 1
    fi
fi

# Step 3: Restart Nginx
log_info "Step 3: Restarting Nginx..."
exec_container "systemctl restart nginx" || {
    log_error "Failed to restart Nginx"
    exit 1
}
log_success "Nginx restarted"

# Step 4: Verify Nginx is running
log_info "Step 4: Verifying Nginx status..."
NGINX_STATUS=$(exec_container "systemctl is-active nginx" || echo "inactive")
if [ "$NGINX_STATUS" = "active" ]; then
    log_success "Nginx is running"
else
    log_error "Nginx is not running"
    exit 1
fi

# Step 5: Test proxy
log_info "Step 5: Testing Nginx proxy..."
sleep 2
if timeout 5 bash -c "echo > /dev/tcp/$IP/80" 2>/dev/null; then
    log_success "Port 80 is accessible"
    HTTP_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" "http://$IP" 2>&1)
    log_info "HTTP response code: $HTTP_RESPONSE"
else
    log_warn "Port 80 may not be accessible"
fi

echo ""
log_success "Nginx configuration fix complete!"
log_info "Note: If Blockscout is not running on port 4000, Nginx will return 502 Bad Gateway"
log_info "Start Blockscout service: pct exec $VMID -- systemctl start blockscout"

