#!/usr/bin/env bash
# Every acceptance check from CARD.md, run for real on Linux with Go 1.22+,
# tmux, file and sha256sum. Usage, from this folder: ./check.sh
# Each check uses its own fresh log under mktemp. The terminal captures that
# the screenshots are made from are written to out/.
set -u
cd "$(dirname "$0")/tomorrow" || exit 1
OUT=$(cd .. && pwd)/out
mkdir -p "$OUT"
W=$(mktemp -d)
pass=0 total=0 extra_pass=0 extra_total=0 f=0
# A private tmux server, so nothing here touches anyone else's sessions.
tmux() { command tmux -L tomorrow-check "$@"; }

need() { "$@" || { echo "  not met: $*"; f=1; }; }
verdict() {
	total=$((total + 1))
	if [ $f -eq 0 ]; then pass=$((pass + 1)) && echo "PASS $1"; else echo "FAIL $1"; fi
	echo
	f=0
}
extra() {
	extra_total=$((extra_total + 1))
	if [ $f -eq 0 ]; then extra_pass=$((extra_pass + 1)) && echo "PASS $1"; else echo "FAIL $1"; fi
	echo
	f=0
}
fresh() {
	TOMORROW_LOG="$(mktemp -d -p "$W")/log.jsonl"
	export TOMORROW_LOG
}
# shell <name> <width> <height>: an interactive bash in tmux with a plain prompt
shell() {
	tmux kill-session -t "$1" 2>/dev/null
	tmux new-session -d -s "$1" -x "$2" -y "$3" -c "$PWD" \
		"$(printf 'env PS1=%q PATH=%q TOMORROW_LOG=%q bash --norc --noprofile' '$ ' "$PWD:$PATH" "$TOMORROW_LOG")"
	for _ in $(seq 100); do
		[ "$(tmux capture-pane -p -t "$1" | sed '/^$/d' | tail -1)" = '$' ] && return 0
		sleep 0.1
	done
	return 1
}
# type_in <name> <line>: type a line, press Enter, wait for the next prompt
type_in() {
	local before
	before=$(tmux capture-pane -p -S - -t "$1" | grep -c '^\$')
	tmux send-keys -t "$1" -l "$2"
	tmux send-keys -t "$1" Enter
	for _ in $(seq 300); do
		sleep 0.1
		[ "$(tmux capture-pane -p -S - -t "$1" | grep -c '^\$')" -gt "$before" ] &&
			[ "$(tmux capture-pane -p -t "$1" | sed '/^$/d' | tail -1)" = '$' ] && return 0
	done
	echo "  timed out waiting for: $2"
	return 1
}

echo "== 1. Build and unit tests"
echo "gofmt -l: $(gofmt -l .)"
need [ -z "$(gofmt -l .)" ]
need go vet ./...
go test -count=1 -v ./... >"$W/t1"
need [ $? = 0 ]
grep -E '^(--- |ok|FAIL)' "$W/t1"
need go build -o tomorrow .
echo "grep -c '^require' go.mod: $(grep -c '^require' go.mod)"
need [ "$(grep -c '^require' go.mod)" = 0 ]
for v in '{0, 0, "50.0%", 8}' '{3, 3, "80.0%", 5}' '{2, 0, "25.0%", 26}' '{10, 7, "66.7%", 28}' \
	'{100, 100, "99.0%", 0}' '{1998, 1998, "99.9%", 0}' '{2998, 0, "0.1%", 26990}' \
	'"how":"run","ms":0}`' '"how":"hand"}`'; do
	need grep -qF "$v" main_test.go
done
verdict "1. vet, tests and build exit 0; no require lines; worked values and ms cases in the test file"

echo "== 2. Exact table from a known log (test input, not real use)"
fresh
K2=$TOMORROW_LOG
for _ in 1 2 3; do echo '{"at":"2026-01-01T00:00:00Z","event":"build","ok":true,"how":"hand"}'; done >"$K2"
for ok in true true false true true false true true false true; do
	echo "{\"at\":\"2026-01-01T00:00:00Z\",\"event\":\"deploy\",\"ok\":$ok,\"how\":\"hand\"}"
