#!/usr/bin/env bash
# End to end acceptance run, checks 2 to 12 of CARD.md, on real child processes.
# Run from the project folder: scripts/e2e.sh. Needs go, sox, soxi, tmux, script.
# The peals it captures are kept in out/.
set -u
cd "$(dirname "$0")/.."
go build -o tailors . || exit 1
export TAILORS_PLAYER=$PWD/scripts/capture.sh CAPTURE_DIR=$(mktemp -d)
mkdir -p out
fails=0
ok() { echo "ok   $*"; }
no() { echo "FAIL $*"; fails=$((fails + 1)); }
fresh() { rm -f "$CAPTURE_DIR/peal.wav"; }
captured() { # wait for the detached player to hand over the peal
	for _ in $(seq 50); do [ -f "$CAPTURE_DIR/peal.wav" ] && return 0; sleep 0.1; done
	return 1
}
len() { soxi -D "$1" 2>/dev/null; }
near() { awk -v a="$1" -v b="$2" 'BEGIN { exit !(a - b < 0.01 && b - a < 0.01) }'; }
ms() { echo $((($(date +%s%N) - $1) / 1000000)); }
T="tmux -L tailors-e2e -f /dev/null"

echo "== 2 exit status passes through"
for c in '7|sh -c exit\ 7' '0|true' '1|false' '143|sh -c kill\ -TERM\ \$\$'; do
	want=${c%%|*}
	eval "./tailors ${c#*|}" 2>/dev/null; got=$?
	[ "$got" = "$want" ] && ok "2 ${c#*|}: $got" || no "2 ${c#*|}: $got, want $want"
done

echo "== 3 input and output pass through"
got=$(echo hi | ./tailors cat 2>/dev/null)
[ "$got" = hi ] && ok "3 echo hi | tailors cat: $got" || no "3 cat gave '$got'"
./tailors sh -c 'echo out; echo err >&2' 2>"$CAPTURE_DIR/err.txt" >"$CAPTURE_DIR/out.txt"
[ "$(cat "$CAPTURE_DIR/out.txt")" = out ] && [ "$(cat "$CAPTURE_DIR/err.txt")" = err ] &&
	ok "3 out.txt: $(cat "$CAPTURE_DIR/out.txt"), err.txt: $(cat "$CAPTURE_DIR/err.txt")" ||
	no "3 out.txt '$(cat "$CAPTURE_DIR/out.txt")' err.txt '$(cat "$CAPTURE_DIR/err.txt")'"

echo "== 4 short run: nine strokes"
captured; fresh
./tailors sleep 2 2>/dev/null; captured; cp "$CAPTURE_DIR/peal.wav" out/sleep-2.wav
fmt="$(soxi -D out/sleep-2.wav) s, $(soxi -r out/sleep-2.wav) Hz, $(soxi -c out/sleep-2.wav) ch, $(soxi -b out/sleep-2.wav) bit"
near "$(len out/sleep-2.wav)" 4.8 && [ "$fmt" = "4.800000 s, 22050 Hz, 1 ch, 16 bit" ] && ok "4 $fmt" || no "4 $fmt"
s=$(strings out/sleep-2.wav | grep tailors:)
[ "$s" = "tailors: 2 s, exit 0, 9 strokes" ] && ok "4 strings: $s" || no "4 strings: $s"
grep -q sleep out/sleep-2.wav && no "4 the peal holds command text" || ok "4 no command text in the peal"
echo "   ffprobe: $(ffprobe -hide_banner out/sleep-2.wav 2>&1 | grep comment | tr -s ' ')"

echo "== 5 one minute aware (61 s)"
fresh
./tailors sleep 61 2>/dev/null; captured; cp "$CAPTURE_DIR/peal.wav" out/sleep-61.wav
s=$(strings out/sleep-61.wav | grep tailors:)
near "$(len out/sleep-61.wav)" 5.6 && [ "$s" = "tailors: 1 min 1 s, exit 0, 10 strokes" ] &&
	ok "5 $(len out/sleep-61.wav) s, strings: $s" || no "5 $(len out/sleep-61.wav) s, strings: $s"

