#!/bin/sh
# End to end checks 2 to 9b, 11 and 12 from CARD.md, on real runs of real commands.
# From the project folder: go build -o usually . && sh test/e2e.sh
# Checks 10 and 10b need a terminal and live in test/tmux.sh.
set -eu
P=$(pwd)
BIN=$P/usually
[ -x "$BIN" ] || { echo "build first: go build -o usually ." >&2; exit 2; }
unset S FAIL
W=$(mktemp -d)
trap 'rm -rf "$W"' EXIT
cd "$W"

TAB=$(printf '\t')
RE="^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}\. [^.]*\. [0-9]+\.[0-9]{3} seconds, exit [0-9]+\. In [^$TAB]*$TAB.*\$"
H1='Observations. One line per run. Durations in seconds, measured, not estimated.'
H2='Runs that did not finish with exit 0 are kept apart and not judged.'
FIRST='No record. This is the first.'
CMD='sleep ${S:-3}; [ -z "$FAIL" ] || exit 3'

fail() { echo "FAIL $*" >&2; exit 1; }
ok() { echo "ok $*"; }
show() { sed 's/^/    | /' "$1"; }
fresh() { USUALLY_LOG=$(mktemp -u); export USUALLY_LOG; }
runs() { grep -cE "$RE" "$USUALLY_LOG" || true; }
is() { printf '%s\n' "$2" | cmp -s - "$1" || { echo "$1 was:"; cat "$1"; fail "$3"; }; }

# 2. First run.
fresh
"$BIN" true >out.txt 2>err.txt || fail "2 exit status"
is err.txt "$FIRST" "2 stderr"
[ ! -s out.txt ] || fail "2 stdout not empty"
[ "$(sed -n 1p "$USUALLY_LOG")" = "$H1" ] && [ "$(sed -n 2p "$USUALLY_LOG")" = "$H2" ] || fail "2 header"
[ "$(runs)" = 1 ] && grep -E "$RE" "$USUALLY_LOG" | grep -q ', exit 0\. In ' || fail "2 log line"
ok "2 first run"; show err.txt; show "$USUALLY_LOG"

# 3. Passthrough and exit code.
fresh
code=0; "$BIN" sh -c 'printf "a\n"; printf "b\n" >&2; exit 7' >out.txt 2>err.txt || code=$?
[ "$code" = 7 ] || fail "3 exit status $code"
is out.txt a "3 stdout"
printf '%s\nb\n\nExit 7. Kept apart, not judged.\n' "$FIRST" | cmp -s - err.txt || fail "3 stderr"
"$BIN" cat <"$BIN" 2>/dev/null | cmp - "$BIN" || fail "3 binary stdin to stdout"
ok "3 passthrough: exit 7, stdout exactly 'a', $(wc -c <"$BIN" | tr -d ' ') bytes through cat byte exact"; show err.txt

# 4. Exactly one execution per invocation.
fresh
printf 'echo run >>count.txt\nsleep 1\n' >count.sh
i=0; while [ $i -lt 5 ]; do "$BIN" sh count.sh 2>/dev/null; i=$((i + 1)); done
[ "$(wc -l <count.txt | tr -d ' ')" = 5 ] && [ "$(runs)" = 5 ] || fail "4 counts"
ok "4 five invocations: count.txt has $(wc -l <count.txt | tr -d ' ') lines, the log $(runs) run lines"

# 5. Thresholds on real runs.
fresh
i=1; while [ $i -le 7 ]; do "$BIN" sleep 3 2>"e5.$i"; i=$((i + 1)); done
is e5.1 "$FIRST" "5 run 1"
is e5.2 "From 1 run on record: 3 seconds. Too few to call anything usual." "5 run 2"
head -n 1 e5.3 | grep -q '^From 2 runs on record' || fail "5 run 3"
i=1; while [ $i -le 3 ]; do ! grep -q 'usual one' "e5.$i" || fail "5 verdict on run $i"; i=$((i + 1)); done
i=4; while [ $i -le 7 ]; do
  head -n 1 "e5.$i" | grep -Eq "^(Usually about|Every one of the) .*$((i - 1)) runs" || fail "5 run $i first line"
  ! grep -Eq 'Expect to finish|under a second to' "e5.$i" || fail "5 run $i said too much"
  tail -n 2 "e5.$i" | head -n 1 | grep -Eqx 'That was (not )?a usual one\.' || fail "5 run $i verdict"
  tail -n 1 "e5.$i" | grep 'Took' | grep 'The usual band is' | grep -q 'the middle half of' || fail "5 run $i evidence"
  i=$((i + 1))
