#!/bin/bash
# Extract enode from Besu nodekey file using Besu CLI
# Usage: DATA_PATH=/data/besu NODE_IP=192.168.11.13 bash extract-enode-from-nodekey.sh

set -euo pipefail

DATA_PATH="${DATA_PATH:-/data/besu}"
BESU_BIN="${BESU_BIN:-/opt/besu/bin/besu}"
NODE_IP="${NODE_IP:-}"
P2P_PORT="${P2P_PORT:-30303}"

# Find nodekey file
NODEKEY_FILE=""
for path in "${DATA_PATH}/key" "${DATA_PATH}/nodekey" "/keys/besu/nodekey"; do
    if [[ -f "$path" ]]; then
        NODEKEY_FILE="$path"
        break
    fi
done

if [[ -z "$NODEKEY_FILE" ]]; then
    echo "ERROR: Nodekey file not found in ${DATA_PATH}/key, ${DATA_PATH}/nodekey, or /keys/besu/nodekey" >&2
    exit 1
fi

echo "Found nodekey: $NODEKEY_FILE" >&2

# Generate enode using Besu CLI
if [[ -n "$NODE_IP" ]]; then
    ENODE=$("${BESU_BIN}" public-key export --node-private-key-file="${NODEKEY_FILE}" --format=enode 2>/dev/null | sed "s/@[0-9.]*:/@${NODE_IP}:/")
else
    ENODE=$("${BESU_BIN}" public-key export --node-private-key-file="${NODEKEY_FILE}" --format=enode 2>/dev/null)
fi

if [[ -z "$ENODE" ]]; then
    echo "ERROR: Failed to generate enode from nodekey" >&2
    exit 1
fi

# Extract and validate node ID length
NODE_ID=$(echo "$ENODE" | sed 's|^enode://||' | cut -d'@' -f1 | tr '[:upper:]' '[:lower:]')
NODE_ID_LEN=${#NODE_ID}

if [[ "$NODE_ID_LEN" -ne 128 ]]; then
    echo "ERROR: Invalid node ID length: $NODE_ID_LEN (expected 128)" >&2
    echo "Node ID: ${NODE_ID:0:32}...${NODE_ID: -32}" >&2
    exit 1
fi

# Validate hex format
if ! echo "$NODE_ID" | grep -qE '^[0-9a-f]{128}$'; then
    echo "ERROR: Node ID contains invalid hex characters" >&2
    exit 1
fi

echo "$ENODE"
