#!/usr/bin/env bash
# Restore Blockscout Full Web Interface - Remove Landing Page, Enable Full Explorer

set -euo pipefail

IP="${IP:-192.168.11.140}"
DOMAIN="${DOMAIN:-explorer.d-bis.org}"
PASSWORD="${PASSWORD:-L@kers2010}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
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_step() { echo -e "${CYAN}[STEP]${NC} $1"; }

exec_container() {
    local cmd="$1"
    sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "bash -c '$cmd'" 2>&1
}

echo "════════════════════════════════════════════════════════"
echo "Restore Blockscout Full Web Interface"
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Remove landing page override
log_step "Step 1: Removing landing page override..."
exec_container "rm -f /var/www/html/index.html" || true
log_success "Landing page removed"

# Step 2: Update Nginx to proxy directly to Blockscout without fallback
log_step "Step 2: Updating Nginx configuration for full Blockscout access..."

cat > /tmp/blockscout-full-interface.conf <<'NGINX_EOF'
# Blockscout Full Web Interface Configuration

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

    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:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    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;

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

    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    send_timeout 300s;

    client_max_body_size 100M;

    # All paths proxy to Blockscout (including root)
    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 X-Forwarded-Host $host;
        proxy_set_header Connection "";
        proxy_buffering off;
        proxy_request_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        
        # Important for Blockscout web interface
        proxy_redirect off;
        proxy_cookie_path / /;
    }

    # API endpoints
    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;
    }

    # Health check
    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;
    }
}

# HTTP redirect
server {
    listen 80;
    listen [::]:80;
    server_name explorer.d-bis.org 192.168.11.140;

    location /.well-known/acme-challenge/ {
        root /var/www/html;
        try_files $uri =404;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

# WebSocket upgrade mapping
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
NGINX_EOF

sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no /tmp/blockscout-full-interface.conf root@"$IP":/etc/nginx/sites-available/blockscout

# Step 3: Verify Blockscout configuration
log_step "Step 3: Verifying Blockscout configuration..."
DISABLE_WEBAPP=$(exec_container "docker exec blockscout env | grep DISABLE_WEBAPP | cut -d'=' -f2")
if [ "$DISABLE_WEBAPP" != "false" ]; then
    log_error "Webapp is disabled! Enabling..."
    exec_container "cd /opt/blockscout && sed -i 's/DISABLE_WEBAPP=true/DISABLE_WEBAPP=false/' docker-compose.yml && docker-compose restart blockscout"
    log_info "Waiting 60 seconds for Blockscout to restart..."
    sleep 60
else
    log_success "Webapp is enabled (DISABLE_WEBAPP=$DISABLE_WEBAPP)"
fi

# Step 4: Restart Blockscout to ensure web interface is fully initialized
log_step "Step 4: Restarting Blockscout to ensure web interface is ready..."
exec_container "cd /opt/blockscout && docker-compose restart blockscout"
log_info "Waiting 90 seconds for Blockscout to fully initialize..."
sleep 90

# Step 5: Test and reload Nginx
log_step "Step 5: Testing and reloading Nginx..."
exec_container "nginx -t" || {
    log_error "Nginx configuration test failed!"
    exit 1
}
log_success "Nginx configuration test passed"
exec_container "systemctl reload nginx"
log_success "Nginx reloaded"

# Step 6: Test Blockscout routes
log_step "Step 6: Testing Blockscout web interface routes..."
sleep 10

# Test various routes
ROOT_TEST=$(curl -k -s -o /dev/null -w '%{http_code}' https://explorer.d-bis.org/ 2>&1)
BLOCKS_TEST=$(curl -k -s -o /dev/null -w '%{http_code}' https://explorer.d-bis.org/blocks 2>&1)
API_TEST=$(curl -k -s -o /dev/null -w '%{http_code}' https://explorer.d-bis.org/api/v2/stats 2>&1)

log_info "Root (/): HTTP $ROOT_TEST"
log_info "Blocks (/blocks): HTTP $BLOCKS_TEST"
log_info "API (/api/v2/stats): HTTP $API_TEST"

# Step 7: Get block number for testing specific routes
LATEST_BLOCK=$(exec_container "docker exec blockscout-postgres psql -U blockscout -d blockscout -t -c \"SELECT number FROM blocks WHERE number > 0 ORDER BY number DESC LIMIT 1;\" 2>&1" | tr -d ' ' | head -1)
if [ -n "$LATEST_BLOCK" ] && [ "$LATEST_BLOCK" != "" ]; then
    log_step "Step 7: Testing specific block route..."
    BLOCK_ROUTE_TEST=$(curl -k -s -o /dev/null -w '%{http_code}' "https://explorer.d-bis.org/block/$LATEST_BLOCK" 2>&1)
    log_info "Block route (/block/$LATEST_BLOCK): HTTP $BLOCK_ROUTE_TEST"
    
    if [ "$BLOCK_ROUTE_TEST" = "200" ]; then
        log_success "Block route is working! Blockscout web interface is accessible!"
    fi
fi

# Step 8: Check Blockscout logs for web interface
log_step "Step 8: Checking Blockscout logs..."
WEBAPP_LOGS=$(exec_container "docker logs --tail 50 blockscout 2>&1 | grep -iE '(webapp|phoenix|router|endpoint|started)' | tail -10")
if [ -n "$WEBAPP_LOGS" ]; then
    log_info "Webapp logs found:"
    echo "$WEBAPP_LOGS"
fi

echo ""
log_step "Summary:"
echo "  Configuration: ✅ Blockscout webapp enabled"
echo "  Nginx: ✅ Updated to proxy all routes to Blockscout"
echo "  Landing Page: ✅ Removed (Blockscout interface will be served)"
echo ""
if [ "$ROOT_TEST" = "200" ] || [ "$BLOCKS_TEST" = "200" ] || [ "$BLOCK_ROUTE_TEST" = "200" ]; then
    log_success "Blockscout full web interface should now be accessible!"
    log_info "Visit: https://explorer.d-bis.org/"
    log_info "Features available:"
    log_info "  - Full block explorer interface"
    log_info "  - Transaction history and details"
    log_info "  - Address lookups"
    log_info "  - Token tracking"
    log_info "  - Contract verification"
    log_info "  - Network statistics"
else
    log_warn "Some routes still return non-200 status"
    log_info "Blockscout may need more time to fully initialize"
    log_info "Try accessing specific routes:"
    log_info "  - https://explorer.d-bis.org/blocks"
    log_info "  - https://explorer.d-bis.org/block/$LATEST_BLOCK"
    log_info "  - https://explorer.d-bis.org/api/v2/stats"
fi
echo ""