done
"$BIN" sleep 4 2>e5.other; is e5.other "$FIRST" "5 other argv"
mkdir elsewhere; (cd elsewhere && "$BIN" sleep 3 2>../e5.elsewhere); is e5.elsewhere "$FIRST" "5 other directory"
ok "5 thresholds"; for i in 1 2 3 4 7; do echo "  run $i:"; show "e5.$i"; done

# 6. The verdict is evidence.
fresh
i=0; while [ $i -lt 5 ]; do "$BIN" sh -c "$CMD" 2>/dev/null; i=$((i + 1)); done
S=9 "$BIN" sh -c "$CMD" 2>e6
grep -qx 'That was not a usual one.' e6 || fail "6 verdict"
grep -qx 'Took 9 seconds. The usual band is 2.7 seconds to 3.3 seconds: the middle half of 5 runs, plus a tenth of the median.' e6 || fail "6 evidence"
ok "6 verdict"; show e6

# 7. Failed exits kept apart (continues 6).
code=0; FAIL=1 "$BIN" sh -c "$CMD" 2>e7a || code=$?
[ "$code" = 3 ] || fail "7 exit status $code"
head -n 1 e7a | grep -q 'From 6 runs\.$' && grep -qx 'Exit 3. Kept apart, not judged.' e7a || fail "7 failed run"
"$BIN" sh -c "$CMD" 2>e7b
head -n 1 e7b | grep -q 'From 6 runs\.$' || fail "7 the failed run counted"
ok "7 failed run kept apart"; show e7a; echo "  next run:"; show e7b

# 8. Two kinds (same log, a fresh key by directory).
mkdir split
for s in 1 1 1 4 4 4 4; do (cd split && S=$s "$BIN" sh -c "$CMD" 2>../e8); done
grep -q 'Runs come in two kinds:' e8 && ! grep -Eq 'Usually about|Expect to finish' e8 || fail "8 two kinds"
ok "8 two kinds"; show e8

# 9. Silence, and the log as the only state.
fresh
i=0; while [ $i -lt 3 ]; do "$BIN" true 2>/dev/null; i=$((i + 1)); done
"$BIN" true 2>e9; [ ! -s e9 ] || fail "9 fourth run spoke"
[ "$(wc -l <"$USUALLY_LOG" | tr -d ' ')" = 6 ] && [ "$(runs)" = 4 ] || fail "9 log shape"
[ "$(ls -l "$USUALLY_LOG" | cut -c1-10)" = "-rw-------" ] || fail "9 mode"
ok "9 fourth run silent, mode $(ls -l "$USUALLY_LOG" | cut -c1-10)"; show "$USUALLY_LOG"
sed -i.bak '3,4s/ seconds, exit / secs, exit /' "$USUALLY_LOG"; rm -f "$USUALLY_LOG.bak"
"$BIN" true 2>e9b || fail "9 run after corruption"
is e9b "From 2 runs on record: under a second, under a second. Too few to call anything usual." "9 corrupted lines skipped"
[ "$(grep -c ' secs, exit ' "$USUALLY_LOG")" = 2 ] || fail "9 corrupted lines rewritten"
rm "$USUALLY_LOG"; "$BIN" true 2>e9c; is e9c "$FIRST" "9 deleted log"
ok "9 two hand-corrupted lines skipped and kept; deleted log gives the no record line"; show e9b

# 9b. The header.
fresh
"$BIN" true 2>/dev/null
[ "$(sed -n 1p "$USUALLY_LOG")" = "$H1" ] && [ "$(sed -n 2p "$USUALLY_LOG")" = "$H2" ] || fail "9b header"
sed -n 3p "$USUALLY_LOG" | grep -Eq "$RE" || fail "9b first run line"
i=0; while [ $i -lt 3 ]; do "$BIN" true 2>/dev/null; i=$((i + 1)); done
[ "$(grep -cxF "$H1" "$USUALLY_LOG")" = 1 ] && [ "$(grep -cxF "$H2" "$USUALLY_LOG")" = 1 ] || fail "9b header twice"
"$BIN" sleep 0 2>/dev/null; "$BIN" sleep 0 2>/dev/null
cp "$USUALLY_LOG" with-header.log
sed -i.bak 1,2d "$USUALLY_LOG"; rm -f "$USUALLY_LOG.bak"
USUALLY_LOG=$W/with-header.log "$BIN" sleep 0 2>e9d.with
"$BIN" sleep 0 2>e9d.without
cmp -s e9d.with e9d.without || fail "9b statement changed without the header"
is e9d.without "From 2 runs on record: under a second, under a second. Too few to call anything usual." "9b statement"
! grep -qxF "$H1" "$USUALLY_LOG" || fail "9b header written again"
: >"$USUALLY_LOG"; "$BIN" true 2>/dev/null
[ "$(sed -n 1p "$USUALLY_LOG")" = "$H1" ] && [ "$(sed -n 2p "$USUALLY_LOG")" = "$H2" ] || fail "9b empty file header"
ok "9b header once; same statement without it; not put back; an empty file gets it"; show e9d.without

