#!/usr/bin/env bash
# Flush mempools on all Besu nodes (validators, sentries, RPC)
# This script must be run on the Proxmox host
# Usage: ./flush-all-mempools-proxmox.sh

set -euo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_detail() { echo -e "${CYAN}[DETAIL]${NC} $1"; }

# Check if pct is available
if ! command -v pct &>/dev/null; then
    log_error "This script must be run on the Proxmox host (pct command not found)"
    exit 1
fi

# All Besu nodes
VALIDATORS=(1000 1001 1002 1003 1004)
SENTRIES=(1500 1501 1502 1503)
RPC_NODES=(2500 2501 2502)

echo "========================================="
echo "Flush All Besu Mempools"
echo "========================================="
echo ""

# Function to restart Besu service
restart_besu_service() {
    local vmid=$1
    local service_name=$2
    
    if ! pct status "$vmid" 2>/dev/null | grep -q "running"; then
        log_warn "⚠ VMID $vmid: Container not running - skipping"
        return 1
    fi
    
    log_info "VMID $vmid: Restarting $service_name..."
    
    if pct exec "$vmid" -- systemctl restart "$service_name" 2>/dev/null; then
        log_success "✓ Service restart command sent"
        sleep 2
        return 0
    else
        log_error "✗ Failed to restart service"
        return 1
    fi
}

# Restart validators
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_info "Validators (1000-1004)"
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
VALIDATOR_SUCCESS=0
for vmid in "${VALIDATORS[@]}"; do
    if restart_besu_service "$vmid" "besu-validator.service"; then
        ((VALIDATOR_SUCCESS++))
    fi
done
log_info "Validators restarted: $VALIDATOR_SUCCESS/${#VALIDATORS[@]}"
echo ""

# Restart sentries
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_info "Sentries (1500-1503)"
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
SENTRY_SUCCESS=0
for vmid in "${SENTRIES[@]}"; do
    if restart_besu_service "$vmid" "besu-sentry.service"; then
        ((SENTRY_SUCCESS++))
    fi
done
log_info "Sentries restarted: $SENTRY_SUCCESS/${#SENTRIES[@]}"
echo ""

# Restart RPC nodes
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_info "RPC Nodes (2500-2502)"
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
RPC_SUCCESS=0
for vmid in "${RPC_NODES[@]}"; do
    if restart_besu_service "$vmid" "besu-rpc.service"; then
        ((RPC_SUCCESS++))
    fi
done
log_info "RPC nodes restarted: $RPC_SUCCESS/${#RPC_NODES[@]}"
echo ""

# Summary
TOTAL_SUCCESS=$((VALIDATOR_SUCCESS + SENTRY_SUCCESS + RPC_SUCCESS))
TOTAL_NODES=$((${#VALIDATORS[@]} + ${#SENTRIES[@]} + ${#RPC_NODES[@]}))

echo "========================================="
echo "Summary"
echo "========================================="
echo ""
log_success "✓ Successfully restarted: $TOTAL_SUCCESS/$TOTAL_NODES nodes"
echo ""

log_info "Waiting 15 seconds for services to stabilize..."
sleep 15

log_info "Verifying services are running..."
VERIFIED=0
for vmid in "${VALIDATORS[@]}" "${SENTRIES[@]}" "${RPC_NODES[@]}"; do
    if pct status "$vmid" 2>/dev/null | grep -q "running"; then
        if pct exec "$vmid" -- pgrep -f "besu" >/dev/null 2>&1; then
            log_success "✓ VMID $vmid: Besu running"
            ((VERIFIED++))
        else
            log_warn "⚠ VMID $vmid: Besu process not found"
        fi
    fi
done

echo ""
log_success "========================================="
log_success "Mempool Flush Complete!"
log_success "========================================="
log_info ""
log_info "Verified: $VERIFIED/$TOTAL_NODES nodes running Besu"
log_info ""
log_info "Next steps:"
log_info "  1. Wait for all nodes to sync"
log_info "  2. Run: ./scripts/configure-ethereum-mainnet-final.sh"
log_info ""

