#!/usr/bin/env bash
# The end to end acceptance run. Prints every check as pass, fail or skipped.
# Every fixture here is a generated test signal (tone, noise and exact zero
# made by sox and ffmpeg), not a recording. A real recording is only read
# when MINUTES_REAL names one (check 9a).
set -uo pipefail
root=$(cd "$(dirname "$0")/.." && pwd)
work=$(mktemp -d)
trap 'tmux kill-session -t minutes-e2e 2>/dev/null; rm -rf "$work"' EXIT
mkdir -p "$root/out"
cd "$work" || exit 1

failed=0
check() {
  local n=$1
  shift
  if "$@"; then echo "check $n: pass"; else echo "check $n: fail"; failed=$((failed + 1)); fi
}
say() { echo "  $*"; }
no() { say "$*"; return 1; }
# line: an exact line in the text; has: a substring
line() { grep -qxF -- "$1" <<<"$2" || no "missing line: $1"; }
has() { grep -qF -- "$1" <<<"$2" || no "missing: $1"; }
squeeze() { tr -s ' '; }
items() { grep -E '^ [0-9]+\. ' <<<"$1"; } # the item rows of a squeezed document
near() { awk -v a="$1" -v b="$2" -v d="$3" 'BEGIN { x = a - b; if (x < 0) x = -x; exit !(x <= d) }'; }
db() { awk -v a="$1" 'BEGIN { printf "%.2f", 20 * log(a) / log(10) }'; }
rms() { sox "$1" -n stat 2>&1 | awk '/^RMS +amplitude/ { print $3 }'; }
peak() { sox "$1" -n stat 2>&1 | awk '/^Maximum amplitude/ { print $3 }'; }

echo "Generated test signals only, unless check 9a names a real recording."
(cd "$root" && go build -o "$work/minutes" .) || exit 1
bash "$root/scripts/fixture.sh" fixture.wav >/dev/null || exit 1
./minutes fixture.wav >base.txt 2>base.err
base_exit=$?
mv gaps.wav fixture-gaps.wav
base=$(squeeze <base.txt)
base_items=$(items "$base")

c1() { (cd "$root" && go vet ./... && go test -count=1 ./...); }

c2() {
  local n r=0
  n=$(./minutes)
  [ "$(./minutes | wc -l)" -le 20 ] || no "notice is over 20 lines" || r=1
  [ "$(./minutes | awk '{ if (length($0) > m) m = length($0) } END { print m }')" -le 64 ] || no "notice is over 64 columns" || r=1
  ! grep -q $'\x1b' <<<"$n" || no "ESC byte in the notice" || r=1
  [ "$(tail -n 1 <<<"$n")" = "normal is dead" ] || no "last line" || r=1
  ./minutes >/dev/null || no "exit status" || r=1
  [ "$(./minutes -h)" = "$n" ] || no "-h differs" || r=1
  say "notice: $(./minutes | wc -l) lines, widest $(./minutes | awk '{ if (length($0) > m) m = length($0) } END { print m }') columns"
  # the patterns are spelled so this file never matches itself; CARD.md is the brief and holds the lineage
  ! grep -rnI "$(printf '\xe2\x80\x94')" "$root" || no "em dash found" || r=1
  ! grep -rniwIE 'ca[g]e|lu[c]ier' --exclude=CARD.md "$root" || no "lineage name found" || r=1
  ! grep -rnI "4'3[3]" --exclude=CARD.md "$root" || no "lineage title found" || r=1
  return $r
}

