#!/bin/bash
# SPDX-License-Identifier: MIT
# Stileex measured requirements bench, method 1.1: a measurement campaign, under the bench lock, one
# application at a time. Runs on the Proxmox host, as root, most often from the queue (file.sh).
#
#   campagne.sh mesure <app>              the short trial, then two independent runs of each profile,
#                                         interleaved (idle, light, sustained, then again), on the
#                                         large server; a third run of a profile only when its two
#                                         runs are more than 10 % apart; then the sustained profile
#                                         replayed at the candidate size of the scale, and at the
#                                         next size up while a replay does not hold
#   campagne.sh valide <app> <vcpu> <mib> the short trial, then one replay of the sustained profile at
#                                         a size of the scale
#   campagne.sh suite <app>               the short trial, then what follows the two runs of each
#                                         profile already in the day's directory: the third runs
#                                         where they are needed, and the replays at the scale
#   campagne.sh essai <app>               the short trial alone
#
# 🔴 The short trial is mandatory before every campaign: one sustained run cut short (30 s of rest
# for the system, 30 s of warm-up, 2 min measured), analysed at once. If it did not hold, or the host
# was busy, the campaign stops there, before hours of bench are spent on a protocol that fails
# (AdGuard Home, 29/11/2026: 1 h 32 lost to upstream resolvers that answered SERVFAIL).
#
# Results go to /root/banc-mesures/resultats/<app>/<day>/ (BANC_JOUR, by default the UTC day of the
# start: set it once for a measurement and its validations, which may run past midnight). A failed run
# is written to echecs.txt and the campaign goes on. The bench is left clean and stopped.
set -uo pipefail

MODE=$1 APP=$2
BANC=$(cd "$(dirname "$0")" && pwd)
CT=${BANC_CT:-207}
LARGE_VCPU=${BANC_LARGE_VCPU:-4}
LARGE_MIO=${BANC_LARGE_MIO:-8192}
RES=${BANC_RESULTATS:-/root/banc-mesures/resultats}/$APP/${BANC_JOUR:-$(date -u +%Y-%m-%d)}
mkdir -p "$RES"

# One lock per bench: a second bench (another measured server) takes its own with BANC_VERROU.
exec 9> "${BANC_VERROU:-/root/banc-mesures.lock}"
flock -n 9 || { echo "The bench is in use (lock ${BANC_VERROU:-/root/banc-mesures.lock})." >&2; exit 1; }

log() { echo "$(date -u +%FT%TZ) $*" >> "$RES/campagne.log"; }

nettoyer() {
  pct stop "$CT" 2>/dev/null || true
  pct rollback "$CT" propre
  pct set "$CT" --cores "$LARGE_VCPU" --memory "$LARGE_MIO" --swap 1024
}

passage() {
  local profil=$1 vcpu=$2 mio=$3 dossier=$4
  log "start $profil ${vcpu} vCPU ${mio} MiB -> $dossier"
  if "$BANC/passage.sh" "$APP" "$profil" "$vcpu" "$mio" "$dossier" > "$dossier.log" 2>&1; then
    log "end $dossier"
  else
    echo "$(date -u +%FT%TZ) FAILED $dossier (see $dossier.log)" | tee -a "$RES/echecs.txt" >> "$RES/campagne.log"
  fi
}

# The next free directory of a run: <prefix>-1, <prefix>-2...
suivant() {
  local n=1
  while [ -e "$1-$n" ]; do n=$((n + 1)); done
  echo "$1-$n"
}

essai() {
  local dossier
  dossier=$(suivant "$RES/essai-sustained")
  log "short trial -> $dossier"
  BANC_SOCLE_S=30 BANC_CHAUFFE_S=30 BANC_MESURE_S=120 passage sustained "$LARGE_VCPU" "$LARGE_MIO" "$dossier"
  if python3 "$BANC/analyse.py" --essai "$dossier" > "$dossier.verdict.json" 2>> "$RES/campagne.log"; then
    log "short trial held: $(cat "$dossier.verdict.json")"
    return 0
  fi
  log "short trial did NOT hold, the campaign stops: $(cat "$dossier.verdict.json" 2>/dev/null)"
  echo "$(date -u +%FT%TZ) SHORT TRIAL FAILED $dossier" >> "$RES/echecs.txt"
  nettoyer
  exit 3
}

valider() {
  local vcpu=$1 mio=$2 dossier
  dossier=$(suivant "$RES/sustained-palier-${vcpu}c-${mio}m")
  passage sustained "$vcpu" "$mio" "$dossier"
  python3 "$BANC/analyse.py" --essai "$dossier" > "$dossier.verdict.json" 2>> "$RES/campagne.log"
}

# After the two runs of each profile: the third runs where they are needed, then the replay of the
# sustained profile at the candidate size, and at the next size up while a replay does not hold
# (memory first, the axis that decides; the vCPU candidate is kept).
suite() {
  python3 "$BANC/analyse.py" "$RES" --sortie "$RES/analyse.json"
  for profil in $(python3 -c 'import json, sys; d = json.load(open(sys.argv[1])); print(" ".join(k for k, p in d["profils"].items() if p["troisieme_passage"]))' "$RES/analyse.json"); do
    passage "$profil" "$LARGE_VCPU" "$LARGE_MIO" "$RES/$profil-large-3"
  done
  python3 "$BANC/analyse.py" "$RES" --sortie "$RES/analyse.json"
  local vcpu mio taille
  read -r vcpu mio < <(python3 -c 'import json, sys; t = json.load(open(sys.argv[1]))["taille_candidate"]; print(t["vcpu"], t["memoire_mio"])' "$RES/analyse.json")
  for taille in 512 1024 2048 4096 8192 16384; do
    [ "$taille" -lt "$mio" ] && continue
    if valider "$vcpu" "$taille"; then log "size ${vcpu} vCPU ${taille} MiB validated"; break; fi
    log "size ${vcpu} vCPU ${taille} MiB did not hold, next size"
  done
  python3 "$BANC/analyse.py" "$RES" --sortie "$RES/analyse.json"
}

case "$MODE" in
  mesure)
    essai
    for k in 1 2; do
      for profil in idle light sustained; do
        passage "$profil" "$LARGE_VCPU" "$LARGE_MIO" "$RES/$profil-large-$k"
      done
    done
    suite
    ;;
  suite)
    essai
    suite
    ;;
  valide)
    VCPU=$3 MIO=$4
    essai
    if valider "$VCPU" "$MIO"; then log "size ${VCPU} vCPU ${MIO} MiB validated"; else log "size ${VCPU} vCPU ${MIO} MiB did not hold"; fi
    ;;
  essai)
    essai
    ;;
  *)
    echo "usage: campagne.sh mesure <app> | suite <app> | valide <app> <vcpu> <mib> | essai <app>" >&2
    exit 2
    ;;
esac

nettoyer
log "campaign done, bench clean and stopped"
