#!/usr/bin/env bash
# Complete SSL setup for Blockscout with Cloudflare Tunnel
# Sets up Let's Encrypt certificates, Nginx SSL, and Cloudflare tunnel HTTPS
# Usage: ./setup-blockscout-ssl-complete.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${ENV_FILE:-$SCRIPT_DIR/../.env}"

# Configuration
VMID="${VMID:-5000}"
IP="${IP:-192.168.11.140}"
DOMAIN="${DOMAIN:-explorer.d-bis.org}"
BLOCKSCOUT_PORT="${BLOCKSCOUT_PORT:-4000}"
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
EMAIL="${EMAIL:-admin@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"; }

# Load environment variables
if [ -f "$ENV_FILE" ]; then
    source "$ENV_FILE"
fi

echo "════════════════════════════════════════════════════════"
echo "Blockscout SSL Setup with Cloudflare Tunnel"
echo "════════════════════════════════════════════════════════"
echo ""
echo "Configuration:"
echo "  VMID: $VMID"
echo "  IP: $IP"
echo "  Domain: $DOMAIN"
echo "  Email: $EMAIL"
echo ""

# Function to execute command in container (direct SSH to container IP)
exec_container() {
    local cmd="$1"
    sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "bash -c '$cmd'" 2>&1
}

# Step 1: Install Certbot
log_info "Step 1: Installing Certbot..."
exec_container "export DEBIAN_FRONTEND=noninteractive && apt-get update -qq && apt-get install -y -qq certbot python3-certbot-nginx" || {
    log_error "Failed to install Certbot"
    exit 1
}
log_success "Certbot installed"

# Step 2: Configure Nginx for ACME challenge (HTTP port 80)
log_info "Step 2: Configuring Nginx for ACME challenge..."
# Create config file locally then copy
cat > /tmp/blockscout-nginx-acme.conf <<EOF
# HTTP server - for Let's Encrypt ACME challenge
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN $IP;

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

    # Temporary: proxy to Blockscout for testing (will redirect to HTTPS after cert)
    location / {
        proxy_pass http://127.0.0.1:$BLOCKSCOUT_PORT;
        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;
    }
}
EOF

sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no /tmp/blockscout-nginx-acme.conf root@"$IP":/etc/nginx/sites-available/blockscout
exec_container "mkdir -p /var/www/html/.well-known/acme-challenge && chown -R www-data:www-data /var/www/html && ln -sf /etc/nginx/sites-available/blockscout /etc/nginx/sites-enabled/ && rm -f /etc/nginx/sites-enabled/default && nginx -t && systemctl reload nginx" || {
    log_error "Failed to configure Nginx"
    exit 1
}
log_success "Nginx configured for ACME challenge"

# Step 3: Obtain SSL certificate from Let's Encrypt
log_info "Step 3: Obtaining SSL certificate from Let's Encrypt..."
log_info "This may take a minute..."
CERT_RESULT=$(exec_container "certbot certonly --nginx -d $DOMAIN --non-interactive --agree-tos --email $EMAIL --keep-until-expiring 2>&1" || echo "FAILED")

if echo "$CERT_RESULT" | grep -q "Successfully received certificate"; then
    log_success "SSL certificate obtained successfully"
    CERT_PATH="/etc/letsencrypt/live/$DOMAIN/fullchain.pem"
    KEY_PATH="/etc/letsencrypt/live/$DOMAIN/privkey.pem"
else
    log_error "Failed to obtain SSL certificate"
    echo "$CERT_RESULT" | tail -20
    exit 1
fi

# Step 4: Configure Nginx with SSL
log_info "Step 4: Configuring Nginx with SSL certificates..."
cat > /tmp/blockscout-nginx-ssl.conf <<EOF
# HTTP server - redirect to HTTPS
server {
    listen 80;
    listen [::]:80;
    server_name $DOMAIN $IP;

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

    # Redirect all other traffic to HTTPS
    location / {
        return 301 https://\$host\$request_uri;
    }
}

