#!/usr/bin/env bash
# Fix All Blockscout Issues - Comprehensive Update and Optimization
# Addresses: Docker image update, Nginx upgrade, configuration improvements

set -euo pipefail

VMID="${VMID:-5000}"
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 All Blockscout Issues - Comprehensive Update"
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Backup current state
log_step "Step 1: Creating backup of current configuration..."
BACKUP_DIR="/tmp/blockscout-backup-$(date +%Y%m%d-%H%M%S)"
exec_container "mkdir -p $BACKUP_DIR && cd /opt/blockscout && cp docker-compose.yml $BACKUP_DIR/ && echo 'Backup created: $BACKUP_DIR'"
log_success "Backup created"

# Step 2: Check current versions
log_step "Step 2: Checking current versions..."
CURRENT_IMAGE=$(exec_container "docker images blockscout/blockscout:latest --format '{{.ID}}' | head -1")
CURRENT_NGINX=$(exec_container "nginx -v 2>&1 | grep -oP 'nginx/\K[0-9.]+'")
CURRENT_OPENSSL=$(exec_container "openssl version | grep -oP 'OpenSSL \K[0-9.]+'")

log_info "Current Blockscout Image ID: $CURRENT_IMAGE"
log_info "Current Nginx Version: $CURRENT_NGINX"
log_info "Current OpenSSL Version: $CURRENT_OPENSSL"

# Step 3: Update Blockscout Docker Image
log_step "Step 3: Updating Blockscout Docker Image..."
log_info "Pulling latest Blockscout image..."
exec_container "cd /opt/blockscout && docker-compose pull blockscout 2>&1 | tail -10"

NEW_IMAGE=$(exec_container "docker images blockscout/blockscout:latest --format '{{.ID}}' | head -1")
if [ "$CURRENT_IMAGE" != "$NEW_IMAGE" ]; then
    log_success "New Blockscout image available: $NEW_IMAGE"
    log_info "Restarting Blockscout with new image..."
    exec_container "cd /opt/blockscout && docker-compose up -d blockscout 2>&1"
    log_success "Blockscout restarted with new image"
else
    log_info "Blockscout image is already up to date"
fi

# Step 4: Upgrade Nginx
log_step "Step 4: Upgrading Nginx..."
log_info "Adding Nginx official repository..."

exec_container "apt-get update -qq && apt-get install -y -qq software-properties-common lsb-release 2>&1 | tail -5" || true

# Add Nginx stable repository
exec_container "if ! grep -q 'nginx' /etc/apt/sources.list.d/nginx.list 2>/dev/null; then
    add-apt-repository -y 'ppa:nginx/stable' 2>&1 || 
    (echo 'deb http://nginx.org/packages/ubuntu/ $(lsb_release -cs) nginx' > /etc/apt/sources.list.d/nginx.list &&
     echo 'deb-src http://nginx.org/packages/ubuntu/ $(lsb_release -cs) nginx' >> /etc/apt/sources.list.d/nginx.list)
fi" 2>&1 | tail -5

log_info "Updating package lists..."
exec_container "apt-get update -qq 2>&1 | tail -5"

log_info "Upgrading Nginx..."
exec_container "apt-get install -y nginx 2>&1 | grep -E '(Setting up|Unpacking|nginx)' | tail -10" || {
    log_warn "Nginx upgrade may require manual intervention or is already latest"
    exec_container "nginx -v 2>&1"
}

NEW_NGINX=$(exec_container "nginx -v 2>&1 | grep -oP 'nginx/\K[0-9.]+'")
if [ "$CURRENT_NGINX" != "$NEW_NGINX" ]; then
    log_success "Nginx upgraded: $CURRENT_NGINX → $NEW_NGINX"
    log_info "Testing Nginx configuration..."
    exec_container "nginx -t 2>&1"
    log_info "Reloading Nginx..."
    exec_container "systemctl reload nginx 2>&1"
    log_success "Nginx reloaded successfully"
else
    log_info "Nginx is already at latest version or upgrade requires manual steps"
fi

# Step 5: Check and optimize configuration
log_step "Step 5: Optimizing Blockscout configuration..."

# Check current configuration values
CURRENT_POOL_SIZE=$(exec_container "cd /opt/blockscout && grep POOL_SIZE docker-compose.yml | grep -oP 'POOL_SIZE=\K[0-9]+' || echo '10'")
log_info "Current database pool size: $CURRENT_POOL_SIZE"

# Check if we should increase pool size based on available memory
MEMORY_GB=$(exec_container "free -g | awk '/^Mem:/ {print \$2}'")
if [ "$MEMORY_GB" -gt 8 ] && [ "$CURRENT_POOL_SIZE" -lt 20 ]; then
    log_info "Increasing database pool size for better performance..."
    exec_container "cd /opt/blockscout && sed -i 's/POOL_SIZE=$CURRENT_POOL_SIZE/POOL_SIZE=20/' docker-compose.yml && grep POOL_SIZE docker-compose.yml"
    log_success "Pool size increased to 20"
