#!/bin/bash
# Complete fix for Blockscout configuration issues
# Fixes SECRET_KEY_BASE and BLOCKSCOUT_HOST in docker-compose.yml

set -euo pipefail

echo "════════════════════════════════════════════════════════"
echo "Fixing Blockscout Configuration"
echo "════════════════════════════════════════════════════════"

# Navigate to Blockscout directory
cd /opt/blockscout 2>/dev/null || cd /root/blockscout 2>/dev/null || (echo "Error: Blockscout directory not found" && exit 1)

# Generate actual secret key
SECRET_KEY=$(openssl rand -hex 64)

# Fix SECRET_KEY_BASE - replace any variation
sed -i "s|SECRET_KEY_BASE=\$(openssl rand -hex 64)|SECRET_KEY_BASE=${SECRET_KEY}|g" docker-compose.yml
sed -i "s|SECRET_KEY_BASE=\${SECRET_KEY:-.*}|SECRET_KEY_BASE=${SECRET_KEY}|g" docker-compose.yml
sed -i "s|SECRET_KEY_BASE=.*openssl.*|SECRET_KEY_BASE=${SECRET_KEY}|g" docker-compose.yml

# Fix BLOCKSCOUT_HOST
sed -i "s|BLOCKSCOUT_HOST=localhost|BLOCKSCOUT_HOST=192.168.11.140|g" docker-compose.yml
sed -i "s|BLOCKSCOUT_HOST=\${BLOCKSCOUT_HOST:-localhost}|BLOCKSCOUT_HOST=192.168.11.140|g" docker-compose.yml
sed -i "s|BLOCKSCOUT_HOST=\${BLOCKSCOUT_HOST}|BLOCKSCOUT_HOST=192.168.11.140|g" docker-compose.yml

# Fix other environment variable defaults
sed -i "s|CHAIN_ID=\${CHAIN_ID:-138}|CHAIN_ID=138|g" docker-compose.yml
sed -i "s|DATABASE_URL=postgresql://blockscout:\${DB_PASSWORD:-blockscout}@postgres:5432/blockscout|DATABASE_URL=postgresql://blockscout:blockscout@postgres:5432/blockscout|g" docker-compose.yml
sed -i "s|ETHEREUM_JSONRPC_WS_URL=\${WS_URL:-ws://192.168.11.250:8546}|ETHEREUM_JSONRPC_WS_URL=ws://192.168.11.250:8546|g" docker-compose.yml

# Remove any command/entrypoint overrides
sed -i '/^\s*command:/d' docker-compose.yml
sed -i '/^\s*entrypoint:/d' docker-compose.yml

echo "✓ Configuration fixed"
echo ""
echo "Updated values:"
grep -E "SECRET_KEY_BASE|BLOCKSCOUT_HOST|CHAIN_ID" docker-compose.yml | grep -v "^#" | head -5

echo ""
echo "Stopping containers..."
docker-compose down 2>/dev/null || docker compose down 2>/dev/null || true

echo "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
    sleep 2
done

echo ""
echo "Starting Blockscout..."
docker-compose up -d blockscout || docker compose up -d blockscout

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

docker ps | grep blockscout

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