c3() {
  local r=0 noise_db floor
  [ "$base_exit" = 0 ] || no "exit $base_exit" || r=1
  [ "$(head -n 1 base.txt)" = "Minutes" ] || no "first line" || r=1
  line "Items" "$base" || r=1
  [ "$(wc -l <<<"$base_items")" = 3 ] || no "item count" || r=1
  sox -n -r 16000 -b 16 -c 1 -D n.wav synth 4.2 whitenoise vol 0.003
  noise_db=$(db "$(rms n.wav)")
  floor=$(awk '$1 == "Floor" { print $2 }' <<<"$base")
  say "printed Floor $floor dBFS, sox RMS of a noise segment alone $noise_db dBFS"
  near "$floor" "$noise_db" 1.5 || no "Floor is not within 1.5 dB" || r=1
  local want=("1. 00:00:03.0 4.2 s" "2. 00:00:12.2 6.0 s -inf 0% no" "3. 00:00:25.7 8.0 s")
  for w in "${want[@]}"; do has " $w" "$base_items" || r=1; done
  awk '$1 == "1." || $1 == "3." { print $5, $7, $8 }' <<<"$base_items" | while read -r lv tone copied; do
    say "item level $lv dB, tone $tone, copied $copied"
    near "$lv" -60.2 1.0 && [ "$tone" = 100% ] && [ "$copied" = yes ] || exit 1
  done || no "items 1 and 3" || r=1
  line " Dead air 18.2 s of 34.7 s (52.4%) in 3 pauses." "$base" || r=1
  line " Longest 8.0 s, item 3, at 00:00:25.7." "$base" || r=1
  [ "$(grep -c '^ No room tone' <<<"$base")" = 1 ] && [ "$(grep -c '^ Room tone' <<<"$base")" = 1 ] || no "totals lines" || r=1
  [ "$(grep -c 'Present:' base.txt)" = 1 ] || no "Present count" || r=1
  grep -qx 'Present:  (none recorded)' base.txt || no "raw Present line" || r=1
  return $r
}

c4() {
  local r=0 d sum err
  d=$(soxi -D fixture-gaps.wav)
  say "fixture-gaps.wav: $d s, $(soxi -r fixture-gaps.wav) Hz, $(soxi -c fixture-gaps.wav) ch, $(soxi -b fixture-gaps.wav) bit, peak $(peak fixture-gaps.wav), RMS $(rms fixture-gaps.wav) (noise alone $(rms n.wav))"
  near "$d" 11.99 0.003 || no "duration" || r=1
  [ "$(soxi -r fixture-gaps.wav)/$(soxi -c fixture-gaps.wav)/$(soxi -b fixture-gaps.wav)" = 16000/1/16 ] || no "format" || r=1
  near "$(peak fixture-gaps.wav)" 0 0.0099 || no "peak: speech stand-in leaked" || r=1
  near "$(rms fixture-gaps.wav)" 0.000977 "$(awk 'BEGIN { print 0.000977 * 0.15 }')" || no "RMS off by more than 15%" || r=1
  cp fixture-gaps.wav gaps.wav
  sum=$(cksum <gaps.wav)
  ./minutes fixture.wav >again.txt 2>again.err
  local code=$?
  err=$(cat again.err)
  say "second run: exit $code, $err"
  [ "$code" = 2 ] && [ "$err" = "minutes: gaps.wav already exists. Nothing was overwritten." ] && [ ! -s again.txt ] || r=1
  [ "$(cksum <gaps.wav)" = "$sum" ] || no "gaps.wav changed" || r=1
  rm -f gaps.wav
  return $r
}

starts_lengths() { awk '{ print $2, $3 }' <<<"$1"; }
same_within() { # two item lists: same count, starts and lengths within 0.02 s
  paste -d' ' <(starts_lengths "$1") <(starts_lengths "$2") | awk '
    function s(t) { split(t, a, ":"); return a[1] * 3600 + a[2] * 60 + a[3] }
    { n++; d = s($1) - s($3); if (d < 0) d = -d; e = $2 - $4; if (e < 0) e = -e; if (d > 0.02 || e > 0.02) bad = 1 }
    END { exit bad || n != 3 }'
}

c5a() {
  sox fixture.wav -r 48000 -c 2 fixture48.wav
  local m
  m=$(./minutes -o g48.wav fixture48.wav | squeeze)
  items "$m" | sed 's/^/  /'
  same_within "$(items "$m")" "$base_items" || no "items differ" || return 1
  [ "$(soxi -r g48.wav)/$(soxi -c g48.wav)" = 48000/2 ] || no "g48.wav format" || return 1
}

