#!/bin/bash
# SPDX-License-Identifier: MIT
# Simafri measured requirements bench: one run of one profile of one application, from the clean
# snapshot to the last sample. Runs on the Proxmox host, as root, under the bench lock.
#
#   passage.sh <app> <idle|light|sustained> <vcpu> <memory_mib> <output_dir>
#
# Every phase is written to evenements.txt with its epoch time:
#   rollback to the clean snapshot, resize, boot;
#   the operating system at rest (2 min to settle, 2 min measured: the base of the system);
#   image pull (not measured), installation until the first healthy response, then 60 s for the
#   migrations (the installation peak); the accounts of the profile;
#   idle: 10 min of rest, then 15 min measured;
#   light and sustained: the reference dataset, then 5 min of warm-up and 30 min measured.
set -euo pipefail

APP=$1 PROFIL=$2 VCPU=$3 MEM=$4 OUT=$5
CT=${BANC_CT:-207}
GEN=${BANC_GEN:-208}
VOISINS=${BANC_VOISINS:-204}
SWAP=${BANC_SWAP:-1024}
CHAUFFE_S=${BANC_CHAUFFE_S:-300}
MESURE_S=${BANC_MESURE_S:-1800}
REPOS_VIDE_S=${BANC_REPOS_VIDE_S:-600}
MESURE_VIDE_S=${BANC_MESURE_VIDE_S:-900}
BANC=$(cd "$(dirname "$0")" && pwd)
SRC=$BANC/apps/$APP
. "$SRC/app.sh"

mkdir -p "$OUT"
EV=$OUT/evenements.txt
META=$OUT/meta.env
: > "$EV"
: > "$META"
ev() { echo "$(date +%s.%N) $*" >> "$EV"; }
meta() { printf '%s=%q\n' "$1" "$2" >> "$META"; }
dans() { pct exec "$CT" -- "$@"; }
gen() { pct exec "$GEN" -- "$@"; }
attendre() { sleep "$(awk -v c="$1" -v n="$(date +%s.%N)" 'BEGIN { d = c - n; if (d < 0) d = 0; printf "%.3f", d }')"; }
du_donnees() { dans bash -c "cd /opt/banc/app && du -sb $APP_DONNEES | awk '{ s += \$1 } END { print s }'"; }

meta app "$APP"; meta version "$APP_VERSION"; meta profil "$PROFIL"
meta vcpu "$VCPU"; meta memoire_mio "$MEM"; meta swap_mio "$SWAP"; meta methode "1.0"

ev debut
# 1. The clean container, at the size of the run.
if pct status "$CT" | grep -q running; then pct stop "$CT"; fi
pct rollback "$CT" propre
pct set "$CT" --cores "$VCPU" --memory "$MEM" --swap "$SWAP"
pct start "$CT"
until dans systemctl is-active -q docker 2>/dev/null; do sleep 1; done
until dans systemctl is-active -q banc-entree 2>/dev/null; do sleep 1; done
ev demarre

# 2. The sampler, from the host.
python3 "$BANC/collecteur.py" --ct "$CT" --gen "$GEN" --voisins "$VOISINS" --sortie "$OUT/echantillons.jsonl" &
COL=$!
trap 'kill -TERM $COL 2>/dev/null || true; wait $COL 2>/dev/null || true' EXIT
pic() { kill -USR1 "$COL"; }

# 3. The operating system at rest.
sleep 120
pic; ev socle_debut
sleep 120
ev socle_fin

# 4. Installation: the images first (network time, not measured), then the first start.
app_poser "$CT" "$SRC"
ev pull_debut
dans bash -c 'cd /opt/banc/app && docker compose pull -q'
ev pull_fin
sleep 30
pic; ev installation_debut
dans bash -c 'cd /opt/banc/app && docker compose up -d --quiet-pull' > /dev/null
SAIN=$(gen timeout 600 sh -c "until curl -fsS -m 1 '$APP_SANTE' 2>/dev/null | grep -q '$APP_SANTE_MOTIF'; do sleep 0.1; done; date +%s.%N")
echo "$SAIN sain" >> "$EV"
sleep 60
ev installation_fin

