#!/usr/bin/env bash
# Fix Besu DEBUG API - Updates the CORRECT config file
# Run this ON the RPC node (besu-rpc-1)

set -euo pipefail

CONFIG_FILE="/etc/besu/config-rpc.toml"  # The ACTUAL file Besu is using

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     ENABLING DEBUG API IN CORRECT CONFIG FILE               ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Config file: $CONFIG_FILE (confirmed from process)"
echo ""

# Check if config file exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo "❌ Config file not found: $CONFIG_FILE"
    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"
    echo ""
    echo "Restarting service to ensure it's active..."
    systemctl restart besu-rpc
    sleep 5
    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
UPDATED=false

# Pattern 1: Standard config
if 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"
    UPDATED=true
fi

# Pattern 2: With DEBUG but missing TRACE
if grep -q 'rpc-http-api=\["ETH","NET","WEB3","TXPOOL","QBFT","ADMIN","DEBUG"\]' "$CONFIG_FILE"; then
    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"
    UPDATED=true
fi

# Pattern 3: Try with single quotes or different formatting
if ! $UPDATED; then
    # Show current line for manual editing
    echo "⚠️  Could not match standard pattern. Current line:"
    grep "rpc-http-api" "$CONFIG_FILE" | head -1
    echo ""
    echo "Please edit manually:"
    echo "  nano $CONFIG_FILE"
    echo ""
    echo "Find rpc-http-api and add \"DEBUG\", \"TRACE\" to the array"
    exit 1
fi

echo "✅ Configuration updated"
echo ""

echo "Step 4: Verifying update..."
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 failed. Please check manually"
    exit 1
fi
echo ""

echo "Step 5: Updating rpc-ws-api (if present)..."
if grep -q "rpc-ws-api" "$CONFIG_FILE"; then
    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
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 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 "   Wait a bit longer and try again, or check logs:"
    echo "   journalctl -u besu-rpc -n 50"
else
    echo "✅ DEBUG API is enabled!"
fi
echo ""

echo "═══════════════════════════════════════════════════════════════"
echo "SUMMARY"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Config file: $CONFIG_FILE"
echo "Backup: $BACKUP_FILE"
echo ""
echo "Test with 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 ""

