#!/bin/bash

# Script to check, test, and fix nginx configuration on VMID 5000
# Run this script directly inside VMID 5000

set -euo pipefail

BLOCKSCOUT_PORT=4000
DOMAIN="explorer.d-bis.org"
VM_IP="192.168.11.140"

echo "=========================================="
echo "Nginx Configuration Check for VMID 5000"
echo "=========================================="
echo ""

# Step 1: Check if nginx is installed
echo "=== Step 1: Checking Nginx Installation ==="
if command -v nginx >/dev/null 2>&1; then
    echo "✅ Nginx is installed"
    nginx -v 2>&1 | head -1
else
    echo "❌ Nginx is not installed"
    echo "Installing nginx..."
    apt-get update -qq
    apt-get install -y nginx
    echo "✅ Nginx installed"
fi
echo ""

# Step 2: Check nginx service status
echo "=== Step 2: Checking Nginx Service Status ==="
if systemctl is-active --quiet nginx; then
    echo "✅ Nginx is running"
else
    echo "⚠️  Nginx is not running, starting..."
    systemctl start nginx
    systemctl enable nginx
    echo "✅ Nginx started and enabled"
fi
echo ""

# Step 3: Check if Blockscout config exists
echo "=== Step 3: Checking Blockscout Configuration ==="
CONFIG_FILE="/etc/nginx/sites-available/blockscout"
ENABLED_FILE="/etc/nginx/sites-enabled/blockscout"

if [ -f "$CONFIG_FILE" ]; then
    echo "✅ Configuration file exists: $CONFIG_FILE"
    echo ""
    echo "Current configuration:"
    head -30 "$CONFIG_FILE"
    echo ""
else
    echo "❌ Configuration file not found: $CONFIG_FILE"
    echo "Creating configuration..."
    
    # Create SSL directory if it doesn't exist
    mkdir -p /etc/nginx/ssl
    
    # Create nginx configuration
    cat > "$CONFIG_FILE" << 'EOF'
# HTTP server - redirect to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name explorer.d-bis.org 192.168.11.140;

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

# HTTPS server - Blockscout Explorer
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name explorer.d-bis.org 192.168.11.140;

    # SSL configuration (if certificates exist)
    ssl_certificate /etc/letsencrypt/live/explorer.d-bis.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/explorer.d-bis.org/privkey.pem;
    
    # Fallback to self-signed if Let's Encrypt not available
    if (!-f /etc/letsencrypt/live/explorer.d-bis.org/fullchain.pem) {
        ssl_certificate /etc/nginx/ssl/blockscout.crt;
        ssl_certificate_key /etc/nginx/ssl/blockscout.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';
    ssl_prefer_server_ciphers off;
    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;

    # Blockscout Explorer endpoint
    location / {
        proxy_pass http://127.0.0.1:4000;
        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 Connection "";
        proxy_buffering off;
        proxy_request_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 300s;
        proxy_connect_timeout 75s;
    }

    # API endpoint (for Blockscout API)
    location /api/ {
        proxy_pass http://127.0.0.1:4000;
        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_read_timeout 300s;
        proxy_connect_timeout 75s;
    }

    # Health check endpoint
    location /health {
        access_log off;
        proxy_pass http://127.0.0.1:4000/api/v2/status;
        proxy_set_header Host $host;
        add_header Content-Type application/json;
    }
}

# WebSocket upgrade mapping
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
EOF
    echo "✅ Configuration file created"
fi
echo ""

# Step 4: Enable the site
echo "=== Step 4: Enabling Blockscout Site ==="
if [ -L "$ENABLED_FILE" ]; then
    echo "✅ Site is already enabled"
else
    echo "Enabling site..."
    ln -sf "$CONFIG_FILE" "$ENABLED_FILE"
    # Remove default site if it exists
    rm -f /etc/nginx/sites-enabled/default 2>/dev/null || true
    echo "✅ Site enabled"
fi
echo ""

# Step 5: Test nginx configuration
echo "=== Step 5: Testing Nginx Configuration ==="
if nginx -t; then
    echo "✅ Nginx configuration is valid"
    CONFIG_VALID=true
