#!/usr/bin/env bash
# Fix Blockscout database migrations and ensure it starts properly
# Run this on the Blockscout container (VMID 5000 on pve2)

set -euo pipefail

VMID="${VMID:-5000}"
IP="${IP:-192.168.11.140}"
PASSWORD="${PASSWORD:-L@kers2010}"

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

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

echo "════════════════════════════════════════════════════════"
echo "Fixing Blockscout Database Migrations"
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Check current status
log_info "Step 1: Checking Blockscout status..."
CONTAINER_STATUS=$(exec_container "docker ps -a | grep blockscout | awk '{print \$7}'" || echo "")
if [ -z "$CONTAINER_STATUS" ]; then
    log_error "Blockscout container not found"
    exit 1
fi
log_info "Container status: $CONTAINER_STATUS"

# Step 2: Stop Blockscout
log_info "Step 2: Stopping Blockscout..."
exec_container "cd /opt/blockscout && docker-compose stop blockscout 2>/dev/null || docker compose stop blockscout 2>/dev/null || true"
log_success "Blockscout stopped"

# Step 3: Wait for PostgreSQL
log_info "Step 3: Ensuring PostgreSQL is ready..."
exec_container "cd /opt/blockscout && docker-compose up -d postgres 2>/dev/null || docker compose up -d postgres 2>/dev/null || true"
log_info "Waiting for PostgreSQL..."
for i in {1..30}; do
    if exec_container "docker exec blockscout-postgres pg_isready -U blockscout >/dev/null 2>&1"; then
        log_success "PostgreSQL is ready"
        break
    fi
    sleep 2
done

# Step 4: Run database migrations manually
log_info "Step 4: Running database migrations..."
log_info "This may take several minutes..."

# Try running migrations via docker exec
MIGRATE_RESULT=$(exec_container "docker run --rm --network blockscout_blockscout-network \
    -e DATABASE_URL=postgresql://blockscout:blockscout@postgres:5432/blockscout \
    -e ETHEREUM_JSONRPC_HTTP_URL=http://192.168.11.250:8545 \
    -e CHAIN_ID=138 \
    -e SECRET_KEY_BASE=73159c7d10b9a5a75ddf10710773078c078bf02124d35b72fa2a841b30b4f88c7c43e5caaf7f9f7f87d16dd66e7870931ae11039c428d1dedae187af762531fa \
    blockscout/blockscout:latest /app/bin/blockscout eval 'Ecto.Migrator.run(Explorer.Repo, :up, all: true)' 2>&1" || echo "FAILED")

if echo "$MIGRATE_RESULT" | grep -qE "(migrated|already up|Migrating)"; then
    log_success "Database migrations completed"
    echo "$MIGRATE_RESULT" | grep -E "(migrated|already|Migrating)" | tail -5
else
    log_warn "Migration command may not have worked, but continuing..."
    echo "$MIGRATE_RESULT" | tail -10
fi

# Step 5: Start Blockscout with proper configuration
log_info "Step 5: Starting Blockscout with correct configuration..."
exec_container "cd /opt/blockscout && docker-compose up -d blockscout 2>/dev/null || docker compose up -d blockscout 2>/dev/null || true"

# Step 6: Wait and check status
log_info "Step 6: Waiting for Blockscout to start..."
sleep 30

STATUS_CHECK=$(exec_container "docker ps | grep blockscout")
if echo "$STATUS_CHECK" | grep -q "Up"; then
    log_success "Blockscout container is running"
    echo "$STATUS_CHECK"
else
    log_warn "Blockscout container may still be starting"
    echo "$STATUS_CHECK"
fi

# Step 7: Check logs for startup
log_info "Step 7: Checking recent logs..."
exec_container "docker logs --tail 30 blockscout 2>&1" | tail -20

# Step 8: Test API endpoint
log_info "Step 8: Testing Blockscout API..."
sleep 10
API_TEST=$(exec_container "timeout 10 curl -s http://localhost:4000/api/v2/status 2>&1" || echo "")
if echo "$API_TEST" | grep -qE "(chain_id|success)"; then
    log_success "Blockscout API is responding!"
    echo "$API_TEST" | head -5
else
    log_warn "API not responding yet (may need more time)"
    echo "$API_TEST" | head -3
fi

echo ""
echo "════════════════════════════════════════════════════════"
echo "Migration Fix Complete"
echo "════════════════════════════════════════════════════════"
echo ""
log_info "Next steps:"
echo "  1. Monitor Blockscout logs: docker logs -f blockscout"
echo "  2. Test API: curl http://localhost:4000/api/v2/status"
echo "  3. Test HTTPS: curl -k https://localhost/health"
echo "  4. Test external: curl https://explorer.d-bis.org/health"
echo ""

