#!/bin/bash
# Extract enode from running Besu node via JSON-RPC
# Usage: RPC_URL=http://192.168.11.13:8545 NODE_IP=192.168.11.13 bash extract-enode-from-rpc.sh

set -euo pipefail

RPC_URL="${RPC_URL:-http://localhost:8545}"
NODE_IP="${NODE_IP:-}"

# Get node info via JSON-RPC
RESPONSE=$(curl -s -X POST \
    -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"admin_nodeInfo","params":[],"id":1}' \
    "${RPC_URL}")

# Check for errors
if echo "$RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); sys.exit(0 if 'error' not in data else 1)" 2>/dev/null; then
    ERROR_MSG=$(echo "$RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); print(data.get('error', {}).get('message', 'Unknown error'))" 2>/dev/null)
    if [[ -n "$ERROR_MSG" ]]; then
        echo "ERROR: JSON-RPC error: $ERROR_MSG" >&2
        echo "NOTE: Ensure RPC is enabled with --rpc-http-api=ADMIN,NET" >&2
        exit 1
    fi
fi

# Extract enode
ENODE=$(echo "$RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('result', {}).get('enode', ''))" 2>/dev/null)

if [[ -z "$ENODE" ]] || [[ "$ENODE" == "None" ]] || [[ "$ENODE" == "null" ]]; then
    echo "ERROR: Could not extract enode from admin_nodeInfo" >&2
    echo "Response: $RESPONSE" >&2
    exit 1
fi

# Extract and validate node ID
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 "Enode: $ENODE" >&2
    exit 1
fi

# Extract IP and port
ENODE_IP=$(echo "$ENODE" | sed 's|.*@||' | cut -d':' -f1)
ENODE_PORT=$(echo "$ENODE" | sed 's|.*:||')

# Verify IP if provided
if [[ -n "$NODE_IP" ]] && [[ "$ENODE_IP" != "$NODE_IP" ]]; then
    echo "WARNING: Enode IP ($ENODE_IP) does not match expected IP ($NODE_IP)" >&2
    echo "NOTE: Check --p2p-host and --nat-method configuration" >&2
fi

echo "$ENODE"