# 11. The hundredth.
fresh
i=1; while [ $i -le 101 ]; do "$BIN" true 2>"e11.$i"; i=$((i + 1)); done
is e11.1 "$FIRST" "11 run 1"
is e11.2 "From 1 run on record: under a second. Too few to call anything usual." "11 run 2"
head -n 1 e11.3 | grep -q '^From 2 runs on record' || fail "11 run 3"
i=4; while [ $i -le 99 ]; do [ ! -s "e11.$i" ] || fail "11 run $i spoke"; i=$((i + 1)); done
printf '\nThis was the 100th.\n' | cmp -s - e11.100 || fail "11 run 100"
[ ! -s e11.101 ] || fail "11 run 101 spoke"
[ "$(cat e11.* | grep -c '100th')" = 1 ] || fail "11 more than one 100th"
ok "11 runs 4 to 99 silent, run 100 says it once, run 101 silent"; show e11.100

# Plumbing from the rules that no numbered check covers.
fresh
code=0; "$BIN" no-such-command 2>e13 || code=$?
[ "$code" = 127 ] && [ ! -e "$USUALLY_LOG" ] || fail "not found: status $code"
touch plain; code=0; "$BIN" ./plain 2>>e13 || code=$?
[ "$code" = 126 ] && [ ! -e "$USUALLY_LOG" ] && ! grep -q 'No record' e13 || fail "not executable: status $code"
code=0; "$BIN" 2>>e13 || code=$?
[ "$code" = 2 ] && [ "$(tail -n 1 e13)" = "normal is dead" ] || fail "no arguments: status $code"
code=0; USUALLY_LOG=$W/no/such/dir/log "$BIN" true 2>e14 || code=$?
[ "$code" = 0 ] || fail "unwritable log blocked the command"
printf '%s\n\nThe log could not be written.\n' "$FIRST" | cmp -s - e14 || fail "unwritable log line"
"$BIN" printf 'x\n' 2>/dev/null | tee t.txt >/dev/null; is t.txt x "a pipe on stdout carried tool text"
"$BIN" sleep 30 2>/dev/null & pid=$!
sleep 1; kill -TERM "$pid"; code=0; wait "$pid" || code=$?
[ "$code" = 143 ] && ! pgrep -f '^sleep 30$' >/dev/null || fail "SIGTERM not forwarded: status $code"
grep -q ', exit 143\. ' "$USUALLY_LOG" || fail "SIGTERM run not recorded"
ok "plumbing: not found 127, not executable 126, no arguments 2, unwritable log said once, stdout pipe clean, SIGTERM forwarded and recorded as 143"
show e13; show e14

# 12. README and usage.
cd "$P"
! grep -q -e /home/ -e /Users/ README.md || fail "12 home path in README"
! grep -qwF -e "$(id -un)" README.md || fail "12 user name in README"
[ "$(tail -n 1 README.md)" = "normal is dead" ] || fail "12 README last line"
[ "$("$BIN" -h | tail -n 1)" = "normal is dead" ] || fail "12 usage last line"
if [ -f out/session.txt ]; then
  awk '/^```text$/ && !f { f = 1; next } f && /^```$/ { exit } f' README.md >"$W/readme.txt"
  cmp -s "$W/readme.txt" out/session.txt || { diff "$W/readme.txt" out/session.txt; fail "12 README transcript differs from the capture"; }
  ok "12 README transcript matches out/session.txt line for line ($(wc -l <out/session.txt | tr -d ' ') lines)"
fi
ok "12 README has no home path or user name, ends with the wordmark, and so does -h"

echo "all checks passed"
