#!/bin/bash

# Script to diagnose why Blockscout container is crashing
# Run from VMID 5000 or Proxmox host

set -euo pipefail

VMID=5000

echo "=========================================="
echo "Blockscout Crash Diagnosis"
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

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

# Check container status
echo "=== Container Status ==="
$EXEC_PREFIX docker inspect --format='Status: {{.State.Status}} | Exit Code: {{.State.ExitCode}} | Started: {{.State.StartedAt}} | Finished: {{.State.FinishedAt}}' $BLOCKSCOUT_CONTAINER
echo ""

# Check recent logs (last 50 lines)
echo "=== Recent Logs (Last 50 lines) ==="
$EXEC_PREFIX docker logs $BLOCKSCOUT_CONTAINER 2>&1 | tail -50
echo ""

# Check for specific errors
echo "=== Error Summary ==="
$EXEC_PREFIX docker logs $BLOCKSCOUT_CONTAINER 2>&1 | grep -i "error\|fatal\|exception\|crash\|panic" | tail -20 || echo "No obvious errors found in logs"
echo ""

# Check container configuration
echo "=== Container Configuration ==="
echo "Command:"
$EXEC_PREFIX docker inspect --format='{{.Config.Cmd}}' $BLOCKSCOUT_CONTAINER
echo ""
echo "Entrypoint:"
$EXEC_PREFIX docker inspect --format='{{.Config.Entrypoint}}' $BLOCKSCOUT_CONTAINER
echo ""

# Check environment variables
echo "=== Key Environment Variables ==="
$EXEC_PREFIX docker inspect --format='{{range .Config.Env}}{{println .}}{{end}}' $BLOCKSCOUT_CONTAINER | grep -E "DATABASE|POSTGRES|PORT|HOST" | head -10
echo ""

# Check if postgres is accessible
echo "=== Database Connectivity ==="
if $EXEC_PREFIX docker ps | grep -q postgres; then
    echo "✅ Postgres container is running"
    $EXEC_PREFIX docker exec blockscout-postgres psql -U blockscout -d blockscout -c "SELECT 1;" >/dev/null 2>&1 && \
      echo "✅ Database connection test successful" || \
      echo "❌ Database connection test failed"
else
    echo "❌ Postgres container is not running"
fi
echo ""

# Check port conflicts
echo "=== Port 4000 Check ==="
if $EXEC_PREFIX netstat -tlnp 2>/dev/null | grep -q ":4000 "; then
    echo "⚠️  Port 4000 is in use:"
    $EXEC_PREFIX netstat -tlnp 2>/dev/null | grep ":4000 "
else
    echo "✅ Port 4000 is available"
fi
echo ""

# Check docker-compose configuration
echo "=== Docker Compose Configuration ==="
if $EXEC_PREFIX test -f /opt/blockscout/docker-compose.yml; then
    echo "docker-compose.yml found"
    echo "Blockscout service configuration:"
    $EXEC_PREFIX grep -A 20 "blockscout:" /opt/blockscout/docker-compose.yml | head -25
else
    echo "⚠️  docker-compose.yml not found at /opt/blockscout"
fi
echo ""

# Recommendations
echo "=========================================="
echo "Diagnosis Complete"
echo "=========================================="
echo ""
echo "Common fixes:"
echo "1. If no startup command: Add 'command: bin/blockscout start' to docker-compose.yml"
echo "2. If database connection fails: Check DATABASE_URL environment variable"
echo "3. If port conflict: Change port mapping or stop conflicting service"
echo "4. If missing env vars: Check .env file or docker-compose.yml environment section"
echo ""

