#!/usr/bin/env bash
# Enable DEBUG API on Besu RPC Node
# Run this script ON the RPC node (besu-rpc-1)

set -euo pipefail

CONFIG_FILE="/etc/besu/config-rpc-core.toml"

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     ENABLING DEBUG API IN BESU CONFIGURATION                 ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Config file: $CONFIG_FILE"
echo ""

# Check if config file exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo "❌ Config file not found: $CONFIG_FILE"
    echo ""
    echo "Available config files:"
    ls -la /etc/besu/*.toml 2>/dev/null || echo "No config files found"
    exit 1
fi

echo "Step 1: Checking current configuration..."
echo "───────────────────────────────────────────────────────────"
CURRENT_API=$(grep "rpc-http-api" "$CONFIG_FILE" | head -1)
echo "Current: $CURRENT_API"
echo ""

# Check if DEBUG is already enabled
if echo "$CURRENT_API" | grep -q "DEBUG"; then
    echo "✅ DEBUG API is already enabled in configuration"
    echo ""
    echo "Checking if service needs restart..."
    if systemctl is-active --quiet besu-rpc; then
        echo "⚠️  Service is running. Restarting to ensure DEBUG API is active..."
        systemctl restart besu-rpc
        sleep 5
        echo "✅ Service restarted"
    else
        echo "⚠️  Service is not running"
    fi
    exit 0
fi

echo "Step 2: Creating backup..."
BACKUP_FILE="${CONFIG_FILE}.backup.$(date +%Y%m%d-%H%M%S)"
cp "$CONFIG_FILE" "$BACKUP_FILE"
echo "✅ Backup created: $BACKUP_FILE"
echo ""

echo "Step 3: Updating configuration..."
echo "───────────────────────────────────────────────────────────"

# Try different patterns to match the rpc-http-api line
if grep -q 'rpc-http-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN"\]' "$CONFIG_FILE"; then
    echo "Pattern 1: Found standard config"
    sed -i 's/rpc-http-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN"\]/rpc-http-api=["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN","DEBUG","TRACE"]/g' "$CONFIG_FILE"
elif grep -q 'rpc-http-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN","DEBUG","TRACE"\]' "$CONFIG_FILE"; then
    echo "✅ DEBUG and TRACE already in config"
elif grep -q 'rpc-http-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN","DEBUG"\]' "$CONFIG_FILE"; then
    echo "Pattern 2: Found config with DEBUG but missing TRACE"
    sed -i 's/rpc-http-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN","DEBUG"\]/rpc-http-api=["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN","DEBUG","TRACE"]/g' "$CONFIG_FILE"
else
    echo "⚠️  Could not match standard pattern. Showing current line:"
    grep "rpc-http-api" "$CONFIG_FILE" | head -1
    echo ""
    echo "Please edit manually:"
    echo "  nano $CONFIG_FILE"
    echo ""
    echo "Find the rpc-http-api line and add \"DEBUG\", \"TRACE\" to the array"
    exit 1
fi

echo "✅ Configuration updated"
echo ""

echo "Step 4: Verifying update..."
echo "───────────────────────────────────────────────────────────"
UPDATED_API=$(grep "rpc-http-api" "$CONFIG_FILE" | head -1)
echo "Updated: $UPDATED_API"
echo ""

if echo "$UPDATED_API" | grep -q "DEBUG" && echo "$UPDATED_API" | grep -q "TRACE"; then
    echo "✅ DEBUG and TRACE successfully added"
else
    echo "❌ Update may have failed. Please check manually:"
    echo "  grep rpc-http-api $CONFIG_FILE"
    exit 1
fi
echo ""

echo "Step 5: Updating rpc-ws-api (if present)..."
if grep -q "rpc-ws-api" "$CONFIG_FILE"; then
    echo "Found rpc-ws-api, updating..."
    if grep -q 'rpc-ws-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN"\]' "$CONFIG_FILE"; then
        sed -i 's/rpc-ws-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN"\]/rpc-ws-api=["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN","DEBUG","TRACE"]/g' "$CONFIG_FILE"
        echo "✅ rpc-ws-api updated"
    fi
else
    echo "ℹ️  rpc-ws-api not found (may not be configured)"
fi
echo ""

echo "Step 6: Restarting Besu service..."
systemctl restart besu-rpc
echo "✅ Service restart initiated"
echo ""

echo "Step 7: Waiting for service to start..."
sleep 10
if systemctl is-active --quiet besu-rpc; then
    echo "✅ Service is running"
else
    echo "⚠️  Service may not be running. Check status:"
    systemctl status besu-rpc --no-pager | head -10
fi
echo ""

echo "Step 8: Testing DEBUG API..."
sleep 5
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 still not enabled"
    echo "   Response: $DEBUG_TEST"
    echo ""
    echo "   Possible issues:"
    echo "   1. Service may need more time to restart"
    echo "   2. Config file may not be the one being used"
    echo "   3. Check which config Besu is actually using:"
    echo "      ps aux | grep besu | grep -v grep"
else
    echo "✅ DEBUG API is enabled!"
    echo "   (Returned error for invalid transaction, which is expected)"
fi
echo ""

echo "═══════════════════════════════════════════════════════════════"
echo "SUMMARY"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Config file: $CONFIG_FILE"
echo "Backup: $BACKUP_FILE"
echo ""
echo "To test with your failed transaction:"
echo "  curl -X POST -H 'Content-Type: application/json' \\"
echo "    --data '{\"jsonrpc\":\"2.0\",\"method\":\"debug_traceTransaction\",\"params\":[\"0x4dc9f5eedf580c2b37457916b04048481aba19cf3c1a106ea1ee9eefa0dc03c8\",{\"tracer\":\"callTracer\"}],\"id\":1}' \\"
echo "    http://localhost:8545 | jq"
echo ""

