#!/usr/bin/env bash
# Acceptance run: checks 1 to 11 of CARD.md, end to end on real files.
# Needs go, cmp, tmux, uv. Run from the project folder: bash check.sh
# Works in a temporary directory; the sheets, the tmux captures and the
# recordings it makes are kept in out/.
set -u
here=$PWD
out=$here/out
mkdir -p "$out"
fails=0
ok() { echo "ok   $*"; }
no() { echo "FAIL $*"; fails=$((fails + 1)); }
has() { grep -qxF "$2" "$1" && ok "$3: $2" || no "$3: missing '$2'"; }
row() { head -n 16 "$1" | grep "^$2 "; }

echo "== 1 tests, stdlib only, text rules"
[ -z "$(gofmt -l .)" ] && ok "gofmt -l prints nothing" || no "gofmt -l: $(gofmt -l .)"
go vet ./... && ok "go vet exits 0" || no "go vet"
go test -v ./... > "$out/test.log" 2>&1 && ok "go test exits 0" || no "go test"
for n in TestIdenticalIsExactlyZero TestSubtractionEqualsDifference TestSilentBeforeFirstDifference TestFlipPeak TestStringIsSharpOfA2 TestRings TestPositions TestSheetFits TestWavHeader TestSingleFileHasNoDC; do
	grep -q "^--- PASS: $n " "$out/test.log" && ok "PASS $n" || no "$n"
done
grep 'gain peaks\|rings, longest' "$out/test.log" | sed 's/^ */     /'
[ -z "$(go list -deps ./... | grep -E '^[^/]+\.[^/]+/')" ] && ok "no third party package" || no "third party package"
[ "$(grep -c '^require' go.mod)" = 0 ] && ok "go.mod has no require" || no "require in go.mod"
mine=$(ls *.go *.md *.sh go.mod | grep -vx CARD.md) # CARD.md is the brief, not this build's text
[ -z "$(grep -n $'\xe2\x80\x94' $mine)" ] && ok "no em dash" || no "em dash"
[ -z "$(grep -nE ' -{2} ' $mine)" ] && ok "no spaced double hyphen" || no "spaced double hyphen"
[ -z "$(grep -nE $'[^\t -~]' $mine)" ] && ok "ASCII only" || no "non ASCII"

w=$(mktemp -d)
go build -o "$w/nulltest" . || exit 1
cp README.md "$w/"
cd "$w"

# setup, as CARD.md gives it
cp nulltest real.bin && chmod u+w real.bin
size=$(wc -c < real.bin)
test "$size" -ge 1500000 || no "real.bin is only $size bytes"
uv run python -I -c "import sys,re; d=open(sys.argv[1],'rb').read()[100000:600000]; sys.exit(re.search(rb'(.)\1{22049}', d, re.S) is not None)" real.bin || no "real.bin has a long run of one byte value"
flip() { printf "$(printf '\\%03o' $(( $(od -An -tu1 -j"$2" -N1 "$1") ^ 1 )))"; }
cp real.bin same.bin
cp real.bin flip1.bin && flip real.bin 100000 | dd of=flip1.bin bs=1 seek=100000 conv=notrunc 2>/dev/null
cp real.bin flip3.bin
for o in 100000 250000 400000; do flip real.bin $o | dd of=flip3.bin bs=1 seek=$o conv=notrunc 2>/dev/null; done
{ head -c 100000 real.bin; head -c 510000 real.bin | tail -c 10000; tail -c +110001 real.bin; } > burst.bin
{ head -c 100000 real.bin; flip real.bin 100000; tail -c +100001 real.bin; } > ins.bin
head -c 100000 real.bin > trunc.bin
SAMPLES='import wave,array,sys; w=wave.open(sys.argv[1]); s=array.array("h",w.readframes(w.getnframes()))'
echo "     real.bin is the built nulltest, $size bytes"
c() { echo "$1" | sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'; }

echo "== 2 identical files are exact silence"
./nulltest -q -o null.wav real.bin same.bin > s.txt; code=$?
cp s.txt "$out/sheet-identical.txt"; cp null.wav "$out/identical.wav"
[ $code = 0 ] && ok "exit 0" || no "exit $code"
has s.txt "Result     IDENTICAL" 2
has s.txt "Recording  0:00.0 to 0:02.0 of the file, no ring-out" 2
has s.txt "Level      none, exactly zero" 2
has s.txt "File       null.wav, 0:02.0" 2
[ "$(stat -c %s null.wav)" = 176444 ] && ok "2 null.wav is 176,444 bytes" || no "2 null.wav $(stat -c %s null.wav)"
[ "$(tail -c +45 null.wav | tr -d '\000' | wc -c)" = 0 ] && ok "2 data bytes all zero" || no "2 data not zero"
echo "     soxi: $(soxi null.wav | grep -E 'Channels|Sample Rate|Precision' | tr -s ' ' | tr '\n' ' ')"

echo "== 3 one flipped byte is one pluck, exactly"
./nulltest -q -o null.wav real.bin flip1.bin > s.txt; code=$?
cp s.txt "$out/sheet-flip1.txt"; cp null.wav "$out/flip1.wav"
[ $code = 1 ] && ok "exit 1" || no "exit $code"
for r in "First      byte 100,001, file time 0:02.2" "Last       byte 100,001, file time 0:02.2" "Differing  1 position in 1 run" "Length     same" "Rings      1, longest 1.8 s" "Recording  0:01.2 to 0:02.2 of the file, then 4.0 s ring-out" "Level      peak -48.2 dBFS before make-up, +45.2 dB applied" "File       null.wav, 0:05.0"; do has s.txt "$r" 3; done
got=$(uv run python -I -c "$SAMPLES; print(len(s), any(s[:44100]), abs(s[44100]), max(map(abs,s)))" null.wav)
[ "$got" = "220501 False 23197 23197" ] && ok "3 samples: $got" || no "3 samples: $got"

echo "== 4 the shapes are told apart"
for x in flip3 burst ins trunc; do
	./nulltest -q -o null.wav real.bin $x.bin > $x.txt; echo $? > $x.code
	cp $x.txt "$out/sheet-$x.txt"; case $x in burst | ins) cp null.wav "$out/$x.wav" ;; esac # the owner listens to the flip, the burst and the insertion
	echo "     $x: exit $(cat $x.code); $(row $x.txt Rings); $(row $x.txt Recording)"