c5b() {
  local r=0
  ffmpeg -loglevel error -i fixture.wav -fflags +bitexact -f wav - | cat >piped.wav
  ffmpeg -loglevel error -i fixture.wav -f wav - | cat >piped2.wav
  say "piped.wav at 36: $(xxd -s 36 -l 8 piped.wav)"
  say "piped2.wav at 36: $(xxd -s 36 -l 8 piped2.wav)"
  say "piped2.wav at 70: $(xxd -s 70 -l 8 piped2.wav)"
  [ "$(xxd -p -s 36 -l 8 piped.wav)" = 64617461ffffffff ] || no "piped.wav header" || r=1
  [ "$(xxd -p -s 36 -l 4 piped2.wav)" = 4c495354 ] && [ "$(xxd -p -s 70 -l 8 piped2.wav)" = 64617461ffffffff ] || no "piped2.wav header" || r=1
  [ "$(items "$(./minutes -o gp.wav piped.wav | squeeze)")" = "$base_items" ] || no "piped items differ" || r=1
  [ "$(items "$(./minutes -o gp2.wav piped2.wav | squeeze)")" = "$base_items" ] || no "piped2 items differ" || r=1
  return $r
}

c5d() {
  local a b
  cp fixture.wav dated.wav && touch -t 202403051200 dated.wav
  a=$(./minutes -o gd.wav dated.wav | grep 'Dated:')
  ffmpeg -loglevel error -i dated.wav -c:a pcm_s16le conv.wav && touch -r dated.wav conv.wav
  b=$(./minutes -o gc.wav conv.wav | grep 'Dated:')
  say "dated.wav: $a / converted: $b"
  [ "$a" = "Dated:    2024-03-05" ] && [ "$b" = "$a" ]
}

reject() { # file, expected stderr line
  local out err code
  out=$(./minutes -o x.wav "$1" 2>rej.err)
  code=$?
  err=$(cat rej.err)
  say "$1 -> exit $code: $err"
  echo "\$ minutes -o x.wav $1" >>"$root/out/rejections.txt"
  echo "$err" >>"$root/out/rejections.txt"
  [ "$code" = 2 ] && [ -z "$out" ] && [ "$err" = "$2" ] && [ ! -e x.wav ]
}

c6() {
  local r=0 f
  : >"$root/out/rejections.txt"
  sox fixture.wav -b 24 f24.wav
  sox fixture.wav -e floating-point -b 32 f32.wav
  ffmpeg -loglevel error -i fixture.wav fixture.m4a
  head -c 4096 /dev/urandom >noise.wav
  conv() { echo "Convert: ffmpeg -i $1 -c:a pcm_s16le $2 (on a Mac: afconvert -f WAVE -d LEI16 $1 $2) then: touch -r $1 $2"; }
  reject f24.wav "minutes: f24.wav is 24-bit. Only 16-bit PCM is read. $(conv f24.wav f2416.wav)" || r=1
  reject f32.wav "minutes: f32.wav is 32-bit float. Only 16-bit PCM is read. $(conv f32.wav f3216.wav)" || r=1
  f=$(conv fixture.m4a fixture.wav)
  reject fixture.m4a "minutes: fixture.m4a is not a WAV file. ${f/Convert:/Convert it first:}" || r=1
  f=$(conv noise.wav noise16.wav)
  reject noise.wav "minutes: noise.wav is not a WAV file. ${f/Convert:/Convert it first:}" || r=1
  local err code
  err=$(./minutes -min 0.1 fixture.wav 2>&1)
  code=$?
  say "-min 0.1 -> exit $code: $err"
  [ "$code" = 2 ] && [ "$err" = "minutes: -min must be at least 0.5." ] || r=1
  return $r
}