done >>"$K2"
for _ in 1 2; do echo '{"at":"2026-01-01T00:00:00Z","event":"meeting-on-time","ok":false,"how":"hand"}'; done >>"$K2"
d1=$(date -d tomorrow +%F)
./tomorrow table >"$W/t2"
d2=$(date -d tomorrow +%F)
cat "$W/t2"
cat >"$W/want2" <<'EOF'

Event            Trials  Yes  Tomorrow*  To 90%  Last five
build                 3    3      80.0%       5  YYY
deploy               10    7      66.7%      28  NYYNY
meeting-on-time       2    0      25.0%      26  NN

* No event has been assigned certainty.
EOF
need cmp -s <(sed -n 4,10p "$W/t2") "$W/want2"
need grep -Eqx 'Tomorrow Table for [0-9]{4}-[0-9]{2}-[0-9]{2}' <(sed -n 1p "$W/t2")
need grep -Eqx "Tomorrow Table for ($d1|$d2)" <(sed -n 1p "$W/t2")
need [ "$(sed -n 2p "$W/t2")" = "Record: $K2" ]
need [ "$(sed -n 3p "$W/t2")" = "Method: rule of succession (Laplace, 1814). Each trial counted as independent." ]
echo "d1=$d1 d2=$d2 lines=$(wc -l <"$W/t2") lines with trailing space=$(grep -c ' $' "$W/t2")"
need [ "$(grep -c ' $' "$W/t2")" = 0 ]
verdict "2. lines 4 to 10 exact, dated title, Record and Method lines, no trailing spaces"

echo "== 3. End to end on real input: go test under tomorrow run, three times"
fresh
for _ in 1 2 3; do
	./tomorrow run tests -- go test ./... >"$W/o3" 2>"$W/e3"
	need [ $? = 0 ]
	cat "$W/o3" "$W/e3"
	need grep -q '^ok' "$W/o3"
	need grep -Eqx 'tomorrow: tests: yes\. [123] of [123]\. Tomorrow [0-9.]+%\.' <(tail -1 "$W/e3")
done
./tomorrow table >"$W/t3"
cat "$W/t3"
need grep -Eqx 'tests +3 +3 +80\.0% +5  YYY' "$W/t3"
echo "wc -l: $(wc -l <"$TOMORROW_LOG")"
head -1 "$TOMORROW_LOG"
need [ "$(wc -l <"$TOMORROW_LOG")" = 3 ]
need grep -Eq '"how":"run","ms":[0-9]+' <(head -1 "$TOMORROW_LOG")
verdict "3. real go test output passes through, summary lines, tests row 3 3 80.0% 5 YYY, 3 log lines with ms"

echo "== 4. Nothing of the child is damaged"
fresh
echo "(a) ./tomorrow run x -- printf 'a\nb' 2>/dev/null | od -c"
./tomorrow run x -- printf 'a\nb' 2>/dev/null | tee "$W/a4" | od -c
need cmp -s "$W/a4" <(printf 'a\nb')
got=$(printf hello | ./tomorrow run x -- cat 2>/dev/null)
echo "(b) printf hello | ./tomorrow run x -- cat: $got"
need [ "$got" = hello ]
./tomorrow run x -- sh -c 'echo out; echo err >&2; exit 7' >"$W/o4" 2>"$W/e4"
rc=$?
echo "(c) exit $rc; stdout:"
cat "$W/o4"
echo "    stderr:"
cat "$W/e4"
need [ $rc = 7 ]
need cmp -s "$W/o4" <(printf 'out\n')
need [ "$(sed -n 1p "$W/e4")" = err ]
need grep -q '^tomorrow: x: no\. ' <(tail -1 "$W/e4")
./tomorrow run x -- sh -c 'kill -TERM $$' 2>"$W/e4d"
rc=$?
echo "(d) exit $rc; $(cat "$W/e4d"); last log line: $(tail -1 "$TOMORROW_LOG")"
need [ $rc = 143 ]
need grep -q '"ok":false' <(tail -1 "$TOMORROW_LOG")
echo "(e) stderr has $(wc -l <"$W/e4") lines; the tomorrow line is line $(grep -n '^tomorrow:' "$W/e4" | cut -d: -f1)"
need [ "$(wc -l <"$W/e4")" = 2 ]
verdict "4. stdout bytes, stdin, stderr order, exit 7, signal exit 143 recorded as no"