done
[ "$(cat flip3.code)" = 1 ] && ok "4 flip3 exit 1" || no "4 flip3 exit"
has flip3.txt "Differing  3 positions in 3 runs" 4
has flip3.txt "Rings      3, longest 1.8 s" 4
has flip3.txt "Last       byte 400,001, file time 0:09.0" 4
has flip3.txt "File       null.wav, 0:11.8" 4
[ "$(cat burst.code)" = 1 ] && ok "4 burst exit 1" || no "4 burst exit"
has burst.txt "Length     same" 4
sec() { row "$1" Rings | sed -E 's/.*longest ([0-9.]+) s/\1/'; }
within() { awk -v v="$1" -v a="$2" -v b="$3" 'BEGIN { exit !(v >= a && v <= b) }'; }
within "$(sec burst.txt)" 2.0 4.0 && ok "4 burst ring $(sec burst.txt) s" || no "4 burst ring $(sec burst.txt)"
last=$(row burst.txt Last | sed -E 's/.*byte ([0-9,]+),.*/\1/' | tr -d ,)
[ "$last" -le 110000 ] && ok "4 burst last byte $last" || no "4 burst last $last"
end=$(row burst.txt Recording | sed -E 's/.* to ([0-9:.]+) of.*/\1/')
[[ "$end" < "0:02.5" ]] && ok "4 burst recording ends $end" || no "4 burst recording ends $end"
n=$(row burst.txt Differing | sed -E 's/Differing +([0-9,]+) .*/\1/' | tr -d ,)
[ "$n" = "$(cmp -l real.bin burst.bin | wc -l)" ] && ok "4 burst $(row burst.txt Differing | tr -s ' ') equals cmp -l" || no "4 burst count $n"
[ "$(cat ins.code)" = 1 ] && ok "4 ins exit 1" || no "4 ins exit"
has ins.txt "First      byte 100,001, file time 0:02.2" 4
has ins.txt "Length     B is 1 byte longer" 4
row ins.txt Last | grep -q "^Last       end of B, after byte $(c $((size + 1))), file time " && ok "4 $(row ins.txt Last)" || no "4 ins last"
within "$(sec ins.txt)" 8.0 99 && ok "4 ins ring $(sec ins.txt) s" || no "4 ins ring $(sec ins.txt)"
[ "$(cat trunc.code)" = 1 ] && ok "4 trunc exit 1" || no "4 trunc exit"
has trunc.txt "First      end of B, after byte 100,000, file time 0:02.2" 4
row trunc.txt Last | grep -q "^Last       end of A, after byte $(c $size), file time " && ok "4 $(row trunc.txt Last)" || no "4 trunc last"
has trunc.txt "Length     B is $(c $((size - 100000))) bytes shorter" 4
within "$(sec trunc.txt)" 8.0 99 && ok "4 trunc ring $(sec trunc.txt) s" || no "4 trunc ring $(sec trunc.txt)"