fi

# Step 6: Verify services
log_step "Step 6: Verifying all services..."
sleep 5

CONTAINER_STATUS=$(exec_container "docker ps --format 'table {{.Names}}\t{{.Status}}' | grep -E '(blockscout|postgres)'")
echo "$CONTAINER_STATUS"

NGINX_STATUS=$(exec_container "systemctl is-active nginx 2>&1")
if [ "$NGINX_STATUS" = "active" ]; then
    log_success "Nginx is running"
else
    log_error "Nginx is not running: $NGINX_STATUS"
fi

# Step 7: Test connectivity
log_step "Step 7: Testing connectivity..."
sleep 10

BLOCKSCOUT_API=$(exec_container "timeout 10 curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:4000/api/v2/status 2>&1" || echo "000")
if [ "$BLOCKSCOUT_API" != "000" ]; then
    log_success "Blockscout API responding (HTTP $BLOCKSCOUT_API)"
else
    log_warn "Blockscout API not responding yet (may need more time)"
fi

NGINX_HTTPS=$(exec_container "timeout 10 curl -k -s -o /dev/null -w '%{http_code}' -H 'Host: $DOMAIN' https://127.0.0.1/ 2>&1" || echo "000")
if [ "$NGINX_HTTPS" != "000" ]; then
    log_success "Nginx HTTPS responding (HTTP $NGINX_HTTPS)"
else
    log_warn "Nginx HTTPS not responding"
fi

# Step 8: Check indexing status
log_step "Step 8: Checking indexing status..."
INDEXING_STATUS=$(exec_container "docker exec blockscout-postgres psql -U blockscout -d blockscout -t -c \"SELECT 'Blocks: ' || count(*)::text || ', Latest: ' || COALESCE(max(number)::text, '0') || ', Transactions: ' || (SELECT count(*)::text FROM transactions) FROM blocks;\" 2>&1" | tr -d ' ')
log_info "Indexing Status: $INDEXING_STATUS"

# Step 9: Provide RPC configuration recommendations
log_step "Step 9: RPC Configuration Analysis..."
log_info "Reviewing RPC connection and method availability..."

RPC_TEST=$(exec_container "timeout 5 curl -s -X POST -H 'Content-Type: application/json' --data '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}' http://192.168.11.250:8545 2>&1" | head -3 || echo "RPC not accessible")
if echo "$RPC_TEST" | grep -q "result"; then
    log_success "RPC endpoint is accessible"
else
    log_warn "RPC endpoint may not be accessible or may need configuration"
fi

echo ""
log_info "RPC Method Recommendations:"
echo "  - Internal transaction tracing: Requires trace_* RPC methods"
echo "  - Block rewards: Requires debug_* or eth_getBlockReward RPC methods"
echo "  - These are optional features - basic explorer works without them"
echo "  - To enable: Configure Besu RPC node with --rpc-ws-api=TRACE,DEBUG"

# Step 10: Summary
log_step "Step 10: Final Status Summary..."
echo ""
echo "════════════════════════════════════════════════════════"
echo "Fix Summary"
echo "════════════════════════════════════════════════════════"
echo ""
echo "Blockscout Image:"
echo "  Before: $CURRENT_IMAGE"
echo "  After:  $NEW_IMAGE"
if [ "$CURRENT_IMAGE" != "$NEW_IMAGE" ]; then
    echo "  Status: ✅ UPDATED"
else
    echo "  Status: ℹ️  Already latest"
fi
echo ""
echo "Nginx Version:"
echo "  Before: $CURRENT_NGINX"
echo "  After:  $NEW_NGINX"
if [ "$CURRENT_NGINX" != "$NEW_NGINX" ]; then
    echo "  Status: ✅ UPGRADED"
else
    echo "  Status: ℹ️  Already latest or manual upgrade needed"
fi
echo ""
echo "Services Status:"
echo "  Blockscout Container: $(exec_container "docker ps --format '{{.Status}}' --filter 'name=blockscout' | head -1")"
echo "  PostgreSQL Container: $(exec_container "docker ps --format '{{.Status}}' --filter 'name=blockscout-postgres' | head -1")"
echo "  Nginx Service: $NGINX_STATUS"
echo ""
echo "Connectivity:"
echo "  Blockscout API: HTTP $BLOCKSCOUT_API"
echo "  Nginx HTTPS: HTTP $NGINX_HTTPS"
echo ""
echo "Indexing: $INDEXING_STATUS"
echo ""
echo "Backup Location: $BACKUP_DIR"
echo ""
log_success "All fixes completed!"
echo ""
log_info "Next steps:"
echo "  1. Monitor Blockscout logs: docker logs -f blockscout"
echo "  2. Monitor indexing progress for 24-48 hours"
echo "  3. Test web interface: https://$DOMAIN"
echo "  4. Review RPC configuration if internal transactions are needed"
echo ""

