#!/bin/bash
# SPDX-License-Identifier: MIT
# Simafri measured requirements bench: a measurement campaign, under the bench lock, one
# application at a time. Runs on the Proxmox host, as root.
#
#   campagne.sh mesure <app>                         three independent runs of each profile,
#                                                    interleaved (idle, light, sustained, then
#                                                    again twice), on the large container
#   campagne.sh valide <app> <profile> <vcpu> <mib>  one run of a profile at the size of a tier
#
# Results go to /root/banc-mesures/resultats/<app>/<UTC day of the start>/. 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/$(date -u +%Y-%m-%d)
mkdir -p "$RES"

exec 9> /root/banc-mesures.lock
flock -n 9 || { echo "The bench is in use (lock /root/banc-mesures.lock)." >&2; exit 1; }

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

case "$MODE" in
  mesure)
    for k in 1 2 3; do
      for profil in idle light sustained; do
        passage "$profil" "$LARGE_VCPU" "$LARGE_MIO" "$RES/$profil-large-$k"
      done
    done
    ;;
  valide)
    PROFIL=$3 VCPU=$4 MIO=$5
    n=1
    while [ -e "$RES/$PROFIL-palier-${VCPU}c-${MIO}m-$n" ]; do n=$((n + 1)); done
    passage "$PROFIL" "$VCPU" "$MIO" "$RES/$PROFIL-palier-${VCPU}c-${MIO}m-$n"
    ;;
  *)
    echo "usage: campagne.sh mesure <app> | valide <app> <profile> <vcpu> <mib>" >&2
    exit 2
    ;;
esac

pct stop "$CT" 2>/dev/null || true
pct rollback "$CT" propre
pct set "$CT" --cores "$LARGE_VCPU" --memory "$LARGE_MIO" --swap 1024
echo "$(date -u +%FT%TZ) campaign done, bench clean and stopped" >> "$RES/campagne.log"