else
    echo "❌ Nginx configuration has errors"
    CONFIG_VALID=false
    echo ""
    echo "Configuration errors:"
    nginx -t 2>&1 || true
    exit 1
fi
echo ""

# Step 6: Check if Blockscout is running
echo "=== Step 6: Checking Blockscout Service ==="
if docker ps | grep blockscout | grep -v postgres >/dev/null; then
    echo "✅ Blockscout container is running"
    BLOCKSCOUT_RUNNING=true
else
    echo "⚠️  Blockscout container is not running"
    BLOCKSCOUT_RUNNING=false
fi

# Check if Blockscout is responding
if curl -s -f http://127.0.0.1:$BLOCKSCOUT_PORT/api/v2/stats >/dev/null 2>&1; then
    echo "✅ Blockscout API is responding on port $BLOCKSCOUT_PORT"
else
    echo "⚠️  Blockscout API is not responding on port $BLOCKSCOUT_PORT"
fi
echo ""

# Step 7: Restart nginx if config is valid
if [ "$CONFIG_VALID" = true ]; then
    echo "=== Step 7: Restarting Nginx ==="
    if systemctl restart nginx; then
        echo "✅ Nginx restarted successfully"
    else
        echo "❌ Failed to restart nginx"
        exit 1
    fi
    echo ""
    
    # Wait a moment for nginx to start
    sleep 2
    
    # Check nginx status
    if systemctl is-active --quiet nginx; then
        echo "✅ Nginx is running after restart"
    else
        echo "❌ Nginx failed to start"
        systemctl status nginx --no-pager -l || true
        exit 1
    fi
else
    echo "⚠️  Skipping nginx restart due to configuration errors"
    exit 1
fi
echo ""

# Step 8: Test the proxy
echo "=== Step 8: Testing Nginx Proxy ==="
echo "Testing HTTP redirect..."
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/ 2>/dev/null || echo "000")
if [ "$HTTP_STATUS" = "301" ] || [ "$HTTP_STATUS" = "302" ]; then
    echo "✅ HTTP redirect working (status: $HTTP_STATUS)"
else
    echo "⚠️  HTTP redirect may not be working (status: $HTTP_STATUS)"
fi

echo "Testing HTTPS proxy (if SSL available)..."
HTTPS_STATUS=$(curl -s -k -o /dev/null -w "%{http_code}" https://localhost/ 2>/dev/null || echo "000")
if [ "$HTTPS_STATUS" = "200" ] || [ "$HTTPS_STATUS" = "301" ] || [ "$HTTPS_STATUS" = "302" ]; then
    echo "✅ HTTPS proxy working (status: $HTTPS_STATUS)"
else
    echo "⚠️  HTTPS may not be configured (status: $HTTPS_STATUS)"
    echo "   This is normal if SSL certificates are not set up yet"
fi

echo "Testing API endpoint..."
API_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/api/v2/stats 2>/dev/null || echo "000")
if [ "$API_STATUS" = "200" ]; then
    echo "✅ API endpoint working (status: $API_STATUS)"
else
    echo "⚠️  API endpoint may not be working (status: $API_STATUS)"
fi
echo ""

# Step 9: Summary
echo "=========================================="
echo "Summary"
echo "=========================================="
echo "Nginx Status: $(systemctl is-active nginx && echo 'Running' || echo 'Not Running')"
echo "Configuration: $CONFIG_FILE"
echo "Site Enabled: $([ -L "$ENABLED_FILE" ] && echo 'Yes' || echo 'No')"
echo "Blockscout Running: $(docker ps | grep blockscout | grep -v postgres >/dev/null && echo 'Yes' || echo 'No')"
echo ""
echo "To view nginx logs:"
echo "  tail -f /var/log/nginx/access.log"
echo "  tail -f /var/log/nginx/error.log"
echo ""
echo "To test from outside:"
echo "  curl -k https://$DOMAIN/api/v2/stats"
echo "  curl -k https://$VM_IP/api/v2/stats"
echo ""