echo "== 5. A command that does not start records nothing"
fresh
./tomorrow record walk yes >/dev/null
n=$(wc -l <"$TOMORROW_LOG")
./tomorrow run typo -- no-such-binary-xyz 2>"$W/e5"
rc=$?
echo "exit $rc: $(cat "$W/e5"); log lines $n -> $(wc -l <"$TOMORROW_LOG")"
need [ $rc = 127 ]
need grep -q 'nothing was run' "$W/e5"
need [ "$(wc -l <"$TOMORROW_LOG")" = "$n" ]
./tomorrow run typo -- /etc/passwd 2>"$W/e5"
rc=$?
echo "exit $rc: $(cat "$W/e5"); log lines $n -> $(wc -l <"$TOMORROW_LOG")"
need [ $rc = 126 ]
need grep -q 'nothing was run' "$W/e5"
need [ "$(wc -l <"$TOMORROW_LOG")" = "$n" ]
verdict "5. 127 and 126, nothing was run, log unchanged"

echo "== 6. Never certainty (test input: 5000 yes, 5000 no)"
fresh
{
	yes '{"at":"2026-01-01T00:00:00Z","event":"always","ok":true,"how":"hand"}' | head -5000
	yes '{"at":"2026-01-01T00:00:00Z","event":"never","ok":false,"how":"hand"}' | head -5000
} >"$TOMORROW_LOG"
./tomorrow table >"$W/t6"
cat "$W/t6"
need grep -Eqx 'always +5000 +5000 +99\.9% +0  YYYYY' "$W/t6"
need grep -Eqx 'never +5000 +0 +0\.1% +[0-9]+  NNNNN' "$W/t6"
c6=$(./tomorrow table | grep -c '100.0%\|  0.0%')
echo "./tomorrow table | grep -c '100.0%\|  0.0%': $c6"
need [ "$c6" = 0 ]
verdict "6. 99.9% with To 90% 0, 0.1%, no 100.0% or 0.0%"

echo "== 7. Damaged log is reported, not repaired"
TOMORROW_LOG=$(mktemp -d -p "$W")/log.jsonl
cp "$K2" "$TOMORROW_LOG"
echo 'not json' >>"$TOMORROW_LOG"
h1=$(head -15 "$TOMORROW_LOG" | sha256sum)
./tomorrow table >"$W/t7" 2>"$W/e7"
need [ $? = 0 ]
cat "$W/t7"
echo "stderr: $(cat "$W/e7")"
need cmp -s <(sed -n 3,10p "$W/t7") <(sed -n 3,10p "$W/t2")
need [ "$(cat "$W/e7")" = "tomorrow: 1 line of the log could not be read. It was left as it is." ]
h2=$(head -15 "$TOMORROW_LOG" | sha256sum)
echo "lines: $(wc -l <"$TOMORROW_LOG"); first 15 sha256 before ${h1%% *} after ${h2%% *}"
need [ "$(wc -l <"$TOMORROW_LOG")" = 16 ]
need [ "$h1" = "$h2" ]
verdict "7. same table, exact stderr sentence, 16 lines, first 15 unchanged"

echo "== 8. Usage errors exit 2 and change nothing"
fresh
./tomorrow record walk yes >/dev/null
for c in "run build" "run build bun run build" "run Build! -- true" "record build maybe" "nonsense"; do
	# shellcheck disable=SC2086
	./tomorrow $c 2>"$W/e8"
	rc=$?
	echo "./tomorrow $c -> exit $rc: $(cat "$W/e8")"
	need [ $rc = 2 ]
	need [ "$(wc -l <"$TOMORROW_LOG")" = 1 ]
done
fresh
./tomorrow table >"$W/t8"
rc=$?
cat "$W/t8"
echo "exit $rc; log file created by table: $([ -e "$TOMORROW_LOG" ] && echo yes || echo no)"
need [ $rc = 0 ]
need [ "$(sed -n 5p "$W/t8")" = "Nothing has happened yet. Record something: tomorrow record walk yes" ]
need [ "$(wc -l <"$W/t8")" = 5 ]
need [ ! -e "$TOMORROW_LOG" ]
verdict "8. five usage errors exit 2 with the log unchanged; empty table line 5, exit 0"

