#!/bin/bash
# Quick fix to enable DEBUG API - run directly on besu-rpc-1
# Usage: bash quick-fix-besu-debug.sh

set -euo pipefail

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

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     QUICK FIX: ENABLE DEBUG API                              ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

# Backup
BACKUP="${CONFIG_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
cp "$CONFIG_FILE" "$BACKUP"
echo "✅ Backup: $BACKUP"
echo ""

# Update rpc-http-api
echo "Updating rpc-http-api..."
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 "✅ rpc-http-api updated"
echo ""

# Update rpc-ws-api
echo "Updating rpc-ws-api..."
sed -i 's/rpc-ws-api=\["ETH","NET","WEB3"\]/rpc-ws-api=["ETH","NET","WEB3","DEBUG","TRACE"]/g' "$CONFIG_FILE"
echo "✅ rpc-ws-api updated"
echo ""

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

# Restart
echo "🔄 Restarting besu-rpc..."
systemctl restart besu-rpc
echo "✅ Service restarted"
echo ""

# Wait
echo "⏳ Waiting 10 seconds..."
sleep 10
echo ""

# Test
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 "Method not enabled"; then
    echo "❌ DEBUG API still not enabled"
    echo "   Wait a bit longer and try again"
else
    echo "✅ DEBUG API is enabled!"
    echo "   Response received"
fi

echo ""
echo "✅ Done! Backup saved at: $BACKUP"