# 5. The accounts of the profile.
USERS=$(app_utilisateurs "$PROFIL")
meta utilisateurs "$USERS"
ev comptes_debut
dans /opt/banc/comptes.sh "$USERS"
ev comptes_fin
pct pull "$CT" /opt/banc/comptes.json "$OUT/comptes.json"
meta taille_installee "$(du_donnees)"

if [ "$USERS" -eq 0 ]; then
  # 6a. Idle: installed, first account created, no data.
  ev repos_debut
  sleep "$REPOS_VIDE_S"
  pic; ev mesure_debut
  sleep "$MESURE_VIDE_S"
  ev mesure_fin
else
  # 6b. Light and sustained: the reference dataset, then the load.
  gen mkdir -p /opt/banc
  pct push "$GEN" "$OUT/comptes.json" /opt/banc/comptes.json
  pct push "$GEN" "$SRC/semis.js" /opt/banc/semis.js
  pct push "$GEN" "$SRC/charge.js" /opt/banc/charge.js
  gen rm -f /opt/banc/k6.csv.gz /opt/banc/resume.json
  TOTAL=$(app_jeu_de_donnees "$USERS")
  meta jeu_de_donnees "$TOTAL"
  ev semis_debut
  gen /usr/local/bin/k6 run --no-usage-report -q -e COMPTES=/opt/banc/comptes.json -e TOTAL="$TOTAL" /opt/banc/semis.js > "$OUT/semis.txt" 2>&1 || ev semis_seuil_franchi
  ev semis_fin
  meta taille_jeu "$(du_donnees)"
  DEBUT_MS=$(( $(date +%s%3N) + 15000 ))
  DEBUT=$(awk -v m="$DEBUT_MS" 'BEGIN { printf "%.3f", m / 1000 }')
  MESURE_DEBUT=$(awk -v d="$DEBUT" -v c="$CHAUFFE_S" 'BEGIN { printf "%.3f", d + c }')
  MESURE_FIN=$(awk -v d="$MESURE_DEBUT" -v m="$MESURE_S" 'BEGIN { printf "%.3f", d + m }')
  gen env K6_CSV_TIME_FORMAT=unix_micro /usr/local/bin/k6 run --no-usage-report -q \
    -e COMPTES=/opt/banc/comptes.json -e DEBUT="$DEBUT_MS" -e CHAUFFE_S="$CHAUFFE_S" -e MESURE_S="$MESURE_S" \
    -e RESUME=/opt/banc/resume.json --out csv=/opt/banc/k6.csv.gz /opt/banc/charge.js > "$OUT/k6.txt" 2>&1 &
  K6=$!
  echo "$DEBUT chauffe_debut" >> "$EV"
  attendre "$MESURE_DEBUT"
  pic; echo "$MESURE_DEBUT mesure_debut" >> "$EV"
  wait "$K6" || ev k6_seuil_franchi
  echo "$MESURE_FIN mesure_fin" >> "$EV"
  pct pull "$GEN" /opt/banc/k6.csv.gz "$OUT/k6.csv.gz"
  pct pull "$GEN" /opt/banc/resume.json "$OUT/resume.json"
fi
ev fin

# 7. After the run: data size, container state, logs, versions.
meta taille_fin "$(du_donnees)"
dans bash -c 'docker inspect --format "{{.Name}} restarts={{.RestartCount}} oomkilled={{.State.OOMKilled}} status={{.State.Status}} started={{.State.StartedAt}}" $(docker ps -aq)' > "$OUT/conteneurs.txt"
dans bash -c 'cd /opt/banc/app && docker compose logs --no-color --tail 300' > "$OUT/journal-application.txt" 2>&1 || true
for image in $APP_IMAGES; do
  dans docker image inspect --format "{{index .RepoDigests 0}} {{.Id}} {{.Size}}" "$image" >> "$OUT/images.txt"
done
meta processeur "$(lscpu | sed -n 's/^Model name: *//p')"
meta fils_hote "$(nproc)"
meta noyau "$(uname -r)"
meta proxmox "$(pveversion | cut -d/ -f2)"
meta systeme "$(dans sh -c '. /etc/os-release; echo $PRETTY_NAME')"
meta docker "$(dans docker version --format '{{.Server.Version}}')"
meta compose "$(dans docker compose version --short)"
meta k6 "$(gen /usr/local/bin/k6 version | awk '{ print $2 }')"
