#!/usr/bin/env bash
# Runs every command published in the guide, with the exact page text (episode.wav -> input, cut*.wav -> output), on the test episode and two edge inputs.
# Usage: test-run.sh <episode-quiet.wav> <episode-fan.wav> <outdir>   (edge inputs = fan episode and a 3 s digital-silence file)
Q=$1; F=$2; O=$3; mkdir -p "$O"; LOG=$O/commands.log; : > "$LOG"
ffmpeg -v error -y -f lavfi -i anullsrc=r=16000:cl=mono -t 3 "$O/allsilent.wav"
S1="silenceremove=start_periods=1:start_threshold=-40dB:stop_periods=-1:stop_duration=0.5:stop_threshold=-40dB"
run() { # label, input, output file or "", page text
  local label=$1 in=$2 out=$3 page=$4
  local cmd=${page//episode.wav/$in}; cmd=${cmd//cut-padded.wav/$out}; cmd=${cmd//cut.wav/${out:-$in}}
  echo "published: $page" >> "$LOG"
  echo "command as run: $cmd  ($label)" >> "$LOG"
  eval "$cmd" </dev/null >"$O/last.txt" 2>&1; local rc=$?
  echo "exit=$rc" >> "$LOG"
  [ -n "$out" ] && { [ -s "$out" ] && echo "out_duration_s=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$out")" >> "$LOG" || echo "out_duration_s=N/A" >> "$LOG"; echo "out_bytes=$(wc -c <"$out")" >> "$LOG"; }
  if grep -q Summary "$O/last.txt"; then sed -n "/Summary/,\$p" "$O/last.txt" | grep -E "^ +I:" | sed "s/^/  integrated loudness/" >> "$LOG"
  else grep -E "mean_volume|max_volume" "$O/last.txt" | sed "s/.*\] /  /" >> "$LOG"; case "$page" in ffprobe*) echo "  duration_s=$(cat "$O/last.txt")" >> "$LOG";; esac; fi
}
for pair in "test:$Q" "edge-fan:$F" "edge-allsilent:$O/allsilent.wav"; do
  tag=${pair%%:*}; in=${pair#*:}
  [ "$tag" != test ] && echo "edge: $tag" >> "$LOG" || echo "test: episode-quiet" >> "$LOG"
  run "room tone" "$in" "" "ffmpeg -hide_banner -ss 0 -t 1 -i episode.wav -af volumedetect -f null -"
  run "cut -40 dB, 0.5 s" "$in" "$O/$tag-a.wav" "ffmpeg -y -i episode.wav -af \"$S1\" cut.wav"
  run "cut with 0.2 s kept" "$in" "$O/$tag-b.wav" "ffmpeg -y -i episode.wav -af \"$S1:stop_silence=0.2\" cut-padded.wav"
  run "input duration" "$in" "" "ffprobe -v error -show_entries format=duration -of csv=p=0 episode.wav"
  run "output duration" "$O/$tag-a.wav" "" "ffprobe -v error -show_entries format=duration -of csv=p=0 cut.wav"
  run "loudness of cut" "$O/$tag-a.wav" "" "ffmpeg -hide_banner -i cut.wav -af ebur128 -f null -"
done
