#!/bin/bash

# Script to verify Blockscout database configuration and tables
# Run from Proxmox host or inside VMID 5000

set -euo pipefail

VMID=5000

echo "=========================================="
echo "Blockscout Database Verification"
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
    # Inside LXC container
    echo "Running inside VMID 5000"
    EXEC_PREFIX=""
else
    # On Proxmox host
    echo "Running from Proxmox host, executing in VMID 5000"
    EXEC_PREFIX="pct exec $VMID --"
fi

# Verify database credentials
echo "=== Database Credentials ==="
$EXEC_PREFIX docker exec -it blockscout-postgres env | grep -E 'POSTGRES_(USER|DB|PASSWORD)' || {
    echo "❌ Cannot access blockscout-postgres container"
    exit 1
}
echo ""

# Test database connection
echo "=== Database Connection Test ==="
$EXEC_PREFIX docker exec -it blockscout-postgres psql -U blockscout -d blockscout -c "SELECT version();" 2>&1 | head -3
if [ $? -eq 0 ]; then
    echo "✅ Database connection successful"
else
    echo "❌ Database connection failed"
    exit 1
fi
echo ""

# Check for critical tables
echo "=== Critical Tables Check ==="
$EXEC_PREFIX docker exec -it blockscout-postgres psql -U blockscout -d blockscout << 'SQL'
SELECT 
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'blocks') 
    THEN '✅ blocks' ELSE '❌ blocks MISSING' END as blocks,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'transactions') 
    THEN '✅ transactions' ELSE '❌ transactions MISSING' END as transactions,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'migrations_status') 
    THEN '✅ migrations_status' ELSE '❌ migrations_status MISSING' END as migrations_status,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'addresses') 
    THEN '✅ addresses' ELSE '❌ addresses MISSING' END as addresses,
  CASE WHEN EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'smart_contracts') 
    THEN '✅ smart_contracts' ELSE '❌ smart_contracts MISSING' END as smart_contracts;
SQL

echo ""

# Count total tables
echo "=== Database Statistics ==="
$EXEC_PREFIX docker exec -it blockscout-postgres psql -U blockscout -d blockscout -c "
SELECT 
  COUNT(*) as total_tables,
  (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('blocks', 'transactions', 'migrations_status')) as critical_tables_exist
FROM information_schema.tables 
WHERE table_schema = 'public';
"

echo ""
echo "=========================================="
echo "Verification complete!"
echo "=========================================="

