#!/bin/bash
# Enable DEBUG and TRACE APIs in Besu RPC configuration
# This script must be run on the Besu RPC node (besu-rpc-1 / VMID 2500)

set -euo pipefail

CONFIG_FILE="/etc/besu/config-rpc.toml"
BACKUP_FILE="/etc/besu/config-rpc.toml.backup.$(date +%Y%m%d_%H%M%S)"

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     ENABLE DEBUG & TRACE APIs IN BESU RPC CONFIG            ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ This script must be run as root"
    exit 1
fi

# Check if config file exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo "❌ Config file not found: $CONFIG_FILE"
    exit 1
fi

echo "📋 Current configuration:"
echo "─────────────────────────────────────────"
grep -E "rpc-http-api|rpc-ws-api" "$CONFIG_FILE" || true
echo ""

# Backup config
echo "📦 Creating backup..."
cp "$CONFIG_FILE" "$BACKUP_FILE"
echo "✅ Backup created: $BACKUP_FILE"
echo ""

# Check if DEBUG is already enabled
if grep -q '"DEBUG"' "$CONFIG_FILE"; then
    echo "⚠️  DEBUG API already appears to be enabled"
    echo "Current rpc-http-api:"
    grep "rpc-http-api" "$CONFIG_FILE" || true
    echo ""
    read -p "Continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Aborted."
        exit 0
    fi
fi

# Update rpc-http-api
echo "🔧 Updating rpc-http-api..."
# Pattern 1: Standard config without QBFT (from user's actual config)
if grep -q 'rpc-http-api=\["ETH","NET","WEB3","TXPOOL","ADMIN"\]' "$CONFIG_FILE"; then
    sed -i 's/rpc-http-api=\["ETH","NET","WEB3","TXPOOL","ADMIN"\]/rpc-http-api=["ETH","NET","WEB3","TXPOOL","ADMIN","DEBUG","TRACE"]/g' "$CONFIG_FILE"
    echo "✅ Updated rpc-http-api (standard pattern)"
# Pattern 2: With QBFT
elif grep -q 'rpc-http-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN"\]' "$CONFIG_FILE"; then
    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"
    echo "✅ Updated rpc-http-api (with QBFT)"
else
    # Try more flexible approach using perl
    echo "⚠️  Exact pattern not found, trying flexible update..."
    perl -i -pe 's/rpc-http-api=\[([^\]]+)\]/rpc-http-api=[$1,"DEBUG","TRACE"]/g if !/"DEBUG"/' "$CONFIG_FILE"
    echo "✅ Updated rpc-http-api (flexible match)"
fi

# Update rpc-ws-api
echo "🔧 Updating rpc-ws-api..."
if grep -q 'rpc-ws-api=\["ETH","NET","WEB3"\]' "$CONFIG_FILE"; then
    sed -i 's/rpc-ws-api=\["ETH","NET","WEB3"\]/rpc-ws-api=["ETH","NET","WEB3","DEBUG","TRACE"]/g' "$CONFIG_FILE"
    echo "✅ Updated rpc-ws-api"
else
    # Try flexible approach
    perl -i -pe 's/rpc-ws-api=\[([^\]]+)\]/rpc-ws-api=[$1,"DEBUG","TRACE"]/g if !/"DEBUG"/' "$CONFIG_FILE"
    echo "✅ Updated rpc-ws-api (flexible match)"
fi

echo ""
echo "📋 Updated configuration:"
echo "─────────────────────────────────────────"
grep -E "rpc-http-api|rpc-ws-api" "$CONFIG_FILE" || true
echo ""

# Validate TOML syntax (if toml-validator is available)
if command -v toml-validator &> /dev/null; then
    echo "🔍 Validating TOML syntax..."
    if toml-validator "$CONFIG_FILE" 2>/dev/null; then
        echo "✅ TOML syntax is valid"
    else
        echo "⚠️  TOML validation failed (may still work)"
    fi
    echo ""
fi

# Restart Besu service
echo "🔄 Restarting Besu service..."
if systemctl is-active --quiet besu-rpc; then
    systemctl restart besu-rpc
    echo "✅ Besu service restarted"
else
    echo "⚠️  Besu service is not running"
    echo "   Start it with: systemctl start besu-rpc"
fi

echo ""
echo "⏳ Waiting for service to start (10 seconds)..."
sleep 10

# Test DEBUG API
echo ""
echo "🧪 Testing DEBUG API..."
TEST_TX="0x4dc9f5eedf580c2b37457916b04048481aba19cf3c1a106ea1ee9eefa0dc03c8"
RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" \
    --data "{\"jsonrpc\":\"2.0\",\"method\":\"debug_traceTransaction\",\"params\":[\"$TEST_TX\",{\"tracer\":\"callTracer\"}],\"id\":1}" \
    http://localhost:8545 2>&1)

if echo "$RESPONSE" | grep -q '"error"'; then
    ERROR=$(echo "$RESPONSE" | jq -r '.error.message // empty' 2>/dev/null || echo "")
    if echo "$ERROR" | grep -q "Method not enabled"; then
        echo "❌ DEBUG API still not enabled"
        echo "   Error: $ERROR"
        echo ""
        echo "📋 Troubleshooting:"
        echo "   1. Check config: grep rpc-http-api $CONFIG_FILE"
        echo "   2. Check service status: systemctl status besu-rpc"
        echo "   3. Check logs: journalctl -u besu-rpc -n 50"
    else
        echo "⚠️  DEBUG API responded with error (but method is enabled)"
        echo "   Error: $ERROR"
        echo "   This might be expected if transaction doesn't exist"
    fi
else
    echo "✅ DEBUG API is enabled and working!"
    echo "   Response received (may contain trace data)"
fi

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     CONFIGURATION COMPLETE                                   ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "📋 Next steps:"
echo "   1. Test with a failed transaction:"
echo "      curl -X POST -H 'Content-Type: application/json' \\"
echo "        --data '{\"jsonrpc\":\"2.0\",\"method\":\"debug_traceTransaction\",\"params\":[\"$TEST_TX\",{\"tracer\":\"callTracer\"}],\"id\":1}' \\"
echo "        http://localhost:8545 | jq"
echo ""
echo "   2. Check service status: systemctl status besu-rpc"
echo "   3. View logs: journalctl -u besu-rpc -f"
echo ""
echo "📦 Backup saved at: $BACKUP_FILE"
echo ""

