#!/usr/bin/env bash
# Fix Blockscout container startup issue
# The container is exiting with code 0, which suggests it needs a proper command

set -euo pipefail

VMID="${1:-5000}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
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"; }

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.12}"

log_info "Fixing Blockscout container startup issue (VMID: $VMID)"

# Check if we're on Proxmox host
if ! command -v pct >/dev/null 2>&1; then
    log_error "This script must be run on Proxmox host"
    exit 1
fi

log_info "Updating docker-compose.yml to add proper command..."
pct exec $VMID -- bash <<'EOF'
cd /opt/blockscout

# Backup current config
cp docker-compose.yml docker-compose.yml.backup

# Update blockscout service to ensure it runs the server
cat > /tmp/blockscout-service.yml <<'SERVICE_EOF'
  blockscout:
    image: blockscout/blockscout:latest
    container_name: blockscout
    depends_on:
      - postgres
    command: mix phx.server
    environment:
      - DATABASE_URL=postgresql://blockscout:${DB_PASSWORD:-blockscout}@postgres:5432/blockscout
      - ETHEREUM_JSONRPC_HTTP_URL=${RPC_URL:-http://192.168.11.250:8545}
      - ETHEREUM_JSONRPC_WS_URL=${WS_URL:-ws://192.168.11.250:8546}
      - ETHEREUM_JSONRPC_TRACE_URL=${RPC_URL:-http://192.168.11.250:8545}
      - ETHEREUM_JSONRPC_VARIANT=besu
      - CHAIN_ID=${CHAIN_ID:-138}
      - COIN=ETH
      - BLOCKSCOUT_HOST=${BLOCKSCOUT_HOST:-localhost}
      - BLOCKSCOUT_PROTOCOL=http
      - SECRET_KEY_BASE=${SECRET_KEY:-$(openssl rand -hex 64)}
    ports:
      - "4000:4000"
    volumes:
      - blockscout-data:/app/apps/explorer/priv/static
    restart: unless-stopped
    networks:
      - blockscout-network
SERVICE_EOF

# Extract the blockscout service section and replace it
# This is a simplified approach - we'll update the file properly
python3 <<'PYTHON_EOF'
import yaml
import sys

try:
    with open('/opt/blockscout/docker-compose.yml', 'r') as f:
        config = yaml.safe_load(f)
    
    # Update blockscout service
    if 'services' in config and 'blockscout' in config['services']:
        # Add command if not present
        if 'command' not in config['services']['blockscout']:
            config['services']['blockscout']['command'] = 'mix phx.server'
        
        # Ensure environment variables are properly set
        env = config['services']['blockscout'].get('environment', [])
        env_dict = {}
        for item in env:
            if isinstance(item, str) and '=' in item:
                key, value = item.split('=', 1)
                env_dict[key] = value
        
        # Update WS_URL if it has wrong value
        if 'ETHEREUM_JSONRPC_WS_URL' in env_dict:
            if '10.3.1.40' in env_dict['ETHEREUM_JSONRPC_WS_URL']:
                env_dict['ETHEREUM_JSONRPC_WS_URL'] = 'ws://192.168.11.250:8546'
        
        # Convert back to list format
        config['services']['blockscout']['environment'] = [f"{k}={v}" for k, v in env_dict.items()]
    
    with open('/opt/blockscout/docker-compose.yml', 'w') as f:
        yaml.dump(config, f, default_flow_style=False, sort_keys=False)
    
    print("Configuration updated successfully")
except Exception as e:
    print(f"Error: {e}", file=sys.stderr)
    sys.exit(1)
PYTHON_EOF

# If Python approach fails, use sed
if [ $? -ne 0 ]; then
    log_warn "Python YAML update failed, using sed approach..."
    
    # Add command line after container_name if not present
    if ! grep -q "command:" docker-compose.yml; then
        sed -i '/container_name: blockscout/a\    command: mix phx.server' docker-compose.yml
    fi
    
    # Fix WS_URL
    sed -i 's|ws://10.3.1.40:8546|ws://192.168.11.250:8546|g' docker-compose.yml
    sed -i 's|\${WS_URL:-ws://10.3.1.40:8546}|ws://192.168.11.250:8546|g' docker-compose.yml
fi

log_info "Restarting Blockscout containers..."
docker-compose down
docker-compose up -d

log_info "Waiting for Blockscout to start..."
sleep 30

# Check status
if docker ps | grep -q blockscout.*Up; then
    echo "SUCCESS: Blockscout container is running"
else
    echo "WARNING: Blockscout container may still be starting"
    docker ps | grep blockscout
fi
EOF

if [ $? -eq 0 ]; then
    log_success "Blockscout container fix applied"
else
    log_error "Failed to fix Blockscout container"
    exit 1
fi

log_info "Checking container status..."
sleep 5
pct exec $VMID -- docker ps | grep blockscout

