#!/usr/bin/env bash
# Quick health check for Besu containers in temporary VM
# Returns exit code 0 if healthy, non-zero if issues found

set -euo pipefail

TEMP_VM_IP="${BESU_TEMP_IP:-192.168.11.90}"

# Check VM accessibility
if ! ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 "root@$TEMP_VM_IP" "echo 'ok'" >/dev/null 2>&1; then
    echo "ERROR: Cannot access VM"
    exit 1
fi

# Check Docker
if ! ssh "root@$TEMP_VM_IP" "docker ps" >/dev/null 2>&1; then
    echo "ERROR: Docker not accessible"
    exit 1
fi

# Count running containers
RUNNING=$(ssh "root@$TEMP_VM_IP" "docker ps --format '{{.Names}}' | grep '^besu-' | wc -l" 2>/dev/null || echo "0")

if [[ "$RUNNING" -lt 10 ]]; then
    echo "WARNING: Only $RUNNING Besu containers running (expected 12)"
    exit 1
fi

# Check if any containers are unhealthy
UNHEALTHY=$(ssh "root@$TEMP_VM_IP" "docker ps --format '{{.Names}} {{.Status}}' | grep 'besu-' | grep -v 'healthy\|Up' | wc -l" 2>/dev/null || echo "0")

if [[ "$UNHEALTHY" -gt 0 ]]; then
    echo "WARNING: $UNHEALTHY containers have issues"
    exit 1
fi

echo "OK: All containers healthy"
exit 0