echo "== 5 agrees with cmp"
for x in same flip1 flip3 burst ins trunc; do
	./nulltest -q real.bin $x.bin > s.txt; a=$?
	cmp -s real.bin $x.bin; b=$?
	[ $a = $b ] && ok "5 $x: nulltest $a, cmp -s $b" || no "5 $x: nulltest $a, cmp -s $b"
	case $x in flip1 | flip3 | ins)
		f=$(row s.txt First | sed -E 's/.*byte ([0-9,]+),.*/\1/' | tr -d ,)
		k=$(cmp real.bin $x.bin | sed -E 's/.*(byte|char) ([0-9]+).*/\2/')
		[ "$f" = "$k" ] && ok "5 $x first $f, cmp $k" || no "5 $x first $f, cmp $k"
		;;
	esac
	case $x in flip1 | flip3 | burst)
		n=$(row s.txt Differing | sed -E 's/Differing +([0-9,]+) .*/\1/' | tr -d ,)
		k=$(cmp -l real.bin $x.bin | wc -l)
		[ "$n" = "$k" ] && ok "5 $x differing $n, cmp -l $k" || no "5 $x differing $n, cmp -l $k"
		;;
	esac
done

echo "== 6 single file and no drone"
./nulltest -q -o null.wav README.md > s.txt; code=$?
cp s.txt "$out/sheet-readme.txt"; cp null.wav "$out/readme.wav"
[ $code = 0 ] && ok "6 exit 0" || no "6 exit $code"
for r in "B          (none)" "Method     A through the string, alone" "Result     RENDERED" "First      n/a" "Last       n/a" "Differing  n/a" "Length     n/a"; do has s.txt "$r" 6; done
got=$(uv run python -I -c "$SAMPLES; print(max(map(abs,s)), abs(sum(s))/len(s) < 232, s[0] != 0)" null.wav)
[ "$got" = "23197 True True" ] && ok "6 samples: $got" || no "6 samples: $got"

echo "== 7 errors and limits"
before=$(stat -c %y null.wav)
sleep 1
./nulltest -q -o null.wav nosuch.bin real.bin > o.txt 2> e.txt; code=$?
[ ! -s o.txt ] && ok "7 stdout empty" || no "7 stdout not empty"
grep -q '^nulltest: cannot read A: .*Nothing was compared\.$' e.txt && ok "7 $(cat e.txt)" || no "7 stderr $(cat e.txt)"
[ $code = 2 ] && ok "7 exit 2" || no "7 exit $code"
[ "$(stat -c %y null.wav)" = "$before" ] && ok "7 null.wav untouched" || no "7 null.wav touched"
dd if=/dev/zero of=big.bin bs=1048576 count=0 seek=257 2>/dev/null
./nulltest -q real.bin big.bin > o.txt 2> e.txt; code=$?
[ "$(cat e.txt)" = "nulltest: B is larger than 256 MiB. Nothing was compared." ] && [ $code = 2 ] && ok "7 $(cat e.txt) exit $code" || no "7 big: $(cat e.txt) exit $code"
for args in "" "a b c" "-s 1 real.bin same.bin" "-s 121 real.bin same.bin"; do
	./nulltest $args > o.txt 2> e.txt; code=$?
	[ "$(cat e.txt)" = "usage: nulltest [-s seconds] [-o file] [-q] A [B]" ] && [ $code = 2 ] && [ ! -s o.txt ] && ok "7 nulltest $args: usage, exit 2" || no "7 nulltest $args: $(cat e.txt) exit $code"
done

echo "== 8 the sheet in a real terminal"
long=$(printf 'n%.0s' $(seq 56)).bin
cp flip1.bin "$long"
for x in flip1.bin same.bin ins.bin README.md "$long"; do
	if [ "$x" = README.md ]; then ./nulltest -q -o null.wav README.md > t.txt; else ./nulltest -q -o null.wav real.bin "$x" > t.txt; fi
	awk '{ if (length($0) > 64) bad = 1 } END { exit bad }' t.txt && [ "$(wc -l < t.txt)" = 20 ] && head -1 t.txt | grep -Eq '^NULL TEST {18}[0-9]{4}-[0-9]{2}-[0-9]{2} {18}Form NT-1$' &&
		ok "8 $x: 20 lines, at most 64 columns, header matches" || no "8 $x"
