#!/bin/sh
# bee-hpc-tuning — apply HPC tuning for deterministic benchmarking
# Called by bee-hpc-tuning.service at boot.

log() { echo "[bee-hpc-tuning] $*"; }

# ── CPU governor ────────────────────────────────────────────────────────────
# Set all CPU cores to performance governor via sysfs.
# cpupower is not available; write directly to scaling_governor.
governor_ok=0
governor_fail=0
for gov_path in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do
    [ -f "$gov_path" ] || continue
    if echo performance > "$gov_path" 2>/dev/null; then
        governor_ok=$((governor_ok + 1))
    else
        governor_fail=$((governor_fail + 1))
    fi
done

if [ "$governor_ok" -gt 0 ] && [ "$governor_fail" -eq 0 ]; then
    log "CPU governor set to performance on ${governor_ok} core(s)"
elif [ "$governor_ok" -gt 0 ]; then
    log "WARN: CPU governor: ${governor_ok} OK, ${governor_fail} failed"
elif [ "$governor_fail" -gt 0 ]; then
    log "WARN: failed to set CPU governor on ${governor_fail} core(s)"
else
    log "WARN: no cpufreq scaling_governor paths found (C-state governor or HW-controlled)"
fi

# ── Transparent Huge Pages ───────────────────────────────────────────────────
# Kernel cmdline sets transparent_hugepage=always at boot, but confirm and log.
thp_path=/sys/kernel/mm/transparent_hugepage/enabled
if [ -f "$thp_path" ]; then
    current=$(cat "$thp_path" 2>/dev/null)
    log "transparent_hugepage: ${current}"
else
    log "WARN: transparent_hugepage sysfs path not found"
fi

log "done"
