#!/bin/bash
# Check peer connections on Besu node
# Usage: bash besu-verify-peers.sh <rpc-url>
# Example: bash besu-verify-peers.sh http://192.168.11.13:8545

set -euo pipefail

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

echo "Checking peers on: $RPC_URL"
echo ""

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

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

if [[ "$ENODE" == "ERROR" ]] || [[ -z "$ENODE" ]]; then
    echo "ERROR: Could not get node info. Is RPC enabled with ADMIN API?" >&2
    exit 1
fi

echo "This node's enode:"
echo "$ENODE"
echo ""

# Get peers
PEERS_RESPONSE=$(curl -s -X POST \
    -H "Content-Type: application/json" \
    --data '{"jsonrpc":"2.0","method":"admin_peers","params":[],"id":2}' \
    "${RPC_URL}")

PEERS=$(echo "$PEERS_RESPONSE" | python3 -c "import sys, json; peers=json.load(sys.stdin).get('result', []); print(len(peers))" 2>/dev/null)
PEERS_LIST=$(echo "$PEERS_RESPONSE" | python3 -c "import sys, json; peers=json.load(sys.stdin).get('result', []); [print(f\"  - {p.get('enode', 'unknown')}\") for p in peers]" 2>/dev/null)

echo "Connected peers: $PEERS"
echo ""

if [[ "$PEERS" == "0" ]]; then
    echo "⚠️  NO PEERS CONNECTED"
    echo ""
    echo "Possible causes:"
    echo "1. Other nodes not running"
    echo "2. Firewall blocking port 30303"
    echo "3. Malformed enodes in allowlist"
    echo "4. Discovery disabled and static-nodes.json incorrect"
    echo "5. Permissions enabled but allowlist missing this node"
    echo "6. Network connectivity issues"
else
    echo "Peer list:"
    echo "$PEERS_LIST"
fi

# Check peer details if jq available
if [[ "$PEERS" != "0" ]] && command -v jq >/dev/null 2>&1; then
    echo ""
    echo "Peer details:"
    echo "$PEERS_RESPONSE" | jq -r '.result[] | "  - \(.id): \(.name) @ \(.network.remoteAddress)"'
fi
