#!/usr/bin/env bash
# Fix RPC authorization to allow contract deployment
# This script updates the RPC node configuration to allow access from deployment host

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_PASS="${PROXMOX_PASS:-L@kers2010}"
RPC_VMID="${RPC_VMID:-2500}"
DEPLOYMENT_HOST="${DEPLOYMENT_HOST:-}"

# 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"; }

ssh_proxmox() {
    sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "$@"
}

# Get deployment host IP if not provided
if [ -z "$DEPLOYMENT_HOST" ]; then
    DEPLOYMENT_HOST=$(hostname -I | awk '{print $1}')
    log_info "Detected deployment host IP: $DEPLOYMENT_HOST"
fi

log_info "========================================="
log_info "Fix RPC Authorization"
log_info "========================================="
log_info ""
log_info "RPC Node: VMID $RPC_VMID"
log_info "Deployment Host: $DEPLOYMENT_HOST"
log_info ""

# Check current configuration
log_info "Step 1: Checking current RPC configuration..."
CURRENT_CONFIG=$(ssh_proxmox "pct exec $RPC_VMID -- cat /etc/besu/config-rpc.toml 2>/dev/null" 2>&1)

if echo "$CURRENT_CONFIG" | grep -q "rpc-http-host"; then
    CURRENT_HOST=$(echo "$CURRENT_CONFIG" | grep "rpc-http-host" | head -1 | sed 's/.*= *"\(.*\)".*/\1/')
    log_info "Current rpc-http-host: $CURRENT_HOST"
    
    if echo "$CURRENT_HOST" | grep -q "0.0.0.0\|\\*"; then
        log_success "RPC is already configured to accept connections from any host"
        exit 0
    fi
fi

# Backup current config
log_info ""
log_info "Step 2: Backing up current configuration..."
ssh_proxmox "pct exec $RPC_VMID -- cp /etc/besu/config-rpc.toml /etc/besu/config-rpc.toml.backup.$(date +%Y%m%d-%H%M%S)" 2>&1 || true

# Update configuration to allow all hosts (for deployment)
log_info ""
log_info "Step 3: Updating RPC configuration to allow all hosts..."

# Create updated config
ssh_proxmox "pct exec $RPC_VMID -- bash -c '
# Update rpc-http-host to allow all connections
sed -i \"s|rpc-http-host=.*|rpc-http-host=\"0.0.0.0\"|g\" /etc/besu/config-rpc.toml

# Ensure rpc-http-enabled is true
sed -i \"s|rpc-http-enabled=.*|rpc-http-enabled=true|g\" /etc/besu/config-rpc.toml

# Add host-allowlist if not present (allows all)
if ! grep -q \"host-allowlist\" /etc/besu/config-rpc.toml; then
    echo \"host-allowlist=[\\\"*\\\"]\" >> /etc/besu/config-rpc.toml
fi
'" 2>&1

# Restart Besu service
log_info ""
log_info "Step 4: Restarting Besu RPC service..."
ssh_proxmox "pct exec $RPC_VMID -- systemctl restart besu-rpc" 2>&1 || {
    log_warn "Failed to restart service, may need manual restart"
}

# Wait for service to start
sleep 5

# Verify RPC is accessible
log_info ""
log_info "Step 5: Verifying RPC is accessible..."
TEST_RESPONSE=$(curl -s -X POST "http://192.168.11.250:8545" \
    -H 'Content-Type: application/json' \
    -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null)

if echo "$TEST_RESPONSE" | grep -q '"result"'; then
    log_success "RPC is now accessible!"
    BLOCK=$(echo "$TEST_RESPONSE" | python3 -c "import sys, json; data=json.load(sys.stdin); print(int(data.get('result', '0x0'), 16))" 2>/dev/null || echo "0")
    log_info "   Current block: $BLOCK"
else
    log_warn "RPC may still have authorization issues"
    log_warn "Response: $TEST_RESPONSE"
fi

log_info ""
log_success "========================================="
log_success "RPC Authorization Fixed!"
log_success "========================================="
log_info ""
log_info "You can now deploy contracts using:"
log_info "  ./scripts/deploy-contracts-chain138.sh"
log_info ""