# HTTPS server - Blockscout Explorer
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name $DOMAIN $IP;

    # SSL configuration
    ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/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;

    # 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;

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

    # Client body size (for large contract verification uploads)
    client_max_body_size 100M;

    # Blockscout Explorer endpoint
    location / {
        proxy_pass http://127.0.0.1:$BLOCKSCOUT_PORT;
        proxy_http_version 1.1;
        
        # Headers
        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 "";
        
        # Buffer settings
        proxy_buffering off;
        proxy_request_buffering off;
        
        # WebSocket support
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection \$connection_upgrade;
    }

    # API endpoint
    location /api/ {
        proxy_pass http://127.0.0.1:$BLOCKSCOUT_PORT;
        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:$BLOCKSCOUT_PORT/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

sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no /tmp/blockscout-nginx-ssl.conf root@"$IP":/etc/nginx/sites-available/blockscout
exec_container "nginx -t && systemctl reload nginx" || {
    log_error "Failed to configure Nginx with SSL"
    exit 1
}
log_success "Nginx configured with SSL"

# Step 5: Set up auto-renewal
log_info "Step 5: Setting up certificate auto-renewal..."
exec_container "systemctl enable certbot.timer && systemctl start certbot.timer" || {
    log_warn "Failed to enable certbot timer (may already be enabled)"
}
log_success "Auto-renewal configured"

# Step 6: Update Blockscout to use HTTPS
log_info "Step 6: Updating Blockscout configuration for HTTPS..."
exec_container "cd /opt/blockscout && if [ -f docker-compose.yml ]; then sed -i 's|BLOCKSCOUT_PROTOCOL=http|BLOCKSCOUT_PROTOCOL=https|g' docker-compose.yml && sed -i 's|BLOCKSCOUT_HOST=192.168.11.140|BLOCKSCOUT_HOST=$DOMAIN|g' docker-compose.yml && docker-compose restart blockscout 2>/dev/null || docker compose restart blockscout 2>/dev/null || true && echo 'Blockscout configuration updated'; else echo 'docker-compose.yml not found, skipping Blockscout config update'; fi" || {
    log_warn "Failed to update Blockscout configuration (may need manual update)"
}

# Step 7: Update Cloudflare Tunnel to use HTTPS
log_info "Step 7: Updating Cloudflare Tunnel route to HTTPS..."
if [ -f "$SCRIPT_DIR/configure-cloudflare-tunnel-route.sh" ]; then
    export EXPLORER_IP="$IP"
    export EXPLORER_PORT="443"
    bash "$SCRIPT_DIR/configure-cloudflare-tunnel-route.sh" || {
        log_warn "Failed to update Cloudflare tunnel route automatically"
        log_info "Manual update needed: Change tunnel route to https://$IP:443"
    }
else
    log_warn "Cloudflare tunnel route script not found"
    log_info "Manual update needed: Change tunnel route to https://$IP:443"
fi

# Step 8: Test SSL configuration
log_info "Step 8: Testing SSL configuration..."
sleep 5

SSL_TEST=$(exec_container "timeout 5 curl -k -s -o /dev/null -w '%{http_code}' https://localhost/health 2>&1" || echo "000")
if [ "$SSL_TEST" = "200" ] || [ "$SSL_TEST" = "301" ] || [ "$SSL_TEST" = "302" ]; then
    log_success "HTTPS is working (HTTP $SSL_TEST)"
else
    log_warn "HTTPS test returned: HTTP $SSL_TEST"
fi

# Step 9: Verify certificate
log_info "Step 9: Verifying SSL certificate..."
CERT_INFO=$(exec_container "openssl x509 -in /etc/letsencrypt/live/$DOMAIN/fullchain.pem -noout -subject -issuer -dates 2>&1" || echo "")
if [ -n "$CERT_INFO" ]; then
    log_success "Certificate details:"
    echo "$CERT_INFO" | while read line; do
        log_info "  $line"
    done
fi

echo ""
echo "════════════════════════════════════════════════════════"
echo "SSL Setup Complete!"
echo "════════════════════════════════════════════════════════"
echo ""
log_success "Configuration Summary:"
echo "  Domain: $DOMAIN"
echo "  SSL Certificate: /etc/letsencrypt/live/$DOMAIN/"
echo "  HTTPS Port: 443"
echo "  HTTP Port: 80 (redirects to HTTPS)"
echo ""
log_info "Access Points:"
echo "  Internal HTTPS: https://$IP"
echo "  External HTTPS: https://$DOMAIN"
echo "  Health Check: https://$DOMAIN/health"
echo ""
log_info "Next Steps:"
echo "  1. Verify Cloudflare tunnel route points to https://$IP:443"
echo "  2. Test external access: curl https://$DOMAIN/health"
echo "  3. Monitor certificate renewal: systemctl status certbot.timer"
echo ""

# Cleanup
rm -f /tmp/blockscout-nginx-acme.conf /tmp/blockscout-nginx-ssl.conf