echo "== 9. Parallel writes"
fresh
for _ in $(seq 20); do ./tomorrow record burst yes >/dev/null & done
wait
bad=$(while read -r l; do echo "$l" | grep -q '^{.*}$' || echo BAD; done <"$TOMORROW_LOG")
./tomorrow table >"$W/t9"
cat "$W/t9"
echo "lines: $(wc -l <"$TOMORROW_LOG"); BAD lines: ${bad:-none}"
need [ "$(wc -l <"$TOMORROW_LOG")" = 20 ]
need [ -z "$bad" ]
need grep -Eqx 'burst +20 +20 +95\.5% +0  YYYYY' "$W/t9"
verdict "9. 20 whole lines, burst 20 20 95.5% 0"

echo "== 10. Terminal fit, observed in tmux 80 x 24"
tmux -V
TOMORROW_LOG=$K2
tmux kill-session -t fit 2>/dev/null
tmux new-session -d -s fit -x 80 -y 24 -c "$PWD" -e TOMORROW_LOG="$K2" './tomorrow table; sleep 30'
for _ in $(seq 50); do
	tmux capture-pane -p -t fit | grep -q 'certainty' && break
	sleep 0.1
done
tmux capture-pane -p -t fit >"$W/c10"
tmux capture-pane -p -J -t fit | sed 's/ *$//' >"$W/j10"
tmux kill-session -t fit
sed '/^$/N;/^\n$/D' "$W/c10"
need [ "$(awk 'length > 80' "$W/c10" | wc -l)" = 0 ]
need cmp -s <(sed 's/ *$//' "$W/c10") "$W/j10"
need [ "$(grep -c 'Tomorrow\*' "$W/c10")" = 1 ]
need [ "$(grep -cx '\* No event has been assigned certainty\.' "$W/c10")" = 1 ]
twin=$(./tomorrow table | awk 'length > 80' | wc -l)
echo "longest captured line: $(awk '{ if (length > m) m = length } END { print m }' "$W/c10"); Method line: $(grep '^Method' "$W/c10" | awk '{ print length }') characters; tool-free twin: $twin"
need [ "$twin" = 0 ]
verdict "10. no line over 80, nothing wraps (plain capture equals joined capture), header and footnote once"

echo "== 11. Static binaries"
rm -rf dist
for o in linux darwin; do for a in amd64 arm64; do
	CGO_ENABLED=0 GOOS=$o GOARCH=$a go build -o dist/tomorrow-$o-$a . || echo FAIL
