#!/bin/bash

# Quick fix script for Blockscout initialization issues
# Run from Proxmox host: ./scripts/blockscout-quick-fix.sh

set -euo pipefail

VMID=5000

echo "=========================================="
echo "Blockscout Quick Fix for VMID 5000"
echo "=========================================="
echo ""

# Execute fix commands in VMID 5000
pct exec $VMID -- bash << 'FIX_SCRIPT'
set -euo pipefail

echo "Finding Blockscout container..."
BLOCKSCOUT_CONTAINER=$(docker ps -a | grep blockscout | grep -v postgres | awk '{print $1}' | head -1)

if [ -z "$BLOCKSCOUT_CONTAINER" ]; then
    echo "❌ ERROR: Blockscout container not found"
    exit 1
fi

echo "✅ Found container: $BLOCKSCOUT_CONTAINER"
echo ""

# Step 1: Verify database connectivity
echo "=== Step 1: Verifying database connectivity ==="
echo "Blockscout database credentials:"
echo "  User: blockscout"
echo "  Database: blockscout"
echo "  Password: blockscout"
docker exec -it blockscout-postgres psql -U blockscout -d blockscout -c "SELECT 1;" >/dev/null 2>&1 && \
  echo "✅ Database connection successful" || \
  echo "⚠️  Database connection check failed (may still work)"
echo ""

# Step 2: Run migrations
echo "=== Step 2: Running database migrations ==="
docker exec -it $BLOCKSCOUT_CONTAINER bin/blockscout eval "Explorer.Release.migrate()" || {
    echo "⚠️  Release.migrate() failed, trying mix ecto.migrate..."
    docker exec -it $BLOCKSCOUT_CONTAINER mix ecto.migrate
}
echo ""

# Step 3: Build assets
echo "=== Step 3: Building static assets ==="
docker exec -it $BLOCKSCOUT_CONTAINER mix phx.digest || {
    echo "⚠️  mix phx.digest failed, trying npm deploy..."
    docker exec -it $BLOCKSCOUT_CONTAINER npm run deploy || true
}
echo ""

# Step 4: Update docker-compose if needed
echo "=== Step 4: Updating docker-compose configuration ==="
BLOCKSCOUT_DIR="/opt/blockscout"
if [ -f "$BLOCKSCOUT_DIR/docker-compose.yml" ]; then
    # Check if command is already set
    if ! grep -q "command:.*blockscout start" "$BLOCKSCOUT_DIR/docker-compose.yml"; then
        echo "Adding startup command to docker-compose.yml..."
        sed -i '/blockscout:/a\    command: bin/blockscout start' "$BLOCKSCOUT_DIR/docker-compose.yml"
        echo "✅ Updated docker-compose.yml"
    else
        echo "✅ docker-compose.yml already has startup command"
    fi
else
    echo "⚠️  docker-compose.yml not found at $BLOCKSCOUT_DIR"
fi
echo ""

# Step 5: Restart Blockscout
echo "=== Step 5: Restarting Blockscout ==="
if [ -f "$BLOCKSCOUT_DIR/docker-compose.yml" ]; then
    cd "$BLOCKSCOUT_DIR"
    docker compose restart blockscout || docker compose up -d blockscout
else
    echo "Restarting container manually..."
    docker restart $BLOCKSCOUT_CONTAINER || {
        docker stop $BLOCKSCOUT_CONTAINER
        docker start $BLOCKSCOUT_CONTAINER
    }
fi

echo ""
echo "Waiting for Blockscout to start..."
sleep 10

# Step 6: Verify
echo "=== Step 6: Verification ==="
if docker ps | grep -q blockscout; then
    echo "✅ Blockscout container is running"
    
    # Check logs for errors
    echo ""
    echo "Recent logs:"
    docker logs blockscout 2>&1 | tail -10
    
    # Check if tables exist in Blockscout database
    echo ""
    echo "Checking Blockscout database tables..."
    docker exec -it blockscout-postgres psql -U blockscout -d blockscout -c "
      SELECT 
        CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'blocks') 
          THEN '✅ blocks' ELSE '❌ blocks' END as blocks,
        CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'transactions') 
          THEN '✅ transactions' ELSE '❌ transactions' END as transactions,
        CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'migrations_status') 
          THEN '✅ migrations_status' ELSE '❌ migrations_status' END as migrations_status;
    " 2>/dev/null || echo "⚠️  Could not verify tables (container may still be starting)"
else
    echo "❌ Blockscout container is not running"
    echo "Check logs: docker logs blockscout"
    exit 1
fi

echo ""
echo "=========================================="
echo "✅ Blockscout fix complete!"
echo "=========================================="
FIX_SCRIPT

echo ""
echo "Fix completed. Check status with:"
echo "  pct exec $VMID -- docker logs blockscout"

