#!/usr/bin/env bash
# Generate static-nodes.json from all node keys
# This script extracts enode URLs from validator and other node keys

set -e

KEYS_DIR="/opt/docker-compose/keys"
OUTPUT_FILE="/opt/docker-compose/config/static-nodes.json"

# Node configuration mapping: key_file:host:port
declare -A NODES=(
    ["validator1.priv"]="10.1.1.4:30303"
    ["validator2.priv"]="10.2.1.4:30303"
    ["validator3.priv"]="10.3.1.4:30303"
    ["validator4.priv"]="10.4.1.4:30303"
    ["rpc-perm.priv"]="10.1.1.4:30304"
    ["rpc-core.priv"]="10.2.1.4:30304"
    ["member1.priv"]="10.3.1.4:30304"
    ["member2.priv"]="10.4.1.4:30304"
    ["rpc-public.priv"]="10.5.1.4:30303"
)

echo "[" > "$OUTPUT_FILE"
first=true

for key_file in "${!NODES[@]}"; do
    key_path="$KEYS_DIR/$key_file"
    if [ ! -f "$key_path" ]; then
        echo "Warning: Key file not found: $key_path" >&2
        continue
    fi
    
    IFS=':' read -r host port <<< "${NODES[$key_file]}"
    
    # Extract public key and generate enode
    # Using Besu to export the public key
    pubkey=$(docker run --rm -v "$KEYS_DIR:/keys" hyperledger/besu:23.10.0 \
        besu public-key export --node-private-key-file="/keys/$key_file" 2>/dev/null | \
        grep -oP '0x[a-fA-F0-9]{128}' | head -1)
    
    if [ -z "$pubkey" ]; then
        echo "Warning: Could not extract public key from $key_file" >&2
        continue
    fi
    
    # Generate enode URL: enode://PUBKEY@HOST:PORT
    enode="enode://${pubkey}@${host}:${port}"
    
    if [ "$first" = true ]; then
        first=false
    else
        echo "," >> "$OUTPUT_FILE"
    fi
    
    echo "  \"$enode\"" >> "$OUTPUT_FILE"
done

echo "]" >> "$OUTPUT_FILE"
echo "Generated static-nodes.json with $(grep -c enode "$OUTPUT_FILE" || echo 0) nodes"

