#!/bin/bash

# Fix nginx conflicting server name warnings on VMID 5000
# Run this directly in VMID 5000

set -euo pipefail

echo "=========================================="
echo "Fixing Nginx Configuration Conflicts"
echo "=========================================="
echo ""

# Step 1: List all enabled sites
echo "=== Step 1: Checking Enabled Sites ==="
echo "Enabled nginx sites:"
ls -la /etc/nginx/sites-enabled/ 2>/dev/null || echo "No sites-enabled directory"
echo ""

# Step 2: Find all config files with conflicting server names
echo "=== Step 2: Finding Conflicting Configurations ==="
echo "Files containing 'explorer.d-bis.org':"
grep -r "explorer.d-bis.org" /etc/nginx/sites-enabled/ /etc/nginx/sites-available/ 2>/dev/null | cut -d: -f1 | sort -u
echo ""

# Step 3: Backup existing configs
echo "=== Step 3: Backing Up Existing Configs ==="
BACKUP_DIR="/root/nginx-backup-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
cp -r /etc/nginx/sites-available/* "$BACKUP_DIR/" 2>/dev/null || true
cp -r /etc/nginx/sites-enabled/* "$BACKUP_DIR/enabled/" 2>/dev/null || true
echo "✅ Backups saved to: $BACKUP_DIR"
echo ""

# Step 4: Remove all enabled sites
echo "=== Step 4: Removing All Enabled Sites ==="
rm -f /etc/nginx/sites-enabled/*
echo "✅ All enabled sites removed"
echo ""

# Step 5: Create a single clean configuration
echo "=== Step 5: Creating Clean Configuration ==="
CONFIG_FILE="/etc/nginx/sites-available/blockscout"

cat > "$CONFIG_FILE" << 'EOF'
# HTTP server - redirect to HTTPS only when not already behind HTTPS proxy (avoids ERR_TOO_MANY_REDIRECTS when NPMplus forwards to :80)
server {
    listen 80;
    listen [::]:80;
    server_name explorer.d-bis.org 192.168.11.140;

    # Allow Let's Encrypt challenges
    location /.well-known/acme-challenge/ {
        root /var/www/html;
        try_files $uri =404;
    }

    # When NPMplus (or similar) forwards HTTPS traffic to this port as HTTP, do NOT redirect back to HTTPS (avoids ERR_TOO_MANY_REDIRECTS)
    set $redirect_to_https 1;
    if ($http_x_forwarded_proto = "https") { set $redirect_to_https 0; }
    if ($http_x_forwarded_proto = "HTTPS") { set $redirect_to_https 0; }

    location /snap/ {
        alias /var/www/html/snap/;
        try_files $uri $uri/ /snap/index.html =404;
        add_header Cache-Control "no-store, no-cache, must-revalidate";
    }
    location = /snap { rewrite ^ /snap/ last; }

    location / {
        if ($redirect_to_https = 1) { return 301 https://$host$request_uri; }
        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;
    }
}

# 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 (nginx does not allow ssl_certificate inside if; use Let's Encrypt or self-signed)
    ssl_certificate /etc/letsencrypt/live/explorer.d-bis.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/explorer.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';
    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;

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

    # Chain 138 MetaMask Snap companion (serve from disk; do not proxy to Blockscout)
    location = /snap { rewrite ^ /snap/ last; }
    location /snap/ {
        alias /var/www/html/snap/;
        try_files $uri $uri/ /snap/index.html =404;
        add_header Cache-Control "no-store, no-cache, must-revalidate";
    }

    # Blockscout Explorer endpoint - proxy to Blockscout
    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;
    }

    # Token-aggregation API at /api/v1/ (Chain 138 Snap: market data, swap quote, bridge). Service runs on port 3001.
    location /api/v1/ {
        proxy_pass http://127.0.0.1:3001/api/v1/;
        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 60s;
        add_header Access-Control-Allow-Origin *;
    }

    # Explorer config API (token list, networks) - serve from /var/www/html/config/
    # Deploy files with: ./scripts/deploy-explorer-config-to-vmid5000.sh
    location = /api/config/token-list {
        default_type application/json;
        add_header Access-Control-Allow-Origin *;
        add_header Cache-Control "public, max-age=3600";
        alias /var/www/html/config/DUAL_CHAIN_TOKEN_LIST.tokenlist.json;
    }
    location = /api/config/networks {
        default_type application/json;
        add_header Access-Control-Allow-Origin *;
        add_header Cache-Control "public, max-age=3600";
        alias /var/www/html/config/DUAL_CHAIN_NETWORKS.json;
    }

    # 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;
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        add_header Access-Control-Allow-Headers "Content-Type";
    }

    # 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 "✅ Clean configuration created: $CONFIG_FILE"
echo ""

# Step 5.5: Ensure config directory exists for /api/config/token-list and /api/config/networks
echo "=== Step 5.5: Config Directory for Token List ==="
mkdir -p /var/www/html/config
if [ -f "/var/www/html/config/DUAL_CHAIN_TOKEN_LIST.tokenlist.json" ]; then
  echo "Config files already present in /var/www/html/config/"
else
  echo "Note: Run deploy-explorer-config-to-vmid5000.sh from repo root to deploy token list. /api/config/* will 404 until then."
fi
echo ""

# Step 6: Enable the site
echo "=== Step 6: Enabling Blockscout Site ==="
ln -sf "$CONFIG_FILE" /etc/nginx/sites-enabled/blockscout
echo "✅ Site enabled"
echo ""

# Step 7: Test configuration
echo "=== Step 7: Testing Configuration ==="
if nginx -t 2>&1 | grep -q "test is successful"; then
    echo "✅ Nginx configuration is valid"
    CONFIG_VALID=true
    # Show warnings if any (but they should be gone now)
    nginx -t 2>&1 | grep -i warn || echo "No warnings!"
else
    echo "❌ Nginx configuration has errors"
    nginx -t
    exit 1
fi
echo ""

# Step 8: Restart nginx
if [ "$CONFIG_VALID" = true ]; then
    echo "=== Step 8: Restarting Nginx ==="
    if systemctl restart nginx; then
        echo "✅ Nginx restarted successfully"
    else
        echo "❌ Failed to restart nginx"
        systemctl status nginx --no-pager -l
        exit 1
    fi
    echo ""
    
    sleep 2
    
    if systemctl is-active --quiet nginx; then
        echo "✅ Nginx is running"
    else
        echo "❌ Nginx failed to start"
        exit 1
    fi
fi
echo ""

# Step 9: Test endpoints
echo "=== Step 9: Testing Endpoints ==="
echo "Testing HTTP redirect..."
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/ 2>/dev/null || echo "000")
echo "HTTP status: $HTTP_STATUS"

echo "Testing API endpoint..."
API_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/api/v2/stats 2>/dev/null || echo "000")
echo "API status: $API_STATUS"

if [ "$API_STATUS" = "200" ]; then
    echo "✅ API endpoint working"
    curl -s http://localhost/api/v2/stats | head -3
else
    echo "⚠️  API endpoint returned status: $API_STATUS"
fi
echo ""

echo "=========================================="
echo "Summary"
echo "=========================================="
echo "✅ Configuration cleaned up"
echo "✅ Single config file: $CONFIG_FILE"
echo "✅ Nginx restarted"
echo "✅ Backup saved to: $BACKUP_DIR"
echo ""
echo "To view logs:"
echo "  tail -f /var/log/nginx/blockscout-access.log"
echo "  tail -f /var/log/nginx/blockscout-error.log"
echo ""

