#!/bin/bash

# Script to run Blockscout migrations before starting the container
# This fixes the "migrations_status does not exist" error

set -euo pipefail

VMID=5000

echo "=========================================="
echo "Fix Blockscout Migrations"
echo "=========================================="
echo ""
echo "The issue: migrations_status table is missing, causing crashes"
echo "Solution: Run migrations BEFORE starting Blockscout"
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

# Find 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 "Container: $BLOCKSCOUT_CONTAINER"
echo ""

# Step 1: Start container temporarily to run migrations
echo "=== Step 1: Starting container temporarily ==="
$EXEC_PREFIX docker start $BLOCKSCOUT_CONTAINER
echo "Waiting for container to initialize..."
sleep 10
echo ""

# Step 2: Run migrations
echo "=== Step 2: Running database migrations ==="
echo "This will create all missing tables including migrations_status..."
echo ""

# Try multiple migration methods
if $EXEC_PREFIX docker exec -it $BLOCKSCOUT_CONTAINER bin/blockscout eval "Explorer.Release.migrate()" 2>&1; then
    echo "✅ Migrations completed using Explorer.Release.migrate()"
elif $EXEC_PREFIX docker exec -it $BLOCKSCOUT_CONTAINER mix ecto.migrate 2>&1; then
    echo "✅ Migrations completed using mix ecto.migrate"
else
    echo "⚠️  Migration commands failed, trying alternative..."
    # Try running migrations in a one-off container
    echo "Attempting to run migrations in a new container..."
    $EXEC_PREFIX docker run --rm \
        --network container:$BLOCKSCOUT_CONTAINER \
        -e DATABASE_URL=postgresql://blockscout:blockscout@postgres:5432/blockscout?sslmode=disable \
        -e ECTO_USE_SSL=false \
        blockscout/blockscout:latest \
        bin/blockscout eval "Explorer.Release.migrate()" 2>&1 || \
    $EXEC_PREFIX docker run --rm \
        --network container:$BLOCKSCOUT_CONTAINER \
        -e DATABASE_URL=postgresql://blockscout:blockscout@postgres:5432/blockscout?sslmode=disable \
        -e ECTO_USE_SSL=false \
        blockscout/blockscout:latest \
        mix ecto.migrate 2>&1
fi

echo ""

# Step 3: Verify migrations_status table exists
echo "=== Step 3: Verifying migrations_status table ==="
$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 table exists' 
    ELSE '❌ migrations_status table MISSING' END;
" 2>&1

echo ""

# Step 4: Check other critical tables
echo "=== Step 4: Verifying critical tables ==="
$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 = 'blocks') 
    THEN '✅ blocks' ELSE '❌ blocks MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'transactions') 
    THEN '✅ transactions' ELSE '❌ transactions MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'migrations_status') 
    THEN '✅ migrations_status' ELSE '❌ migrations_status MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'addresses') 
    THEN '✅ addresses' ELSE '❌ addresses MISSING' END,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'smart_contracts') 
    THEN '✅ smart_contracts' ELSE '❌ smart_contracts MISSING' END;
" 2>&1

echo ""

# Step 5: Restart Blockscout
echo "=== Step 5: Restarting Blockscout ==="
$EXEC_PREFIX docker restart $BLOCKSCOUT_CONTAINER
echo "Waiting for Blockscout to start..."
sleep 30

# Step 6: Check if it's running
echo ""
echo "=== Step 6: Checking container status ==="
if $EXEC_PREFIX docker ps | grep -q blockscout; then
    echo "✅ Blockscout container is running"
    echo ""
    echo "Recent logs:"
    $EXEC_PREFIX docker logs $BLOCKSCOUT_CONTAINER 2>&1 | tail -20
else
    echo "❌ Blockscout container is not running"
    echo ""
    echo "Check logs:"
    $EXEC_PREFIX docker logs $BLOCKSCOUT_CONTAINER 2>&1 | tail -30
fi

echo ""
echo "=========================================="
echo "Migration fix complete!"
echo "=========================================="