echo "== 6 a kill gets three, a failure the flat stroke"
fresh; ./tailors sh -c 'kill -TERM $$' 2>/dev/null; captured; cp "$CAPTURE_DIR/peal.wav" out/kill-term.wav
near "$(len out/kill-term.wav)" 2.4 && ok "6 kill: $(len out/kill-term.wav) s" || no "6 kill: $(len out/kill-term.wav) s"
fresh; ./tailors false 2>/dev/null; captured; cp "$CAPTURE_DIR/peal.wav" out/false.wav
near "$(len out/false.wav)" 4.8 && ok "6 false: $(len out/false.wav) s" || no "6 false: $(len out/false.wav) s"
fresh; ./tailors true 2>/dev/null; captured; cp "$CAPTURE_DIR/peal.wav" out/true.wav
sox -m -v 1 out/false.wav -v -1 out/true.wav "$CAPTURE_DIR/diff.wav"
before=$(sox "$CAPTURE_DIR/diff.wav" -n trim 0 3.2 stat 2>&1 | awk '/Maximum amplitude/ { print $3 }')
after=$(sox "$CAPTURE_DIR/diff.wav" -n trim 3.2 stat 2>&1 | awk '/Maximum amplitude/ { print $3 }')
[ "$before" = 0.000000 ] && [ "$after" != 0.000000 ] &&
	ok "6 false minus true: max $before before 3.2 s, $after after" || no "6 diff: $before before, $after after"

echo "== 7 never blocks"
TAILORS_PLAYER=$PWD/scripts/slow.sh
t0=$(date +%s%N); ./tailors true 2>/dev/null; a=$(ms "$t0")
t0=$(date +%s%N); ./tailors true 2>/dev/null | cat; b=$(ms "$t0")
[ "$a" -lt 1000 ] && [ "$b" -lt 1000 ] && ok "7 tailors true: ${a} ms, tailors true | cat: ${b} ms" || no "7 ${a} ms, ${b} ms"
# the player itself, not any shell whose command line merely mentions slow.sh
ringing() { pgrep -f "^/bin/sh $PWD/scripts/slow.sh"; }
ringing >/dev/null && echo "   slow.sh is ringing: pid $(ringing | tr '\n' ' ')"
s=$(./tailors 2>&1 >/dev/null)
t0=$(date +%s%N) # SIGTERM is delivered when the player is next scheduled
for _ in $(seq 100); do ringing >/dev/null || break; sleep 0.02; done
[ "$s" = "tailors: the bell was stopped." ] && ! ringing >/dev/null &&
	ok "7 bare tailors: '$s', pgrep finds no slow.sh after $(ms "$t0") ms" || no "7 '$s', pgrep: $(ringing)"
s=$(./tailors 2>&1 >/dev/null)
[ "$s" = "tailors: no bell was ringing." ] && ok "7 again: '$s'" || no "7 again: '$s'"
TAILORS_PLAYER=$PWD/scripts/capture.sh

echo "== 8 not found means no bell"
fresh
s=$(./tailors nosuchcommand 2>&1); rc=$?
sleep 1
[ "$s" = 'tailors: nothing to toll. "nosuchcommand" was not found.' ] && [ $rc = 127 ] && [ ! -e "$CAPTURE_DIR/peal.wav" ] &&
	ok "8 '$s', exit $rc, no peal.wav" || no "8 '$s', exit $rc"
s=$(./tailors ./README.md 2>&1); rc=$?
[ $rc = 126 ] && ok "8 not executable: '$s', exit $rc" || no "8 not executable: exit $rc"

echo "== 9 the notice fits the grid"
lines=$(./tailors 2>/dev/null | wc -l)
cols=$(./tailors 2>/dev/null | awk '{ if (length($0) > m) m = length($0) } END { print m }')
esc=$(./tailors 2>/dev/null | grep -c $'\x1b')
last=$(./tailors 2>/dev/null | tail -n 1)
[ "$lines" -le 20 ] && [ "$cols" -le 64 ] && [ "$esc" = 0 ] && [ "$last" = "normal is dead" ] &&
	./tailors 2>/dev/null | grep -qx Tellers &&
	ok "9 notice: $lines lines, $cols columns, $esc ESC bytes, Tellers, ends '$last'" ||
	no "9 notice: $lines lines, $cols columns, $esc ESC, ends '$last'"
[ "$(./tailors --help)" = "$(./tailors 2>/dev/null)" ] && ok "9 --help prints the same notice" || no "9 --help"
tail -n 3 README.md | grep -q . && echo "   README ends: $(tail -n 3 README.md | tr '\n' '|')"
[ "$(sed -n '$p' README.md)" = "normal is dead" ] && tail -n 3 README.md | head -n 1 | grep -qx 'The tellers follow the custom of the parish.' &&
	tail -n 2 README.md | head -n 1 | grep -Eq '^Nine stroke peak: [0-9.]+ of full scale\.$' &&
	ok "9 README colophon" || no "9 README colophon"
n=$(grep -rIln $'\xe2\x80\x94' . | wc -l)
[ "$n" = 0 ] && ok "9 no em dash in any text file" || no "9 em dash in $n files"

echo "== 10 record line in a real terminal"
o=$(script -qec "./tailors sh -c 'sleep 1; exit 2'" /dev/null | tr -d '\r')
[ "$o" = $'tailors: 1 s, exit \x1b[38;2;236;94;82m2\x1b[39m, 9 strokes.' ] &&
	ok "10 pty: $(printf '%s' "$o" | od -c | head -n 3 | tr -s ' ' | tr '\n' ' ')" || no "10 pty: $(printf '%q' "$o")"