done
./nulltest -q -o null.wav "$long" real.bin > t.txt; cp t.txt "$out/sheet-longname.txt"
grep -q "^A          ...$(printf 'n%.0s' $(seq 23)).bin " t.txt && ok "8 $(row t.txt A | tr -s ' ')" || no "8 long name"
./nulltest -q -o null.wav real.bin flip1.bin > sheet.txt
T="tmux -L nulltest-check -f /dev/null"
$T new-session -d -s nt -x 80 -y 24 './nulltest real.bin flip1.bin; echo EXIT=$?; sleep 20'
for _ in $(seq 150); do $T capture-pane -p -t nt | grep -q '^EXIT=' && break; sleep 0.1; done
$T capture-pane -p -t nt | sed 's/ *$//' > pane.txt
$T kill-session -t nt 2>/dev/null
cp pane.txt "$out/tmux-flip1.txt"
head -20 pane.txt | diff - sheet.txt > /dev/null && ok "8 tmux pane lines 1 to 20 equal sheet.txt" || no "8 pane differs from sheet.txt"
rest=$(tail -n +21 pane.txt | grep -v '^$')
[ "$rest" = "EXIT=1" ] && ok "8 the only other text is EXIT=1" || no "8 other text: $rest"

echo "== 9 options"
./nulltest -q -o null.wav -s 5 real.bin ins.bin > s.txt; cp s.txt "$out/sheet-ins-s5.txt"
n=$(uv run python -I -c "$SAMPLES; print(len(s))" null.wav)
[ "$n" -le 396900 ] && ok "9 -s 5: $n samples, at most 396,900" || no "9 -s 5: $n samples"
end=$(row s.txt Recording | sed -E 's/.* to ([0-9:.]+) of.*/\1/')
fl=$(row s.txt File | sed -E 's/.*, //')
[[ ! "$end" > "0:06.2" ]] && ok "9 $(row s.txt Recording | tr -s ' ')" || no "9 recording ends $end"
[[ ! "$fl" < "0:08.5" && ! "$fl" > "0:09.0" ]] && ok "9 $(row s.txt File | tr -s ' ')" || no "9 file $fl"
before=$(stat -c %y null.wav)
sleep 1
./nulltest -q -o out.wav real.bin flip1.bin > /dev/null
[ -f out.wav ] && [ "$(stat -c %y null.wav)" = "$before" ] && ok "9 -o out.wav written, null.wav untouched" || no "9 -o"

echo "== 10 quiet means no file"
mkdir empty && cd empty
../nulltest -q ../real.bin ../flip1.bin > ../q.txt
n=$(ls | wc -l)
cd .. && rmdir empty
has q.txt "File       not written" 10
[ "$n" = 0 ] && ok "10 empty directory still empty" || no "10 $n files"

echo "== 11 Ctrl-C stops the sound"
mkdir -p fakebin && printf '#!/bin/sh\nexec sleep 30\n' > fakebin/afplay && chmod +x fakebin/afplay
$T new-session -d -s nti -x 80 -y 24 "bash -c 'PATH=$PWD/fakebin:\$PATH ./nulltest real.bin flip1.bin; echo EXIT=\$?; sleep 5'"
sleep 2
pgrep -f 'sleep 30' > /dev/null && ok "11 stand-in player running" || no "11 stand-in not running"
t0=$(date +%s%N)
$T send-keys -t nti C-c
got=""
for _ in $(seq 30); do got=$($T capture-pane -p -t nti | grep -o 'EXIT=[0-9]*'); [ -n "$got" ] && break; sleep 0.1; done
ms=$((($(date +%s%N) - t0) / 1000000))
$T capture-pane -p -t nti | sed 's/ *$//' > "$out/tmux-ctrl-c.txt"
$T kill-session -t nti 2>/dev/null
rm -rf fakebin
[ "$got" = "EXIT=1" ] && ok "11 $got $ms ms after Ctrl-C" || no "11 '$got' after $ms ms"

cd "$here" && rm -rf "$w"
echo "== $fails failed"
exit $((fails > 0))
