#!/usr/bin/env bash
# Audit Besu heap sizing (BESU_OPTS) vs container memory for RPC VMIDs.
#
# Usage:
#   PROXMOX_HOST=192.168.11.10 ./scripts/audit-proxmox-rpc-besu-heap.sh
#
# Output highlights containers where Xmx appears larger than container memory.

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
UNIT="/etc/systemd/system/besu-rpc.service"

VMIDS=(2400 2401 2402 2500 2501 2502 2503 2504 2505 2506 2507 2508)

ssh_pve() {
  ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 "root@${PROXMOX_HOST}" "$@"
}

extract_xmx_gb() {
  local line="$1"
  # Matches -Xmx8g / -Xmx4096m
  if [[ "$line" =~ -Xmx([0-9]+)([gGmM]) ]]; then
    local n="${BASH_REMATCH[1]}"
    local u="${BASH_REMATCH[2]}"
    if [[ "$u" =~ [gG] ]]; then
      echo "$n"
      return 0
    fi
    # m -> gb (floor)
    echo $(( n / 1024 ))
    return 0
  fi
  echo ""
}

echo "=== Proxmox RPC Besu Heap Audit ==="
echo "Host: ${PROXMOX_HOST}"
echo

printf "%-6s %-8s %-12s %-20s %s\n" "VMID" "MEM(MB)" "SWAP(MB)" "BESU_OPTS" "RISK"
printf "%-6s %-8s %-12s %-20s %s\n" "----" "------" "--------" "--------" "----"

for v in "${VMIDS[@]}"; do
  mem="$(ssh_pve "pct config ${v} | sed -n 's/^memory: //p' | head -1" 2>/dev/null | tr -d '\r')"
  swap="$(ssh_pve "pct config ${v} | sed -n 's/^swap: //p' | head -1" 2>/dev/null | tr -d '\r')"
  opts_line="$(ssh_pve "pct exec ${v} -- bash -lc \"grep -oE 'BESU_OPTS=.*' ${UNIT} 2>/dev/null | head -1\"" 2>/dev/null | tr -d '\r' || true)"

  # Fallback to just the Environment= line
  if [[ -z "${opts_line}" ]]; then
    opts_line="$(ssh_pve "pct exec ${v} -- bash -lc \"grep -n 'BESU_OPTS' ${UNIT} 2>/dev/null | head -1\"" 2>/dev/null | tr -d '\r' || true)"
  fi

  xmx_gb="$(extract_xmx_gb "${opts_line}")"
  mem_gb=$(( (mem + 1023) / 1024 ))
  risk=""
  if [[ -n "${xmx_gb}" ]] && [[ "${mem_gb}" -gt 0 ]] && [[ "${xmx_gb}" -ge "${mem_gb}" ]]; then
    risk="HIGH (Xmx>=mem)"
  fi

  printf "%-6s %-8s %-12s %-20s %s\n" "$v" "${mem:-?}" "${swap:-?}" "$(echo "${opts_line:-<missing>}" | cut -c1-20)" "${risk}"
done

cat <<'NOTE'

NOTE:
- A safe rule of thumb: keep -Xmx <= ~60-70% of container memory to avoid swap/IO thrash during RocksDB work.
- If you see HIGH risk, reduce BESU_OPTS and restart besu-rpc during a maintenance window.
NOTE

