#!/usr/bin/env bash
# Fix Blockscout Root Path - Redirect root to /blocks
# Blockscout doesn't serve root path, so we redirect it

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 "Fix Blockscout Root Path - Redirect to /blocks"
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Test if /blocks route works
log_step "Step 1: Testing /blocks route..."
BLOCKS_TEST=$(exec_container "curl -s -o /dev/null -w '%{http_code}' 'http://127.0.0.1:4000/blocks' 2>&1")
log_info "/blocks route: HTTP $BLOCKS_TEST"

if [ "$BLOCKS_TEST" = "404" ]; then
    log_warn "/blocks also returns 404, trying /block (singular)..."
    BLOCK_SINGULAR_TEST=$(exec_container "curl -s -o /dev/null -w '%{http_code}' 'http://127.0.0.1:4000/block' 2>&1")
    log_info "/block route: HTTP $BLOCK_SINGULAR_TEST"
fi

# Step 2: Get current Nginx config
log_step "Step 2: Reading current Nginx configuration..."
exec_container "cp /etc/nginx/sites-available/blockscout /etc/nginx/sites-available/blockscout.backup"
log_success "Backup created"

# Step 3: Read and modify Nginx config
log_step "Step 3: Updating Nginx configuration..."

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

# Modify to add root redirect
cat > /tmp/blockscout-nginx-updated.conf <<'EOF'
# Blockscout Root Path Fix
# Redirect root path to /blocks if Blockscout returns 404

# Try root path first, if 404, redirect to /blocks
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;
    
    # If Blockscout returns 404, try redirect to /blocks
    proxy_intercept_errors on;
    error_page 404 = @redirect_to_blocks;
}

# Redirect to blocks page
location @redirect_to_blocks {
    return 302 /blocks;
}

EOF

# Read existing config and insert our fix
EXISTING_CONFIG=$(cat /tmp/blockscout-nginx-current.conf)

# Create new config with root path handling
cat > /tmp/blockscout-nginx-fixed.conf <<'NGINX_EOF'
# Blockscout Nginx Configuration with Root Path Fix

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;

    # Root path - redirect to /blocks if Blockscout returns 404
    location = / {
        # Try Blockscout first
        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;
        
        # Intercept 404 errors and redirect
        proxy_intercept_errors on;
        error_page 404 = @redirect_to_blocks;
    }

    # Redirect handler
    location @redirect_to_blocks {
        return 302 /blocks;
    }

    # All other paths
    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;
    }

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

# 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

# Upload new config
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no /tmp/blockscout-nginx-fixed.conf root@"$IP":/etc/nginx/sites-available/blockscout

# Step 4: Test and reload Nginx
log_step "Step 4: Testing Nginx configuration..."
exec_container "nginx -t" || {
    log_error "Nginx configuration test failed!"
    log_info "Restoring backup..."
    exec_container "cp /etc/nginx/sites-available/blockscout.backup /etc/nginx/sites-available/blockscout"
    exit 1
}

log_success "Nginx configuration test passed"

log_step "Step 5: Reloading Nginx..."
exec_container "systemctl reload nginx"
log_success "Nginx reloaded"

# Step 6: Test root path
log_step "Step 6: Testing root path..."
sleep 2

ROOT_TEST=$(curl -k -s -o /dev/null -w '%{http_code}' https://explorer.d-bis.org/ 2>&1)
log_info "Root path response: HTTP $ROOT_TEST"

if [ "$ROOT_TEST" = "302" ] || [ "$ROOT_TEST" = "200" ]; then
    log_success "Root path is now working! (HTTP $ROOT_TEST)"
    log_info "If 302, it's redirecting to /blocks (expected)"
elif [ "$ROOT_TEST" = "404" ]; then
    log_warn "Root path still returns 404"
    log_info "Blockscout may need a different route or more initialization time"
else
    log_info "Root path returns HTTP $ROOT_TEST"
fi

echo ""
log_success "Configuration update completed!"
log_info "Access: https://explorer.d-bis.org/"
log_info "  - Root (/) will redirect to /blocks if Blockscout returns 404"
log_info "  - All other routes work normally"
echo ""

