#!/usr/bin/env bash

# Monitor Besu nodes on VMs
# This script monitors Besu nodes and displays status

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Configuration
VM_IPS="${VM_IPS:-}"
RESOURCE_GROUP="${RESOURCE_GROUP:-defi-oracle-mainnet-rg}"


log_success "Monitoring Besu nodes..."

# Get VM IPs from Azure if not provided
if [ -z "$VM_IPS" ]; then
    log_warn "Getting VM IPs from Azure..."
    VM_IPS=$(az vm list-ip-addresses --resource-group "$RESOURCE_GROUP" --query "[].virtualMachine.network.publicIpAddresses[0].ipAddress" -o tsv 2>/dev/null || echo "")
    
    if [ -z "$VM_IPS" ]; then
        log_error "Error: Could not get VM IPs from Azure"
        echo "Please set VM_IPS environment variable or ensure Azure CLI is configured"
        exit 1
    fi
fi

# Monitor each VM
for VM_IP in $VM_IPS; do
    if [ -z "$VM_IP" ] || [ "$VM_IP" == "None" ]; then
        continue
    fi
    
    log_warn "Monitoring VM: $VM_IP"
    
    # Check VM accessibility
    if ! ping -c 1 -W 2 "$VM_IP" &> /dev/null; then
        log_error "✗ VM $VM_IP is not accessible"
        continue
    fi
    
    # Check Docker
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no besuadmin@$VM_IP "command -v docker &> /dev/null" 2>/dev/null; then
        log_success "✓ Docker is installed"
    else
        log_error "✗ Docker is not installed"
        continue
    fi
    
    # Check Besu container
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no besuadmin@$VM_IP "docker ps | grep -q besu" 2>/dev/null; then
        log_success "✓ Besu container is running"
        
        # Get container status
        CONTAINER_STATUS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no besuadmin@$VM_IP "docker ps --filter 'name=besu' --format '{{.Names}} {{.Status}}'" 2>/dev/null || echo "")
        log_warn "  Container: $CONTAINER_STATUS"
    else
        log_error "✗ Besu container is not running"
        continue
    fi
    
    # Check metrics endpoint
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no besuadmin@$VM_IP "curl -s http://localhost:9545/metrics | grep -q besu" 2>/dev/null; then
        log_success "✓ Metrics endpoint is accessible"
    else
        log_warn "⚠ Metrics endpoint is not accessible"
    fi
    
    # Get block number (if RPC node)
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no besuadmin@$VM_IP "docker ps | grep -q rpc" 2>/dev/null; then
        BLOCK_NUMBER=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no besuadmin@$VM_IP "curl -s -X POST -H 'Content-Type: application/json' --data '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}' http://localhost:8545 | jq -r '.result'" 2>/dev/null || echo "unknown")
        log_warn "  Block number: $BLOCK_NUMBER"
    fi
    
done

log_success "Monitoring complete!"