o=$(NO_COLOR=1 script -qec "./tailors sh -c 'sleep 1; exit 2'" /dev/null | tr -d '\r')
[ "$o" = "tailors: 1 s, exit 2, 9 strokes." ] && ok "10 NO_COLOR=1: '$o', no ESC" || no "10 NO_COLOR: $(printf '%q' "$o")"
script -qec "./tailors true 2>$CAPTURE_DIR/rec.txt" /dev/null >/dev/null
[ ! -s "$CAPTURE_DIR/rec.txt" ] && ok "10 stderr to a file: no record line" || no "10 file holds: $(cat "$CAPTURE_DIR/rec.txt")"

echo "== 11 Ctrl-C ends the command and is tolled"
$T kill-server 2>/dev/null
$T new-session -d -s e2e -x 100 -y 30 "env -i HOME=$HOME PATH=$PATH TERM=xterm-256color bash --norc --noprofile -i"
sleep 0.5
$T send-keys -t e2e "cd $PWD; export TAILORS_PLAYER=$TAILORS_PLAYER CAPTURE_DIR=$CAPTURE_DIR; PS1='$ '; clear" Enter
sleep 0.5; fresh
$T send-keys -t e2e './tailors sleep 30' Enter; sleep 1
$T send-keys -t e2e C-c; sleep 1.5
$T send-keys -t e2e 'echo $?' Enter; sleep 0.5
pane=$($T capture-pane -p -t e2e)
captured; cp "$CAPTURE_DIR/peal.wav" out/ctrl-c.wav
echo "$pane" | grep -v '^$' | sed 's/^/   | /'
echo "$pane" | grep -q 'killed by SIGINT, 3 strokes\.$' && echo "$pane" | grep -qx 130 && near "$(len out/ctrl-c.wav)" 2.4 &&
	ok "11 pane shows the kill and 130, peal $(len out/ctrl-c.wav) s" || no "11 pane or peal ($(len out/ctrl-c.wav) s)"
sox out/ctrl-c.wav -t raw -e signed -b 16 "$CAPTURE_DIR/c.raw"
sox out/kill-term.wav -t raw -e signed -b 16 "$CAPTURE_DIR/k.raw"
cmp "$CAPTURE_DIR/c.raw" "$CAPTURE_DIR/k.raw" && ok "11 PCM of the Ctrl-C peal equals the SIGTERM peal ($(wc -c <"$CAPTURE_DIR/c.raw") bytes)" || no "11 PCM differs"
fresh
$T send-keys -t e2e 'clear' Enter; sleep 0.3
$T send-keys -t e2e 'for i in 1 2; do ./tailors sleep 30; echo NEXT; done' Enter; sleep 1
$T send-keys -t e2e C-c; sleep 1.5
$T send-keys -t e2e 'echo $?' Enter; sleep 0.5
pane=$($T capture-pane -p -t e2e)
captured; cp "$CAPTURE_DIR/peal.wav" out/ctrl-c-loop.wav
echo "$pane" | grep -v '^$' | sed 's/^/   | /'
! echo "$pane" | grep -qx NEXT && echo "$pane" | grep -qx 130 && [ "$(echo "$pane" | grep -c 'killed by SIGINT')" = 1 ] &&
	near "$(len out/ctrl-c-loop.wav)" 2.4 &&
	ok "11 loop stopped: no NEXT, 130, one peal of $(len out/ctrl-c-loop.wav) s" || no "11 loop"
$T kill-server

echo "== 12 no player: the peal is the output"
empty=$(mktemp -d)
o=$(script -qec "env -u TAILORS_PLAYER PATH=$empty $PWD/tailors /bin/true; echo \$?" /dev/null | tr -d '\r')
echo "$o" | sed 's/^/   | /'
path=$(echo "$o" | sed -n 's/^tailors: no player found. The peal is at \(.*\)\. It can be carried\.$/\1/p')
[ -n "$path" ] && [ "$(echo "$o" | tail -n 1)" = 0 ] && near "$(len "$path")" 4.8 &&
	ok "12 no player: peal at $path, $(len "$path") s, exit 0" || no "12 no player"
o=$(env -u TAILORS_PLAYER PATH="$empty" "$PWD/tailors" /bin/true 2>&1)
[ -z "$o" ] && ok "12 with stderr not a terminal, nothing is printed" || no "12 non-tty printed: $o"
rmdir "$empty"

./tailors >/dev/null 2>&1
rm -rf "$CAPTURE_DIR" tailors
echo "== $fails failed"
exit $((fails > 0))
