#!/usr/bin/env bash
# Enable TXPOOL RPC methods on Besu RPC node via SSH
# Usage: ./enable-txpool-rpc-ssh.sh [vmid] [rpc_ip]

set -euo pipefail

VMID="${1:-2500}"  # Default to RPC node 2500
RPC_IP="${2:-192.168.11.250}"
RPC_CONFIG="/etc/besu/config-rpc.toml"
PROXMOX_HOST="192.168.11.10"
PROXMOX_PASS="L@kers2010"

# 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 (via SSH)"
log_info "========================================="
log_info ""
log_info "VMID: $VMID"
log_info "RPC IP: $RPC_IP"
log_info "Config: $RPC_CONFIG"
log_info ""

# Check if sshpass is available
if ! command -v sshpass >/dev/null 2>&1; then
    log_error "sshpass is required. Install with: sudo apt-get install sshpass"
    exit 1
fi

# Test SSH connection to Proxmox host
log_info "Testing SSH connection to Proxmox host..."
if ! sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 \
    "root@$PROXMOX_HOST" "echo 'Connection successful'" 2>/dev/null; then
    log_error "Cannot connect to Proxmox host $PROXMOX_HOST"
    exit 1
fi
log_success "✓ Connected to Proxmox host"

# Check current config via Proxmox
log_info "Checking current RPC API configuration..."
CURRENT_API=$(sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "pct exec $VMID -- grep -E '^rpc-http-api=' $RPC_CONFIG 2>/dev/null || echo ''" 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..."
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "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
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "pct exec $VMID -- sed -i '/^rpc-http-api=/d' $RPC_CONFIG" 2>/dev/null || true

# Add new rpc-http-api with TXPOOL after rpc-http-port
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "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..."
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "pct exec $VMID -- systemctl restart besu-rpc" 2>/dev/null || {
    log_error "Failed to restart service"
    log_info "You may need to restart manually on Proxmox host"
    exit 1
}

log_success "✓ Service restarted"

# Wait for service to come online
log_info "Waiting for RPC to come online..."
sleep 10

# Verify TXPOOL is enabled
log_info "Verifying TXPOOL is enabled on $RPC_IP:8545..."
RPC_URL="http://${RPC_IP}:8545"

for i in {1..10}; do
    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 [ -n "$RPC_MODULES" ] && echo "$RPC_MODULES" | jq -e '.result' >/dev/null 2>&1; then
        if echo "$RPC_MODULES" | jq -r '.result | keys[]' 2>/dev/null | grep -qi "txpool"; then
            log_success "✓ TXPOOL is now enabled"
            break
        else
            log_warn "⚠ RPC is online but TXPOOL not found (attempt $i/10)"
            sleep 2
        fi
    else
        log_info "Waiting for RPC to come online (attempt $i/10)..."
        sleep 2
    fi
done

log_info ""
log_success "========================================="
log_success "TXPOOL Enable Complete"
log_success "========================================="
log_info ""
log_info "Next step: Run ./scripts/resolve-stuck-transaction-besu-qbft.sh"