c7() {
  local r=0 m code
  m=$(./minutes -o z10.wav -min 10 fixture.wav)
  code=$?
  [ "$code" = 0 ] || no "exit $code" || r=1
  line "  No pause of 10.0 s or longer was found at these settings." "$m" || r=1
  line " Dead air 0.0 s of 34.7 s (0.0%) in 0 pauses." "$(squeeze <<<"$m")" || r=1
  [ "$(grep -c 'Present:' <<<"$m")" = 1 ] || no "Present count" || r=1
  [ ! -e z10.wav ] || no "a file was written" || r=1
  sox -n -r 16000 -b 16 -c 1 loud.wav synth 10 sine 440 vol 0.3
  m=$(./minutes -o zl.wav loud.wav | squeeze)
  code=$?
  [ "$code" = 0 ] || r=1
  line " Quiet digital zero only: the floor is above -30 dBFS." "$m" || r=1
  line " No pause of 2.0 s or longer was found at these settings." "$m" || r=1
  line " Dead air 0.0 s of 10.0 s (0.0%) in 0 pauses." "$m" || r=1
  [ ! -e zl.wav ] || no "a file was written for loud.wav" || r=1
  return $r
}

c8() {
  local r=0 m
  sox -n -r 16000 -b 16 -c 1 -D zeros.wav trim 0 5 && sox fixture.wav zeros.wav gated.wav
  m=$(items "$(./minutes -o gg.wav gated.wav | squeeze)")
  sed 's/^/  /' <<<"$m"
  [ "$(head -n 3 <<<"$m")" = "$base_items" ] || no "first three items changed" || r=1
  [ "$(wc -l <<<"$m")" = 4 ] && grep -q '^ 4\. .* 0% no$' <<<"$m" || no "fourth item" || r=1
  sox -D -n -r 16000 -b 16 -c 1 tone.wav synth 5 sine 440 vol 0.3
  sox -D -n -r 16000 -b 16 -c 1 zero.wav trim 0 6
  sox -D tone.wav zero.wav tone.wav tz.wav
  m=$(./minutes -o gtz.wav tz.wav)
  [ $? = 0 ] || no "tz.wav exit status" || r=1
  m=$(squeeze <<<"$m")
  line " Quiet digital zero only: the floor is above -30 dBFS." "$m" || r=1
  [ "$(items "$m")" = " 1. 00:00:05.0 6.0 s -inf 0% no" ] || no "tz item: $(items "$m")" || r=1
  line " Dead air 6.0 s of 16.0 s (37.5%) in 1 pause." "$m" || r=1
  line " No room tone 1 pause, 6.0 s: digital zero in the file." "$m" || r=1
  ! grep -q '^ Room tone' <<<"$m" || no "Room tone line printed" || r=1
  [ ! -e gtz.wav ] || no "a file was written" || r=1
  return $r
}

# dur() back to seconds: "18.2 s", "41 min 07 s", "2 h 03 min 41 s"
secs() { awk '{ t = 0; for (i = 1; i < NF; i++) { if ($(i+1) == "h") t += $i * 3600; if ($(i+1) == "min") t += $i * 60; if ($(i+1) == "s") t += $i }; print t }' <<<"$1"; }

# Invariants that hold for any input. Lengths in the table are rounded to
# 0.1 s, so sums of n rows are compared to within 0.05 s per row.
invariants() { # wav, gaps file
  local m r=0 total rows dead floor n copied want got
  m=$(./minutes -o "$2" "$1" | squeeze)
  echo "$m" | sed 's/^/    /'
  total=$(soxi -D "$1")
  rows=$(items "$m")
  n=$(grep -c . <<<"$rows")
  awk -v T="$total" '
    function s(t) { split(t, a, ":"); return a[1] * 3600 + a[2] * 60 + a[3] }
    NF { st = s($2); if (st < end - 0.1) bad = 1; end = st + $3; if (end > T + 0.1) bad = 1 }
    END { exit bad }' <<<"$rows" || no "items overlap or run past the end" || r=1
  dead=$(secs "$(sed -n 's/^ Dead air \(.*\) of .*/\1/p' <<<"$m")")
  near "$dead" "$(awk '{ t += $3 } END { print t + 0 }' <<<"$rows")" "$(awk -v n="$n" 'BEGIN { print 0.5 + n * 0.05 }')" || no "Dead air is not the sum of the Length column" || r=1
  floor=$(awk '$1 == "Floor" { print $2 }' <<<"$m")
  awk -v f="$floor" 'BEGIN { exit !(f >= -90.31) }' || no "Floor below -90.3" || r=1
  if awk -v f="$floor" 'BEGIN { exit !(f > -30) }'; then
    has "Quiet digital zero only" "$m" || r=1
    ! grep -vq ' 0% no$' <<<"$rows" || no "a row is not 0% no" || r=1
  fi
  copied=$(grep ' yes$' <<<"$rows" || true)
  if [ -n "$copied" ]; then
    want=$(awk '{ t += $3 - 0.10; k++ } END { print t - (k - 1) * 0.010 }' <<<"$copied")
    got=$(soxi -D "$2")
    say "$2: $got s, formula on the copied rows $want s"
    near "$got" "$want" "$(awk -v k="$(grep -c . <<<"$copied")" 'BEGIN { print 0.01 + k * 0.05 }')" || no "gaps length" || r=1
  fi
  say "$n items checked"
  return $r
}

