#!/usr/bin/env bash
set -euo pipefail

HUGEPAGES=4096
SYSCTL_DROPIN="/etc/sysctl.d/60-hugepages.conf"
LIMITS_DROPIN="/etc/security/limits.d/99-memlock.conf"
SERVICE_NAME="cpu-governor-performance.service"
SERVICE_PATH="/etc/systemd/system/${SERVICE_NAME}"

need_root() {
  if [[ $EUID -ne 0 ]]; then
    echo "Ce script doit être exécuté en root (sudo)." >&2
    exit 1
  fi
}

configure_hugepages_dropin() {
  echo "==> Configuration HugePages via ${SYSCTL_DROPIN} (${HUGEPAGES})"
  mkdir -p /etc/sysctl.d
  cat > "$SYSCTL_DROPIN" <<EOF
# XMRig / RandomX: réserver ${HUGEPAGES} pages énormes (2 MiB chacune) ≈ $((HUGEPAGES*2)) MiB
vm.nr_hugepages=${HUGEPAGES}
EOF
  # Recharge toutes les confs sysctl.d + kernel defaults
  sysctl --system >/dev/null
  grep -E 'HugePages_Total|Hugepagesize' /proc/meminfo | sed 's/^/   /'
}

configure_limits_dropin() {
  echo "==> Configuration memlock via ${LIMITS_DROPIN} (unlimited)"
  mkdir -p /etc/security/limits.d
  cat > "$LIMITS_DROPIN" <<'EOF'
# Autoriser le lock mémoire pour HugePages (XMRig)
*     soft memlock unlimited
*     hard memlock unlimited
root  soft memlock unlimited
root  hard memlock unlimited
EOF
  echo "   Note: ouvre une nouvelle session (ou reboot) pour que 'ulimit -l' devienne 'unlimited'."
}

apply_governor_now() {
  echo "==> Application immédiate du gouverneur CPU = performance (si disponible)"
  shopt -s nullglob
  for g in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do
    echo performance > "$g" 2>/dev/null || true
  done
  shopt -u nullglob
  local cur="(indisponible)"
  if [[ -f /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor ]]; then
    cur=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)
  fi
  echo "   Gouverneur actuel CPU0: ${cur}"
}

create_governor_service() {
  echo "==> Service systemd pour forcer 'performance' au boot"
  cat > "$SERVICE_PATH" <<'UNIT'
[Unit]
Description=Set CPU governor to performance
After=multi-user.target

[Service]
Type=oneshot
ExecStart=/bin/bash -c 'for g in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo performance > "$g" 2>/dev/null || true; done'

[Install]
WantedBy=multi-user.target
UNIT
  systemctl daemon-reload
  systemctl enable --now "$SERVICE_NAME" >/dev/null 2>&1 || true
  systemctl is-enabled "$SERVICE_NAME" || true
}

summary() {
  echo "==> Résumé:"
  echo -n "   - HugePages: "; grep -E 'HugePages_Total|HugePages_Free|Hugepagesize' /proc/meminfo | xargs -I{} echo {}
  echo "   - memlock: ouvre une nouvelle session, puis 'ulimit -l' (attendu: unlimited)"
  if command -v lscpu >/dev/null; then
    if lscpu | grep -qi aes; then echo "   - AES-NI: OUI"; else echo "   - AES-NI: NON"; fi
  fi
}

main() {
  need_root
  configure_hugepages_dropin
  configure_limits_dropin
  apply_governor_now
  create_governor_service
  summary
  echo "✅ Terminé. Recommandé: reboot pour valider memlock & HugePages dès le démarrage."
}

main "$@"
