#!/bin/bash

# Complete fix for Blockscout migrations issue
# Runs migrations in one-off container and updates docker-compose.yml

set -euo pipefail

VMID=5000

echo "=========================================="
echo "Complete Blockscout Migrations Fix"
echo "=========================================="
echo ""

# Check if running from Proxmox host or inside container
if [ -f "/proc/1/cgroup" ] && grep -q "lxc" /proc/1/cgroup 2>/dev/null; then
    EXEC_PREFIX=""
    echo "Running inside VMID 5000"
else
    EXEC_PREFIX="pct exec $VMID --"
    echo "Running from Proxmox host, executing in VMID 5000"
fi

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

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

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

# Step 2: Run migrations in one-off container
echo "Step 2: Running migrations in one-off container..."
echo "This may take a few minutes..."
$EXEC_PREFIX docker run --rm \
  --network container:$BLOCKSCOUT_CONTAINER \
  -e DATABASE_URL=postgresql://blockscout:blockscout@postgres:5432/blockscout \
  blockscout/blockscout:latest \
  bin/blockscout eval "Explorer.Release.migrate()"

if [ $? -eq 0 ]; then
    echo "✅ Migrations completed successfully"
else
    echo "❌ Migrations failed"
    exit 1
fi
echo ""

# Step 3: Verify tables were created
echo "Step 3: Verifying tables were created..."
$EXEC_PREFIX docker exec blockscout-postgres psql -U blockscout -d blockscout -c "
SELECT 
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'migrations_status') 
    THEN '✅ migrations_status' ELSE '❌ MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'blocks') 
    THEN '✅ blocks' ELSE '❌ MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'transactions') 
    THEN '✅ transactions' ELSE '❌ MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'addresses') 
    THEN '✅ addresses' ELSE '❌ MISSING' END;
" 2>&1

echo ""

# Step 4: Find docker-compose.yml
echo "Step 4: Updating docker-compose.yml to run migrations on startup..."
BLOCKSCOUT_DIR=""
if [ -d /opt/blockscout ]; then
    BLOCKSCOUT_DIR="/opt/blockscout"
elif [ -d /root/blockscout ]; then
    BLOCKSCOUT_DIR="/root/blockscout"
else
    echo "❌ Cannot find Blockscout directory"
    exit 1
fi

cd "$BLOCKSCOUT_DIR"

if [ ! -f docker-compose.yml ]; then
    echo "❌ docker-compose.yml not found in $BLOCKSCOUT_DIR"
    exit 1
fi

# Backup
cp docker-compose.yml docker-compose.yml.backup.$(date +%Y%m%d_%H%M%S)
echo "✅ Created backup: docker-compose.yml.backup.*"

# Update command to run migrations before start
if grep -q "command:" docker-compose.yml; then
    # Replace existing command
    sed -i 's|command:.*blockscout start|command: sh -c "bin/blockscout eval '\''Explorer.Release.migrate()'\'' \&\& bin/blockscout start"|' docker-compose.yml
    sed -i 's|command:.*/app/bin/blockscout start|command: sh -c "bin/blockscout eval '\''Explorer.Release.migrate()'\'' \&\& bin/blockscout start"|' docker-compose.yml
else
    # Add command if it doesn't exist
    sed -i '/blockscout:/a\    command: sh -c "bin/blockscout eval '\''Explorer.Release.migrate()'\'' \&\& bin/blockscout start"' docker-compose.yml
fi

echo "✅ Updated docker-compose.yml"
echo ""

# Step 5: Restart Blockscout
echo "Step 5: Restarting Blockscout..."
$EXEC_PREFIX cd "$BLOCKSCOUT_DIR" && docker compose down blockscout 2>/dev/null || true
sleep 2
$EXEC_PREFIX cd "$BLOCKSCOUT_DIR" && docker compose up -d blockscout

echo "✅ Blockscout restarted"
echo ""

# Step 6: Wait and check status
echo "Step 6: Waiting for Blockscout to start (30 seconds)..."
sleep 30

echo ""
echo "Checking container status..."
$EXEC_PREFIX docker ps | grep blockscout || echo "⚠️  Container not running"

echo ""
echo "Recent logs:"
$EXEC_PREFIX docker logs blockscout 2>&1 | tail -20

echo ""
echo "=========================================="
echo "Fix Complete!"
echo "=========================================="
echo ""
echo "If container is still crashing, check logs:"
echo "  docker logs blockscout 2>&1 | tail -50"
echo ""
echo "To verify API is working:"
echo "  curl -s http://localhost:4000/api/v2/stats | head -20"