c9a() {
  if [ -z "${MINUTES_REAL:-}" ]; then
    echo "check 9a: skipped, no real recording given"
    return 2
  fi
  invariants "$MINUTES_REAL" real-gaps.wav || return 1
  if [ -z "${MINUTES_SOURCE:-}" ]; then
    echo "check 9a dated: skipped, no source file given"
    return 0
  fi
  if command -v ffmpeg >/dev/null; then
    ffmpeg -loglevel error -i "$MINUTES_SOURCE" -c:a pcm_s16le src.wav
  else
    afconvert -f WAVE -d LEI16 "$MINUTES_SOURCE" src.wav
  fi
  touch -r "$MINUTES_SOURCE" src.wav
  [ "$(./minutes -o src-gaps.wav src.wav | grep 'Dated:')" = "Dated:    $(date -r "$MINUTES_SOURCE" +%F)" ] || no "Dated: is not the source's date"
}

timed() { # label, minutes args...
  local label=$1
  shift
  /usr/bin/time -v ./minutes "$@" >"$label.txt" 2>"$label.time"
  local wall rss
  wall=$(awk -F': ' '/Elapsed \(wall clock\)/ { n = split($2, a, ":"); s = 0; for (i = 1; i <= n; i++) s = s * 60 + a[i]; print s }' "$label.time")
  rss=$(awk -F': ' '/Maximum resident set size/ { printf "%.1f", $2 / 1024 }' "$label.time")
  say "$label: $wall s wall, $rss MB peak resident"
  awk -v w="$wall" -v m="$rss" 'BEGIN { exit !(w < 10 && m < 64) }' || no "$label is over 10 s or 64 MB"
}

c9b() {
  local r=0 m
  sox fixture.wav big.wav repeat 206
  sox -n -r 16000 -b 16 -c 1 hour.wav synth 3600 whitenoise vol 0.003
  say "big.wav $(soxi -D big.wav) s, hour.wav $(soxi -D hour.wav) s (generated)"
  timed big -o bigg.wav big.wav || r=1
  # long totals wrap at 64 columns, so the totals are read as one paragraph
  m=$(tr '\n' ' ' <big.txt | squeeze)
  sed -n 's/.*\(Dead air [^.]*\.[^.]*\.\).*/  \1/p' <<<"$m"
  has "in 621 pauses." "$m" || r=1
  has " Dead air 1 h 02 min 47 s of " "$m" || r=1
  timed hour -o hourg.wav hour.wav || r=1
  m=$(squeeze <hour.txt)
  items "$m" | sed 's/^/  /'
  has "in 1 pause." "$(tr '\n' ' ' <hour.txt | squeeze)" && near "$(items "$m" | awk '{ print $3 }')" 3600 1 || no "one pause of about 3600 s" || r=1
  say "hourg.wav: $(soxi -D hourg.wav) s"
  cp big.txt "$root/out/big-minutes.txt"
  cp hour.txt "$root/out/hour-minutes.txt"
  rm -f big.wav bigg.wav hour.wav hourg.wav
  return $r
}

