#!/bin/bash
# SPDX-License-Identifier: MIT
# Stileex measured requirements bench: the queue of campaigns, on the Proxmox host, as root.
#
#   file.sh ajoute <campagne.sh arguments>   queue a campaign (BANC_JOUR, if set, goes with it)
#   file.sh liste                            what waits, what runs, what is done or failed
#   file.sh traite                           run the queue, oldest first, until it is empty
#
# `traite` is what banc-file.service runs, started by banc-file.path as soon as a job waits: a
# campaign runs in systemd, logged in the journal, and no session has to stay awake to watch it.
# A job waits for the bench lock rather than failing on it, so a campaign started by hand delays the
# queue and is never broken by it.
set -uo pipefail

BANC=$(cd "$(dirname "$0")" && pwd)
FILE=${BANC_FILE:-/root/banc-mesures/file}
VERROU=${BANC_VERROU:-/root/banc-mesures.lock}
mkdir -p "$FILE/attente" "$FILE/en-cours" "$FILE/faits" "$FILE/echecs"

case "${1:-}" in
  ajoute)
    shift
    [ $# -ge 2 ] || { echo "usage: file.sh ajoute mesure <app> | valide <app> <vcpu> <mib> | essai <app>" >&2; exit 2; }
    nom="$(date -u +%Y%m%dT%H%M%SZ)-$$-$2-$1"
    { printf 'ARGS=%q\n' "$*"; [ -n "${BANC_JOUR:-}" ] && printf 'BANC_JOUR=%q\n' "$BANC_JOUR"; } > "$FILE/attente/$nom.tmp"
    mv "$FILE/attente/$nom.tmp" "$FILE/attente/$nom.job"
    echo "queued: $nom"
    ;;
  liste)
    for etat in en-cours attente faits echecs; do
      echo "== $etat"
      ls -1 "$FILE/$etat" 2>/dev/null | tail -20
    done
    ;;
  traite)
    while true; do
      job=$(ls -1 "$FILE/attente"/*.job 2>/dev/null | sort | head -1)
      [ -n "$job" ] || exit 0
      nom=$(basename "$job" .job)
      mv "$job" "$FILE/en-cours/$nom.job"
      until flock -n "$VERROU" true; do sleep 60; done
      ARGS='' BANC_JOUR=''
      # shellcheck source=/dev/null
      . "$FILE/en-cours/$nom.job"
      echo "$(date -u +%FT%TZ) start $nom: campagne.sh $ARGS"
      # shellcheck disable=SC2086
      if BANC_JOUR=${BANC_JOUR:-$(date -u +%Y-%m-%d)} "$BANC/campagne.sh" $ARGS; then
        mv "$FILE/en-cours/$nom.job" "$FILE/faits/$nom.job"
        echo "$(date -u +%FT%TZ) done $nom"
      else
        rc=$?
        mv "$FILE/en-cours/$nom.job" "$FILE/echecs/$nom.job"
        echo "$(date -u +%FT%TZ) FAILED $nom (exit $rc)"
      fi
    done
    ;;
  *)
    echo "usage: file.sh ajoute <campagne.sh arguments> | liste | traite" >&2
    exit 2
    ;;
esac
