#!/usr/bin/env bash
# Enable TXPOOL RPC methods on Besu RPC node
# This enables transaction pool inspection and clearing methods
# Usage: ./enable-txpool-rpc.sh [vmid]

set -euo pipefail

VMID="${1:-2500}"  # Default to RPC node 2500
RPC_CONFIG="/etc/besu/config-rpc.toml"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "========================================="
log_info "Enable TXPOOL on Besu RPC Node"
log_info "========================================="
log_info ""
log_info "VMID: $VMID"
log_info "Config: $RPC_CONFIG"
log_info ""

# Check if running on Proxmox host
if command -v pct >/dev/null 2>&1; then
    log_info "Running on Proxmox host"
    USE_PCT=true
else
    log_info "Not on Proxmox host - will use SSH or direct access"
    USE_PCT=false
fi

if [ "$USE_PCT" = true ]; then
    # Check if container exists
    if ! pct status "$VMID" >/dev/null 2>&1; then
        log_error "Container $VMID not found"
        exit 1
    fi
    
    # Check current config
    log_info "Checking current RPC API configuration..."
    CURRENT_API=$(pct exec "$VMID" -- grep -E "^rpc-http-api=" "$RPC_CONFIG" 2>/dev/null || echo "")
    
    if [ -n "$CURRENT_API" ]; then
        log_info "Current config: $CURRENT_API"
        
        # Check if TXPOOL already enabled
        if echo "$CURRENT_API" | grep -qi "TXPOOL"; then
            log_success "✓ TXPOOL already enabled"
            exit 0
        fi
    else
        log_warn "⚠ rpc-http-api not found in config"
    fi
    
    # Backup config
    log_info "Backing up config..."
    pct exec "$VMID" -- cp "$RPC_CONFIG" "${RPC_CONFIG}.backup.$(date +%Y%m%d_%H%M%S)" 2>/dev/null || true
    
    # Update config to include TXPOOL
    log_info "Updating config to enable TXPOOL..."
    
    # Remove old rpc-http-api line if exists
    pct exec "$VMID" -- sed -i '/^rpc-http-api=/d' "$RPC_CONFIG" 2>/dev/null || true
    
    # Add new rpc-http-api with TXPOOL
    # Find line number after rpc-http-port
    LINE_NUM=$(pct exec "$VMID" -- grep -n "^rpc-http-port=" "$RPC_CONFIG" 2>/dev/null | cut -d: -f1 || echo "21")
    INSERT_LINE=$((LINE_NUM + 1))
    
    pct exec "$VMID" -- sed -i "${INSERT_LINE}i rpc-http-api=[\"ETH\",\"NET\",\"WEB3\",\"TXPOOL\"]" "$RPC_CONFIG" 2>/dev/null || {
        # Fallback: append to end of RPC section
        pct exec "$VMID" -- sed -i '/^rpc-http-port=/a rpc-http-api=["ETH","NET","WEB3","TXPOOL"]' "$RPC_CONFIG" 2>/dev/null || {
            log_error "Failed to update config"
            exit 1
        }
    }
    
    log_success "✓ Config updated"
    
    # Restart Besu service
    log_info "Restarting Besu RPC service..."
    pct exec "$VMID" -- systemctl restart besu-rpc 2>/dev/null || {
        log_error "Failed to restart service"
        log_info "You may need to restart manually: pct exec $VMID -- systemctl restart besu-rpc"
        exit 1
    }
    
    log_success "✓ Service restarted"
    
    # Wait for service to come online
    log_info "Waiting for RPC to come online..."
    sleep 5
    
    # Verify TXPOOL is enabled
    RPC_IP=$(pct exec "$VMID" -- hostname -I | awk '{print $1}' 2>/dev/null || echo "192.168.11.250")
    RPC_URL="http://${RPC_IP}:8545"
    
    log_info "Verifying TXPOOL is enabled on $RPC_URL..."
    RPC_MODULES=$(curl -s -X POST -H "Content-Type: application/json" \
        --data '{"jsonrpc":"2.0","method":"rpc_modules","params":[],"id":1}' \
        "$RPC_URL" 2>/dev/null || echo "")
    
    if echo "$RPC_MODULES" | jq -r '.result | keys[]' 2>/dev/null | grep -qi "txpool"; then
        log_success "✓ TXPOOL is now enabled"
    else
        log_warn "⚠ TXPOOL may not be enabled - check manually"
    fi
    
else
    log_warn "⚠ Not on Proxmox host"
    log_info "To enable TXPOOL manually:"
    log_info "  1. Edit $RPC_CONFIG on the Besu RPC node"
    log_info "  2. Change: rpc-http-api=[\"ETH\",\"NET\",\"WEB3\"]"
    log_info "  3. To: rpc-http-api=[\"ETH\",\"NET\",\"WEB3\",\"TXPOOL\"]"
    log_info "  4. Restart Besu service: systemctl restart besu-rpc"
fi

log_info ""
log_success "========================================="
log_success "TXPOOL Enable Complete"
log_success "========================================="
log_info ""