c10() {
  local r=0 cap col
  tmux kill-session -t minutes-e2e 2>/dev/null
  tmux new-session -d -s minutes-e2e -x 64 -y 48 -c "$work" 'bash --norc --noprofile'
  tmux send-keys -t minutes-e2e "PS1='$ '; clear; ./minutes -o tg.wav fixture.wav | tee pane.txt" Enter
  for _ in $(seq 50); do grep -q '^normal is dead$' pane.txt 2>/dev/null && break; sleep 0.1; done
  sleep 0.3
  cap=$(tmux capture-pane -p -t minutes-e2e | sed 's/ *$//')
  echo "$cap" >"$root/out/tmux-64.txt"
  [ "$(tmux display -p -t minutes-e2e '#{pane_width}')" = 64 ] || no "pane is not 64 columns" || r=1
  while IFS= read -r l; do
    [ -z "$l" ] && continue
    grep -qxF -- "$l" <<<"$cap" || { no "wrapped or missing in the pane: $l"; r=1; }
  done < <(sed 's/ *$//' pane.txt)
  col=$(awk 'index($0, "Copied") && /Item/ { print index($0, "Copied") }' <<<"$cap")
  awk -v c="$col" '/^  [0-9]+\. / { if (index($0, $NF) != c) bad = 1; n++ } END { exit bad || !n }' <<<"$cap" || no "Copied column does not line up" || r=1
  say "pane width $(tmux display -p -t minutes-e2e '#{pane_width}'), Copied column at $col"
  tmux kill-session -t minutes-e2e
  local hits
  hits=$(cd "$root" && grep -c "(none recorded)" ./*.go | grep -v ':0$')
  say "(none recorded) in source: $hits"
  [ "$hits" = "./report.go:1" ] || no "the string is not in exactly one place" || r=1
  return $r
}

c11() {
  local r=0 f os arch
  (cd "$root" && bash scripts/release.sh >/dev/null) || return 1
  for f in minutes-darwin-arm64 minutes-darwin-amd64 minutes-linux-amd64 minutes-linux-arm64 minutes-windows-amd64.exe; do
    os=$(cut -d- -f2 <<<"$f")
    arch=$(cut -d- -f3 <<<"$f" | sed 's/\.exe$//')
    local info
    info=$(go version -m "$root/dist/$f")
    if [ -s "$root/dist/$f" ] && grep -q 'CGO_ENABLED=0' <<<"$info" && grep -q "GOOS=$os" <<<"$info" && grep -q "GOARCH=$arch" <<<"$info"; then
      say "dist/$f: $(wc -c <"$root/dist/$f") bytes, CGO_ENABLED=0 GOOS=$os GOARCH=$arch"
    else
      no "dist/$f" || r=1
    fi
  done
  if [ "$(uname -s)/$(uname -m)" = Linux/aarch64 ]; then
    [ "$("$root/dist/minutes-linux-arm64")" = "$(./minutes)" ] || no "linux-arm64 notice differs" || r=1
    say "dist/minutes-linux-arm64 run: prints the notice; the other four: not run"
  fi
  return $r
}

check 1 c1
check 2 c2
check 3 c3
check 4 c4
check 5a c5a
check 5b c5b
if command -v afconvert >/dev/null; then
  check 5c bash -c 'afconvert -f WAVE -d LEI16 fixture.wav mac.wav && [ "$(./minutes -o gm.wav mac.wav | tr -s " " | grep -E "^ [0-9]+\. ")" = "$0" ]' "$base_items"
else
  echo "check 5c: skipped, no afconvert"
fi
check 5d c5d
check 6 c6
check 7 c7
check 8 c8
c9a
case $? in 0) echo "check 9a: pass" ;; 1) echo "check 9a: fail"; failed=$((failed + 1)) ;; esac
if [ -n "${MINUTES_DRY:-}" ]; then
  echo "invariants of check 9a, dry run on a generated file:"
  check 9a-dry invariants "$MINUTES_DRY" dry-gaps.wav
fi
check 9b c9b
check 10 c10
check 11 c11

./minutes >"$root/out/notice.txt"
cp base.txt "$root/out/fixture-minutes.txt"
cp fixture-gaps.wav "$root/out/fixture-gaps.wav"
echo "failed: $failed"
exit $((failed > 0))
