#!/bin/bash
# Health check script for environments

set -e

ENVIRONMENT=$1
COLOR=${2:-green}  # green or blue for blue-green deployments

if [ -z "$ENVIRONMENT" ]; then
    echo "Usage: $0 <environment> [color]"
    exit 1
fi

echo "Running health checks for $ENVIRONMENT (color: $COLOR)..."

# Check if pods are ready
echo "Checking pod status..."
kubectl get pods -n besu-network -l color=$COLOR --no-headers | while read line; do
    STATUS=$(echo $line | awk '{print $3}')
    if [ "$STATUS" != "Running" ]; then
        echo "❌ Pod not running: $line"
        exit 1
    fi
done

# Check if services are accessible
echo "Checking service endpoints..."
ENDPOINTS=$(kubectl get endpoints -n besu-network -l color=$COLOR --no-headers | wc -l)
if [ "$ENDPOINTS" -eq 0 ]; then
    echo "❌ No endpoints found"
    exit 1
fi

# Check RPC endpoint (if RPC nodes exist)
if kubectl get pods -n besu-network -l role=rpc,color=$COLOR --no-headers | grep -q .; then
    echo "Checking RPC endpoint..."
    RPC_POD=$(kubectl get pods -n besu-network -l role=rpc,color=$COLOR -o jsonpath='{.items[0].metadata.name}')
    if kubectl exec -n besu-network $RPC_POD -- curl -s http://localhost:8545 -X POST \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' | grep -q result; then
        echo "✅ RPC endpoint responding"
    else
        echo "❌ RPC endpoint not responding"
        exit 1
    fi
fi

# Check validator health
if kubectl get pods -n besu-network -l role=validator,color=$COLOR --no-headers | grep -q .; then
    echo "Checking validator health..."
    VALIDATOR_POD=$(kubectl get pods -n besu-network -l role=validator,color=$COLOR -o jsonpath='{.items[0].metadata.name}')
    BLOCK_NUMBER=$(kubectl exec -n besu-network $VALIDATOR_POD -- curl -s http://localhost:8545 -X POST \
        -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' | grep -o '"result":"[^"]*"' | cut -d'"' -f4)
    
    if [ -n "$BLOCK_NUMBER" ]; then
        echo "✅ Validator synced to block: $BLOCK_NUMBER"
    else
        echo "❌ Validator not synced"
        exit 1
    fi
fi

echo "✅ All health checks passed for $ENVIRONMENT ($COLOR)"