done; done >"$W/b11"
cat "$W/b11"
for b in dist/*; do echo "$b $(wc -c <"$b") bytes"; done
file dist/tomorrow-linux-arm64
need [ ! -s "$W/b11" ]
need [ "$(ls dist | wc -l)" = 4 ]
need grep -q 'statically linked' <(file dist/tomorrow-linux-arm64)
dist/tomorrow-linux-arm64 help >/dev/null
rc=$?
echo "dist/tomorrow-linux-arm64 help: exit $rc"
need [ $rc = 0 ]
verdict "11. four static builds, linux-arm64 statically linked, help exits 0"

echo "== Extra: behaviour the card states outside the eleven checks"
fresh
./tomorrow run nap -- sleep 5 2>"$W/x1" &
p=$!
sleep 0.5
s=$(date +%s%N)
kill -TERM $p
wait $p
rc=$?
ms=$((($(date +%s%N) - s) / 1000000))
echo "SIGTERM to tomorrow during sleep 5: exit $rc after ${ms} ms; $(cat "$W/x1")"
need [ $rc = 143 ]
need [ $ms -lt 2000 ]
extra "E1. SIGTERM is forwarded to the child; exit 143; recorded as no"

out=$(
	trap '' HUP
	./tomorrow run hup -- sh -c 'kill -HUP $$; echo survived' 2>/dev/null
)
rc=$?
echo "SIGHUP already ignored (as under nohup): child printed '$out', exit $rc"
need [ "$out" = survived ]
need [ $rc = 0 ]
extra "E2. an ignored signal stays ignored for the child"

fresh
need shell cc 80 24
tmux send-keys -t cc 'tomorrow run nap -- sleep 30' Enter
sleep 1
tmux send-keys -t cc C-c
sleep 0.5
type_in cc 'echo $?'
tmux capture-pane -p -t cc | sed '/^$/d' | tee "$OUT/ctrl-c.txt"
tmux kill-session -t cc
need grep -q 'tomorrow: nap: no\. 0 of 1\. Tomorrow 33\.3%\.$' "$OUT/ctrl-c.txt"
need grep -qx '130' "$OUT/ctrl-c.txt"
extra "E3. Ctrl-C in a real terminal stops the child, tomorrow survives to record it, exit 130"

fresh
printf 'not json\n\n{"event":"Walk","ok":true}\n{"event":"walk","ok":true}\n' >"$TOMORROW_LOG"
./tomorrow table >/dev/null 2>"$W/x4"
echo "stderr: $(cat "$W/x4")"
need [ "$(cat "$W/x4")" = "tomorrow: 3 lines of the log could not be read. They were left as they are." ]
extra "E4. plural sentence for several unreadable lines"

./tomorrow help >"$W/h" && ./tomorrow -h | cmp -s - "$W/h" && ./tomorrow --help | cmp -s - "$W/h"
need [ $? = 0 ]
need [ "$(sed -n 1p "$W/h")" = "tomorrow: log what repeats, read the odds of the next one." ]
need [ "$(tail -1 "$W/h")" = "normal is dead" ]
need [ "$(awk 'length > 80' "$W/h" | wc -l)" = 0 ]
./tomorrow >"$W/x5" 2>/dev/null && ./tomorrow table 2>/dev/null | cmp -s - "$W/x5"
need [ $? = 0 ]
extra "E5. help, -h and --help agree; first and last lines; no-argument run equals table"

TOMORROW_LOG=/dev/null/no/log.jsonl
./tomorrow run x -- sh -c 'echo still here; exit 3' >"$W/o7" 2>"$W/e7"
rc=$?
echo "log unwritable, run: exit $rc; stdout: $(cat "$W/o7"); stderr: $(cat "$W/e7")"
need [ $rc = 3 ]
need [ "$(cat "$W/o7")" = "still here" ]
need grep -q '^tomorrow: could not write the log: ' "$W/e7"
./tomorrow record x yes 2>"$W/e7"
rc=$?
echo "log unwritable, record: exit $rc; stderr: $(cat "$W/e7")"
need [ $rc = 1 ]
extra "E6. an unwritable log is reported and never changes the command's exit code"

echo "== Captures for the screenshots (real sessions in tmux, 80 columns)"
fresh
need shell first 80 44
for l in 'tomorrow record meeting-on-time yes' 'tomorrow record meeting-on-time yes' \
	'tomorrow record meeting-on-time yes' 'tomorrow table' 'tomorrow run tests -- go test ./...' 'tomorrow table'; do
	need type_in first "$l"
done
tmux capture-pane -p -S - -t first | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' >"$OUT/session-first.txt"
tmux kill-session -t first
fresh
need shell plain 80 44
for l in 'tomorrow help' 'tomorrow' 'tomorrow record walk maybe' 'tomorrow run typo -- no-such-binary-xyz' 'echo $?'; do
	need type_in plain "$l"
done
tmux capture-pane -p -S - -t plain | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' >"$OUT/session-plain.txt"
tmux kill-session -t plain
for s in first plain; do
	{
		printf '<!doctype html>\n<html lang="en"><head><meta charset="utf-8">\n'
		printf '<meta name="viewport" content="width=device-width, initial-scale=1">\n'
		printf '<title>Tomorrow Table, terminal</title>\n<style>\n'
		printf 'html { -webkit-text-size-adjust: 100%%; text-size-adjust: 100%%; }\n'
		printf 'body { margin: 0; background: #FCF0DD; color: #1A1A1A; }\n'
		printf 'pre { margin: 16px; font-family: "DejaVu Sans Mono", Menlo, monospace; line-height: 1.35;\n'
		printf '  font-size: min(15px, calc((100vw - 32px) / 48.4)); }\n'
		printf 'p { margin: 16px 16px 0; font: 12px/1.4 Georgia, serif; color: #5B5B5B; }\n</style></head>\n'
		printf '<body><p>Captured from tmux at 80 columns. Unedited.</p><pre>'
		sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' "$OUT/session-$s.txt"
		printf '</pre></body></html>\n'
	} >"$OUT/session-$s.html"
done
extra "E7. two terminal sessions captured to out/ for the screenshots"

tmux kill-server 2>/dev/null
rm -rf "$W"
echo "acceptance checks passed: $pass of $total"
echo "extra checks passed: $extra_pass of $extra_total"
[ $pass = "$total" ] && [ $extra_pass = "$extra_total" ]
