#!/bin/sh
# One library, every server: two full runs and two extra scan-only runs each, then the seek check.
#   BENCH_MUSIC=/path/to/library BENCH_LIBRARY=public ./run_all.sh
# Results go to results/$BENCH_LIBRARY/. Stops if game mode turns on. Host load is logged before every run.
set -u
cd "$(dirname "$0")" || exit 1
: "${BENCH_MUSIC:?set BENCH_MUSIC}" "${BENCH_LIBRARY:?set BENCH_LIBRARY (public or real)}"
OUT=results/$BENCH_LIBRARY
SERVERS=${SERVERS:-"leyr navidrome gonic jellyfin plex"}
IDLE=${IDLE:-300}
mkdir -p "$OUT"
export BENCH_LONG_FLAC=${BENCH_LONG_FLAC:-"Long Form Drone"}
export BENCH_LONG_FLAC_FILE=${BENCH_LONG_FLAC_FILE:-$(find "$BENCH_MUSIC" -name "*.flac" -path "*$BENCH_LONG_FLAC*" | head -1)}
step() {
    # step SERVER --phase P --run N [...]; a finished run is skipped, so an interrupted batch can be restarted
    if [ -f "$OUT/$1-$3-$5.json" ]; then echo "skip $*"; return; fi
    while gamemoded -s 2>&1 | grep -q 'is active'; do echo "$(date -Is) game mode active, waiting before: $*" | tee -a "$OUT/progress.log"; sleep 60; done
    echo "$(date -Is) load=$(cut -d' ' -f1-3 /proc/loadavg) $*" | tee -a "$OUT/progress.log"
    ps -eo pcpu,comm --sort=-pcpu | sed -n 2,6p | tr '\n' ';' | sed 's/^/  top: /; s/$/\n/' >> "$OUT/progress.log"
    nice -n 10 python3 bench.py "$@" --out "$OUT" || echo "FAILED: $*" | tee -a "$OUT/progress.log"
}
for s in $SERVERS; do step "$s" --phase main --run 1 --idle "$IDLE"; done
for r in ${SCAN_RUNS:-2 3}; do for s in $SERVERS; do step "$s" --phase scan --run "$r"; done; done
for s in $SERVERS; do step "$s" --phase main --run 2 --idle "$IDLE"; done
for s in $SERVERS; do
    grep -q "^{\"$s\"" "$OUT/seek-validation.jsonl" 2>/dev/null && continue
    echo "$(date -Is) seek check $s" | tee -a "$OUT/progress.log"
    nice -n 10 python3 validate_seek.py "$s" >> "$OUT/seek-validation.jsonl" || echo "FAILED: seek $s" | tee -a "$OUT/progress.log"
done
echo "$(date -Is) $BENCH_LIBRARY done" | tee -a "$OUT/progress.log"
