#!/usr/bin/env bash
# Enable DEBUG API in Besu Configuration
# Must be run on the RPC node

set -euo pipefail

RPC_IP="${1:-192.168.11.250}"
SSH_PASSWORD="${SSH_PASSWORD:-${2:-}}"
if [ -z "${SSH_PASSWORD}" ]; then
    echo "ERROR: SSH_PASSWORD is required. Pass it as an argument or export SSH_PASSWORD in the environment." >&2
    echo "       Hardcoded default removed for security; see docs/SECURITY.md." >&2
    exit 2
fi

CONFIG_FILE="${3:-/etc/besu/config-rpc-core.toml}"

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     ENABLING DEBUG API IN BESU CONFIGURATION                ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "RPC IP: $RPC_IP"
echo "Config File: $CONFIG_FILE"
echo ""

# Check if sshpass is available
if ! command -v sshpass >/dev/null 2>&1; then
    echo "⚠️  sshpass not installed. Installing..."
    sudo apt-get update -qq && sudo apt-get install -y sshpass 2>/dev/null || {
        echo "❌ Cannot install sshpass automatically"
        exit 1
    }
fi

echo "Step 1: Checking current configuration..."
CURRENT_CONFIG=$(sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
    root@"$RPC_IP" \
    "cat $CONFIG_FILE 2>/dev/null || echo 'FILE_NOT_FOUND'" 2>&1)

if echo "$CURRENT_CONFIG" | grep -q "FILE_NOT_FOUND"; then
    echo "❌ Config file not found: $CONFIG_FILE"
    echo ""
    echo "Available config files:"
    sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
        root@"$RPC_IP" \
        "ls -la /etc/besu/*.toml 2>/dev/null || echo 'No config files found'"
    exit 1
fi

echo "✅ Config file found"
echo ""

# Check if DEBUG is already enabled
if echo "$CURRENT_CONFIG" | grep -q "DEBUG"; then
    echo "✅ DEBUG API is already enabled in configuration"
    echo ""
    echo "Current rpc-http-api setting:"
    echo "$CURRENT_CONFIG" | grep "rpc-http-api" | head -1
    echo ""
    echo "Checking if Besu service needs restart..."
    RESTART_NEEDED=$(sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
        root@"$RPC_IP" \
        "systemctl is-active besu-rpc >/dev/null 2>&1 && echo 'active' || echo 'inactive'" 2>&1)
    
    if [ "$RESTART_NEEDED" = "active" ]; then
        echo "⚠️  DEBUG API is enabled but service may need restart"
        echo "   Restarting Besu service..."
        sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
            root@"$RPC_IP" \
            "systemctl restart besu-rpc && sleep 5 && systemctl status besu-rpc --no-pager | head -10" 2>&1
        echo ""
        echo "✅ Besu service restarted"
    fi
else
    echo "Step 2: Adding DEBUG to rpc-http-api..."
    
    # Create backup
    sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
        root@"$RPC_IP" \
        "cp $CONFIG_FILE ${CONFIG_FILE}.backup.$(date +%Y%m%d-%H%M%S)" 2>&1
    
    # Update configuration
    sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
        root@"$RPC_IP" \
        "sed -i 's/rpc-http-api=\[\"ETH\",\"NET\",\"WEB3\",\"TXPOOL\",\"QBFT\",\"ADMIN\",\"DEBUG\",\"TRACE\"\]/rpc-http-api=[\"ETH\",\"NET\",\"WEB3\",\"TXPOOL\",\"QBFT\",\"ADMIN\",\"DEBUG\",\"TRACE\"]/g' $CONFIG_FILE || \
         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 || \
         sed -i 's/rpc-http-api=\[\"ETH\",\"NET\",\"WEB3\"\]/rpc-http-api=[\"ETH\",\"NET\",\"WEB3\",\"DEBUG\",\"TRACE\"]/g' $CONFIG_FILE" 2>&1
    
    echo "✅ Configuration updated"
    echo ""
    
    echo "Step 3: Verifying configuration..."
    UPDATED_CONFIG=$(sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
        root@"$RPC_IP" \
        "grep 'rpc-http-api' $CONFIG_FILE | head -1" 2>&1)
    
    echo "Updated rpc-http-api: $UPDATED_CONFIG"
    echo ""
    
    if echo "$UPDATED_CONFIG" | grep -q "DEBUG"; then
        echo "✅ DEBUG API added to configuration"
        echo ""
        echo "Step 4: Restarting Besu service..."
        sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
            root@"$RPC_IP" \
            "systemctl restart besu-rpc && sleep 5 && systemctl status besu-rpc --no-pager | head -10" 2>&1
        
        echo ""
        echo "✅ Besu service restarted"
        echo ""
        echo "Step 5: Verifying DEBUG API is enabled..."
        sleep 3
        DEBUG_TEST=$(sshpass -p "$SSH_PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \
            root@"$RPC_IP" \
            "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" 2>&1)
        
        if echo "$DEBUG_TEST" | grep -q "Method not enabled"; then
            echo "⚠️  DEBUG API still not enabled (may need more time to restart)"
        elif echo "$DEBUG_TEST" | grep -q "error"; then
            echo "✅ DEBUG API is enabled (returned error for invalid transaction, which is expected)"
        else
            echo "✅ DEBUG API appears to be enabled"
        fi
    else
        echo "❌ Failed to add DEBUG API to configuration"
        echo "   Please edit manually: $CONFIG_FILE"
        echo "   Add \"DEBUG\" and \"TRACE\" to rpc-http-api array"
    fi
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "SUMMARY"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "To enable DEBUG API manually:"
echo "  1. Edit: $CONFIG_FILE"
echo "  2. Find: rpc-http-api=[...]"
echo "  3. Add: \"DEBUG\", \"TRACE\" to the array"
echo "  4. Restart: systemctl restart besu-rpc"
echo ""
echo "Then test with:"
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 ""

