#!/usr/bin/env bash
# Investigate Besu Configuration - Run this ON the RPC node
# This script should be run directly on besu-rpc-1

set -euo pipefail

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     INVESTIGATING BESU CONFIGURATION                         ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Running on: $(hostname)"
echo ""

# Step 1: Find Besu config files
echo "═══════════════════════════════════════════════════════════════"
echo "Step 1: Finding Besu configuration files"
echo "═══════════════════════════════════════════════════════════════"
echo ""

CONFIG_FILES=$(find /etc -name '*besu*' -o -name '*.toml' 2>/dev/null | grep -E 'besu|toml' | head -20)
if [ -n "$CONFIG_FILES" ]; then
    echo "Found config files:"
    echo "$CONFIG_FILES"
else
    echo "No config files found in /etc"
    echo "Searching in other locations..."
    find /opt /usr /home -name '*besu*.toml' -o -name 'config*.toml' 2>/dev/null | head -10
fi
echo ""

# Step 2: Check which config Besu is using
echo "═══════════════════════════════════════════════════════════════"
echo "Step 2: Checking which config file Besu is using"
echo "═══════════════════════════════════════════════════════════════"
echo ""

BESU_PROCESS=$(ps aux | grep besu | grep -v grep | head -1)
if [ -n "$BESU_PROCESS" ]; then
    echo "Besu process found:"
    echo "$BESU_PROCESS"
    echo ""
    CONFIG_FILE=$(echo "$BESU_PROCESS" | grep -oE '--config-file=[^ ]+' | cut -d'=' -f2 || echo "")
    if [ -n "$CONFIG_FILE" ]; then
        echo "Config file from process: $CONFIG_FILE"
    fi
else
    echo "Besu process not found (may not be running)"
fi
echo ""

# Step 3: Check systemd service
echo "═══════════════════════════════════════════════════════════════"
echo "Step 3: Checking systemd service configuration"
echo "═══════════════════════════════════════════════════════════════"
echo ""

SERVICE_FILES=$(find /etc/systemd/system -name '*besu*.service' 2>/dev/null)
if [ -n "$SERVICE_FILES" ]; then
    for service_file in $SERVICE_FILES; do
        echo "Service file: $service_file"
        echo "ExecStart line:"
        grep "ExecStart" "$service_file" || echo "  No ExecStart found"
        echo ""
    done
else
    echo "No Besu service files found"
fi
echo ""

# Step 4: Read the actual config file
echo "═══════════════════════════════════════════════════════════════"
echo "Step 4: Reading Besu configuration"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Try common locations
CONFIG_LOCATIONS=(
    "/etc/besu/config-rpc-core.toml"
    "/etc/besu/config-rpc.toml"
    "/etc/besu/besu-config.toml"
    "/opt/besu/config/config.toml"
    "/data/besu/config.toml"
)

CONFIG_FOUND=""
for config_loc in "${CONFIG_LOCATIONS[@]}"; do
    if [ -f "$config_loc" ]; then
        echo "✅ Found config file: $config_loc"
        CONFIG_FOUND="$config_loc"
        break
    fi
done

if [ -z "$CONFIG_FOUND" ]; then
    echo "⚠️  Standard config locations not found"
    echo "Searching for any .toml files..."
    find /etc /opt /data -name "*.toml" 2>/dev/null | head -10
else
    echo ""
    echo "Configuration file contents:"
    echo "───────────────────────────────────────────────────────────"
    cat "$CONFIG_FOUND"
    echo "───────────────────────────────────────────────────────────"
    echo ""
    
    # Check for rpc-http-api
    echo "Current rpc-http-api setting:"
    grep "rpc-http-api" "$CONFIG_FOUND" || echo "  rpc-http-api not found"
    echo ""
    
    # Check for rpc-ws-api
    echo "Current rpc-ws-api setting:"
    grep "rpc-ws-api" "$CONFIG_FOUND" || echo "  rpc-ws-api not found"
    echo ""
    
    # Check if DEBUG is enabled
    if grep -q "DEBUG" "$CONFIG_FOUND"; then
        echo "✅ DEBUG API appears to be in config"
    else
        echo "❌ DEBUG API is NOT in config"
        echo ""
        echo "To enable DEBUG API:"
        echo "  1. Edit: $CONFIG_FOUND"
        echo "  2. Add \"DEBUG\" and \"TRACE\" to rpc-http-api array"
        echo "  3. Restart: systemctl restart besu-rpc"
    fi
fi
echo ""

# Step 5: Check Besu service status
echo "═══════════════════════════════════════════════════════════════"
echo "Step 5: Checking Besu service status"
echo "═══════════════════════════════════════════════════════════════"
echo ""

systemctl status besu-rpc --no-pager | head -20 || echo "Service not found or not running"
echo ""

# Step 6: Check if DEBUG API is actually enabled (test)
echo "═══════════════════════════════════════════════════════════════"
echo "Step 6: Testing if DEBUG API is enabled"
echo "═══════════════════════════════════════════════════════════════"
echo ""

DEBUG_TEST=$(curl -s -X POST -H "Content-Type: application/json" \
  --data '{"jsonrpc":"2.0","method":"debug_traceTransaction","params":["0x0000000000000000000000000000000000000000000000000000000000000000",{"tracer":"callTracer"}],"id":1}' \
  http://localhost:8545 2>&1)

if echo "$DEBUG_TEST" | grep -q "Method not enabled"; then
    echo "❌ DEBUG API is NOT enabled"
elif echo "$DEBUG_TEST" | grep -q "error"; then
    echo "✅ DEBUG API is enabled (returned error for invalid tx, which is expected)"
    echo "$DEBUG_TEST" | jq '.' 2>/dev/null || echo "$DEBUG_TEST"
else
    echo "✅ DEBUG API appears to be enabled"
    echo "$DEBUG_TEST" | jq '.' 2>/dev/null || echo "$DEBUG_TEST"
fi
echo ""

# Summary
echo "═══════════════════════════════════════════════════════════════"
echo "SUMMARY"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -n "$CONFIG_FOUND" ]; then
    echo "Config file: $CONFIG_FOUND"
    echo ""
    echo "To enable DEBUG API, edit the file and add DEBUG/TRACE:"
    echo "  nano $CONFIG_FOUND"
    echo ""
    echo "Find: rpc-http-api=[...]"
    echo "Add: \"DEBUG\", \"TRACE\" to the array"
    echo ""
    echo "Then restart:"
    echo "  systemctl restart besu-rpc"
else
    echo "⚠️  Could not find Besu configuration file"
    echo "   Please locate it manually and update rpc-http-api"
fi
echo ""

