#!/usr/bin/env bash
# Upgrade all Besu nodes in rolling fashion

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh"

BESU_VERSION="${1:-23.10.0}"

load_config

# Load inventory
INVENTORY_FILE="$PROJECT_ROOT/config/inventory.conf"
if [[ ! -f "$INVENTORY_FILE" ]]; then
    error_exit "Inventory file not found: $INVENTORY_FILE"
fi

source "$INVENTORY_FILE"

log_info "Upgrading all nodes to Besu version $BESU_VERSION"
log_info "This will perform a rolling upgrade (one node at a time)"

# Get all VMIDs
ALL_VMIDS=()

# Add validators
for var in $(grep "^VALIDATOR_.*_VMID=" "$INVENTORY_FILE" 2>/dev/null); do
    vmid=$(echo "$var" | cut -d'=' -f2)
    ALL_VMIDS+=("$vmid")
done

# Add sentries
for var in $(grep "^SENTRY_.*_VMID=" "$INVENTORY_FILE" 2>/dev/null); do
    vmid=$(echo "$var" | cut -d'=' -f2)
    ALL_VMIDS+=("$vmid")
done

# Add RPC nodes
for var in $(grep "^RPC_.*_VMID=" "$INVENTORY_FILE" 2>/dev/null); do
    vmid=$(echo "$var" | cut -d'=' -f2)
    ALL_VMIDS+=("$vmid")
done

if [[ ${#ALL_VMIDS[@]} -eq 0 ]]; then
    error_exit "No nodes found in inventory"
fi

log_info "Found ${#ALL_VMIDS[@]} nodes to upgrade"

# Confirm
read -p "Continue with rolling upgrade? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    log_info "Upgrade cancelled"
    exit 0
fi

# Upgrade each node
SUCCESS=0
FAILED=0

for vmid in "${ALL_VMIDS[@]}"; do
    log_info ""
    log_info "Upgrading node $vmid..."
    
    if "$SCRIPT_DIR/upgrade-node.sh" "$vmid" "$BESU_VERSION"; then
        SUCCESS=$((SUCCESS + 1))
        log_info "Waiting 30 seconds before next upgrade..."
        sleep 30
    else
        FAILED=$((FAILED + 1))
        log_error "Upgrade failed for node $vmid"
        read -p "Continue with remaining nodes? (y/N) " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_warn "Upgrade aborted by user"
            break
        fi
    fi
done

log_info ""
log_success "Upgrade completed: $SUCCESS successful, $FAILED failed"

