#!/bin/bash
# Fix Blockscout container restart issue
# Run this inside the Blockscout container

set -euo pipefail

echo "════════════════════════════════════════════════════════"
echo "Diagnosing and Fixing Blockscout Restart Issue"
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Check logs
echo "Step 1: Checking Blockscout logs..."
docker logs --tail 50 blockscout 2>&1 | head -30
echo ""

# Step 2: Check PostgreSQL
echo "Step 2: Checking PostgreSQL connection..."
docker exec blockscout-postgres pg_isready -U blockscout
echo ""

# Step 3: Check docker-compose.yml
echo "Step 3: Checking docker-compose.yml configuration..."
cd /opt/blockscout 2>/dev/null || cd /root/blockscout 2>/dev/null || (echo "Blockscout directory not found!" && exit 1)

if [ -f docker-compose.yml ]; then
    echo "✓ docker-compose.yml exists"
    echo ""
    echo "Current environment variables:"
    grep -E "ETHEREUM_JSONRPC|CHAIN_ID|DATABASE_URL|BLOCKSCOUT_HOST" docker-compose.yml | head -10
else
    echo "✗ docker-compose.yml not found!"
    exit 1
fi
echo ""

# Step 4: Stop containers
echo "Step 4: Stopping containers..."
docker-compose down 2>/dev/null || docker compose down 2>/dev/null || true
echo ""

# Step 5: Verify RPC connectivity
echo "Step 5: Testing RPC connectivity..."
RPC_TEST=$(curl -s -X POST "http://192.168.11.250:8545" \
    -H 'Content-Type: application/json' \
    -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null || echo "")
if echo "$RPC_TEST" | grep -q '"result"'; then
    echo "✓ RPC endpoint is accessible"
else
    echo "⚠ RPC endpoint may not be accessible"
    echo "Response: $RPC_TEST"
fi
echo ""

# Step 6: Fix docker-compose.yml - ensure no command override
echo "Step 6: Fixing docker-compose.yml..."
# Remove any command overrides that might be causing issues
sed -i '/^\s*command:/d' docker-compose.yml
sed -i '/^\s*entrypoint:/d' docker-compose.yml

# Ensure SECRET_KEY_BASE is set
if ! grep -q "SECRET_KEY_BASE" docker-compose.yml || grep -q "SECRET_KEY_BASE=\$" docker-compose.yml; then
    SECRET_KEY=$(openssl rand -hex 64)
    if grep -q "SECRET_KEY_BASE=PLACEHOLDER" docker-compose.yml; then
        sed -i "s|SECRET_KEY_BASE=PLACEHOLDER.*|SECRET_KEY_BASE=${SECRET_KEY}|" docker-compose.yml
    elif ! grep -q "^.*SECRET_KEY_BASE=" docker-compose.yml; then
        # Add SECRET_KEY_BASE to environment section
        sed -i '/environment:/a\      - SECRET_KEY_BASE='"${SECRET_KEY}" docker-compose.yml
    else
        # Replace existing SECRET_KEY_BASE
        sed -i 's|SECRET_KEY_BASE=.*|SECRET_KEY_BASE='"${SECRET_KEY}"'|' docker-compose.yml
    fi
fi

echo "✓ docker-compose.yml fixed"
echo ""

# Step 7: Start PostgreSQL first
echo "Step 7: Starting PostgreSQL..."
docker-compose up -d postgres || docker compose up -d postgres
echo "Waiting for PostgreSQL..."
for i in {1..30}; do
    if docker exec blockscout-postgres pg_isready -U blockscout >/dev/null 2>&1; then
        echo "✓ PostgreSQL ready"
        break
    fi
    echo -n "."
    sleep 2
done
echo ""
echo ""

# Step 8: Start Blockscout with logs
echo "Step 8: Starting Blockscout and monitoring logs..."
docker-compose up -d blockscout || docker compose up -d blockscout

echo "Waiting 10 seconds, then checking status..."
sleep 10

docker ps | grep blockscout

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

# Step 9: If still restarting, check specific issues
if docker ps -a | grep blockscout | grep -q "Restarting\|Exited"; then
    echo "════════════════════════════════════════════════════════"
    echo "Container still restarting. Checking common issues..."
    echo "════════════════════════════════════════════════════════"
    echo ""
    
    echo "Full error logs:"
    docker logs blockscout 2>&1 | tail -50
    echo ""
    
    echo "Checking database connection..."
    docker exec blockscout-postgres psql -U blockscout -d blockscout -c "SELECT version();" 2>&1 || echo "Database connection failed"
    echo ""
    
    echo "Checking environment variables in container:"
    docker inspect blockscout | grep -A 20 "Env" | head -25
    echo ""
fi

echo "════════════════════════════════════════════════════════"
echo "Diagnosis Complete"
echo "════════════════════════════════════════════════════════"
echo ""
echo "If container is still restarting, check:"
echo "  1. RPC endpoint is accessible: curl http://192.168.11.250:8545"
echo "  2. Database connection: docker exec blockscout-postgres pg_isready -U blockscout"
echo "  3. View full logs: docker logs -f blockscout"
echo ""

