#!/usr/bin/env bash
# Update static-nodes.json in all containers

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh"

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 "Updating static-nodes.json in all containers..."

# Collect all node enodes
ENODES=()

# Process validators
for var in $(grep "^VALIDATOR_.*_IP=" "$INVENTORY_FILE" 2>/dev/null); do
    ip=$(echo "$var" | cut -d'=' -f2)
    # Get enode from container (if running)
    vmid_var=$(echo "$var" | sed 's/_IP=/_VMID=/')
    vmid=$(grep "$vmid_var" "$INVENTORY_FILE" | cut -d'=' -f2)
    
    if pct status "$vmid" 2>/dev/null | grep -q running; then
        enode=$(pct exec "$vmid" -- cat /opt/besu/enode 2>/dev/null || echo "")
        if [[ -n "$enode" ]]; then
            # Replace IP in enode
            enode=$(echo "$enode" | sed "s/@.*:/@${ip}:30303/")
            ENODES+=("$enode")
        fi
    fi
done

# Process sentries
for var in $(grep "^SENTRY_.*_IP=" "$INVENTORY_FILE" 2>/dev/null); do
    ip=$(echo "$var" | cut -d'=' -f2)
    vmid_var=$(echo "$var" | sed 's/_IP=/_VMID=/')
    vmid=$(grep "$vmid_var" "$INVENTORY_FILE" | cut -d'=' -f2)
    
    if pct status "$vmid" 2>/dev/null | grep -q running; then
        enode=$(pct exec "$vmid" -- cat /opt/besu/enode 2>/dev/null || echo "")
        if [[ -n "$enode" ]]; then
            enode=$(echo "$enode" | sed "s/@.*:/@${ip}:30303/")
            ENODES+=("$enode")
        fi
    fi
done

if [[ ${#ENODES[@]} -eq 0 ]]; then
    log_warn "No enodes found. Containers may need to be started first."
    exit 0
fi

# Create static-nodes.json
STATIC_NODES_JSON="/tmp/static-nodes.json"
cat > "$STATIC_NODES_JSON" <<EOF
[
$(printf '  "%s",\n' "${ENODES[@]}" | sed '$s/,$//')
]
EOF

log_info "Generated static-nodes.json with ${#ENODES[@]} nodes"

# Copy to all containers
for var in $(grep "_VMID=" "$INVENTORY_FILE" 2>/dev/null); do
    vmid=$(echo "$var" | cut -d'=' -f2)
    
    if pct status "$vmid" 2>/dev/null | grep -q running; then
        log_info "Updating static-nodes.json in container $vmid..."
        copy_to_container "$vmid" "$STATIC_NODES_JSON" "/etc/besu/static-nodes.json"
        
        # Restart service if running
        pct exec "$vmid" -- systemctl restart besu-validator.service 2>/dev/null || \
        pct exec "$vmid" -- systemctl restart besu-sentry.service 2>/dev/null || \
        pct exec "$vmid" -- systemctl restart besu-rpc.service 2>/dev/null || true
    fi
done

rm -f "$STATIC_NODES_JSON"

log_success "Static nodes updated in all containers"

