#!/bin/sh
# Shell tests for the suit command line. Each case prints "ok NAME" or
# "FAIL NAME"; the exit status is nonzero if any case failed.
# SUIT names the binary under test (default build/suit).

SUIT=${SUIT:-build/suit}
case $SUIT in /*) ;; *) SUIT=$PWD/$SUIT ;; esac
ROOT=$PWD
mkdir -p build/tmp
T=$(mktemp -d "$ROOT/build/tmp/run.XXXXXX") || exit 1
trap 'rm -rf "$T"' EXIT INT TERM

total=0
failed=0

pass() { total=$((total + 1)); echo "ok $1"; }
bad() {
    total=$((total + 1)); failed=$((failed + 1))
    echo "FAIL $1${2:+: $2}"
}

# conf NAME: read stdin into $T/NAME.conf
conf() { cat > "$T/$1.conf"; }

# ---- valid configs --------------------------------------------------------

expect_dump() { # NAME CONF GOLDEN
    if out=$("$SUIT" check "$2" 2>"$T/err"); then
        if [ "$out" = "$(cat "$3")" ]; then pass "$1"
        else bad "$1" "dump differs from $3"; fi
    else
        bad "$1" "exit $?: $(cat "$T/err")"
    fi
}

expect_dump example-fixture test/fixtures/example.conf test/fixtures/example.dump
expect_dump every-kind-and-key test/fixtures/everything.conf test/fixtures/everything.dump

expect_text() { # NAME EXPECTED   (config on stdin)
    conf "$1"
    out=$("$SUIT" check "$T/$1.conf" 2>"$T/err"); rc=$?
    if [ $rc -eq 0 ] && [ "$out" = "$2" ]; then pass "$1"
    else bad "$1" "exit $rc, got: $out $(cat "$T/err")"; fi
}

printf '' | expect_text empty-file ''
expect_text only-comments '' <<'X'
# one

   # indented
X
expect_text comment-after-space 'harness a
harness a record = x' <<'X'
[harness a] # trailing
record = x # trailing
X
expect_text hash-inside-word-kept 'harness a
harness a event E = a#b' <<'X'
[harness a]
event E = a#b
X
expect_text key-and-value-trimmed 'outfit a
outfit a skills = x y z*' <<'X'
[outfit a]
   skills    =    x	  y   z*   
X
expect_text multiword-key-collapsed 'outfit a
outfit a slot hook/Stop = f.sh' <<'X'
[outfit a]
slot    hook/Stop = f.sh
X
printf '[harness a]\r\nrecord = x\r\n' > "$T/crlf.conf"
if [ "$("$SUIT" check "$T/crlf.conf")" = 'harness a
harness a record = x' ]; then pass crlf-line-endings; else bad crlf-line-endings; fi
printf '[harness a]\nrecord = x' > "$T/nonl.conf"
if "$SUIT" check "$T/nonl.conf" >/dev/null 2>&1; then pass no-trailing-newline; else bad no-trailing-newline; fi
expect_text forward-include 'outfit a
outfit a include = b
outfit b' <<'X'
[outfit a]
include = b
[outfit b]
X
expect_text dump-order-stable 'harness a
harness b
outfit a
outfit b
wear user
upstream u' <<'X'
[wear user]
[upstream u]
[outfit b]
[outfit a]
[harness b]
[harness a]
X

# ---- strict errors --------------------------------------------------------

expect_err() { # NAME LINE MESSAGE-PART   (config on stdin)
    conf "$1"
    out=$("$SUIT" check "$T/$1.conf" 2>"$T/err"); rc=$?
    want="$T/$1.conf:$2: "
    if [ $rc -ne 2 ]; then bad "$1" "exit $rc, want 2"
    elif [ -n "$out" ]; then bad "$1" "printed a partial dump"
    elif [ "$(wc -l < "$T/err" | tr -d ' ')" != 1 ]; then bad "$1" "stderr is not one line: $(cat "$T/err")"
    elif ! grep -qF -- "$want" "$T/err"; then bad "$1" "want '$want' in: $(cat "$T/err")"
    elif ! grep -qF -- "$3" "$T/err"; then bad "$1" "want '$3' in: $(cat "$T/err")"
    else pass "$1"; fi
}

expect_err err-unknown-kind 3 "unknown section kind" <<'X'
[harness a]
record = x
[gadget a]
X
expect_err err-unknown-key 2 "unknown key 'nope'" <<'X'
[harness a]
nope = 1
X
expect_err err-key-in-wrong-kind 2 "unknown key 'skills'" <<'X'
[harness a]
skills = x
X
expect_err err-unknown-harness-key 2 "unknown key 'skills.galaxy'" <<'X'
[harness a]
skills.galaxy = x
X
expect_err err-duplicate-section 3 "duplicate section (first at line 1)" <<'X'
[harness a]

[harness a]
X
expect_err err-duplicate-wear-section 4 "duplicate section" <<'X'
[wear user machine=m]
outfits = a
[outfit a]
[wear user machine=m]
X
expect_err err-duplicate-key 3 "duplicate key 'skills.user' (first at line 2)" <<'X'
[harness a]
skills.user = x
skills.user = y
X
expect_err err-duplicate-slot-key 4 "duplicate key 'slot s'" <<'X'
[outfit a]
slot s = x
only = h
slot   s = y
X
expect_err err-entry-before-section 1 "entry before any section header" <<'X'
record = x
[harness a]
X
expect_err err-header-no-close 2 "malformed section header" <<'X'
# c
[harness a
X
expect_err err-header-empty 1 "malformed section header" <<'X'
[]
X
expect_err err-header-trailing-text 1 "malformed section header" <<'X'
[harness a] extra
X
expect_err err-header-missing-name 1 "exactly one NAME" <<'X'
[harness]
X
expect_err err-header-two-names 1 "exactly one NAME" <<'X'
[outfit a b]
X
expect_err err-need-missing-name 2 "HARNESS and a NAME" <<'X'
[harness a]
[need a]
X
expect_err err-include-cycle 4 "include cycle: a -> b -> a" <<'X'
[outfit a]
include = b
[outfit b]
include = a
X
expect_err err-include-self 2 "include cycle: a -> a" <<'X'
[outfit a]
include = a
X
expect_err err-include-cycle-long 6 "include cycle: a -> b -> c -> a" <<'X'
[outfit a]
include = b
[outfit b]
include = c
[outfit c]
include = a
X
expect_err err-include-unknown 3 "include of unknown outfit 'ghost'" <<'X'
[outfit a]
skills = x
include = b ghost
[outfit b]
X
expect_err err-wear-unknown-outfit 2 "wear names unknown outfit 'ghost'" <<'X'
[wear user]
outfits = ghost
X
expect_err err-only-unknown-harness 3 "only names unknown harness 'ghost'" <<'X'
[harness real]
[outfit a]
only = ghost
X
expect_err err-need-unknown-harness 1 "need names unknown harness 'ghost'" <<'X'
[need ghost n]
X
expect_err err-wear-unknown-scope 1 "unknown scope 'galaxy'" <<'X'
[wear galaxy]
X
expect_err err-wear-shared-needs-target 1 "needs a TARGET" <<'X'
[wear shared]
X
expect_err err-wear-personal-needs-target 1 "needs a TARGET" <<'X'
[wear personal machine=m]
X
expect_err err-wear-user-forbids-target 1 "takes no TARGET" <<'X'
[wear user github.com/o/n]
X
expect_err err-wear-enterprise-forbids-target 1 "takes no TARGET" <<'X'
[wear enterprise github.com/o/n]
X
expect_err err-wear-machine-on-enterprise 1 "machine= is allowed only on user and personal" <<'X'
[wear enterprise machine=m]
X
expect_err err-wear-machine-on-shared 1 "machine= is allowed only on user and personal" <<'X'
[wear shared github.com/o/n machine=m]
X
expect_err err-publish-on-user 2 "publish is allowed only on wear shared" <<'X'
[wear user]
publish = yes
X
expect_err err-publish-not-yesno 2 "must be yes or no" <<'X'
[wear shared github.com/o/n]
publish = maybe
X
expect_err err-trust-bad 2 "must be review or auto" <<'X'
[upstream u]
trust = always
X
expect_err err-into-dotdot 2 "'into' must be a relative path of names" <<'X'
[upstream u]
into = skills/../x
X
expect_err err-into-absolute 2 "'into' must be a relative path of names" <<'X'
[upstream u]
into = /skills
X
expect_err err-into-empty-part 2 "'into' must be a relative path of names" <<'X'
[upstream u]
into = skills//x
X
expect_err err-into-trailing-slash 2 "'into' must be a relative path of names" <<'X'
[upstream u]
into = skills/
X
expect_err err-into-dot-part 2 "'into' must be a relative path of names" <<'X'
[upstream u]
into = a/.hidden
X
expect_err err-into-bad-character 2 "'into' must be a relative path of names" <<'X'
[upstream u]
into = a b
X
long=$(awk 'BEGIN { for (i = 0; i < 5; i++) printf "%060d/", 7; print "x" }')
expect_err err-into-too-long 2 "at most 256 bytes" <<X
[upstream u]
into = $long
X
expect_text into-dump 'upstream u
upstream u into = vendor/u' <<'X'
[upstream u]
into = vendor/u
X
expect_err err-empty-value 2 "empty value for 'record'" <<'X'
[harness a]
record =
X
expect_err err-no-equals 2 "expected KEY = VALUE" <<'X'
[harness a]
record=x
X
expect_err err-only-two-words 3 "takes one name" <<'X'
[harness a]
[outfit o]
only = a b
X
expect_err err-bad-list-name 2 "invalid name" <<'X'
[outfit o]
skills = ok bad/name
X
expect_err err-glob-in-include 2 "invalid name" <<'X'
[outfit o]
include = o*
X
expect_err err-two-word-event-name 2 "invalid key" <<'X'
[harness a]
event two words = x
X
printf '[harness a]\nrecord = x\0y\n' > "$T/nul.conf"
"$SUIT" check "$T/nul.conf" >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 2 ] && grep -qF "nul.conf:2: NUL byte in line" "$T/err" && [ ! -s "$T/out" ]; then pass err-nul-byte; else bad err-nul-byte "$(cat "$T/err")"; fi
"$SUIT" check "$T/does-not-exist.conf" >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 2 ] && grep -qF "does-not-exist.conf:0: cannot open" "$T/err"; then pass err-missing-file; else bad err-missing-file "exit $rc $(cat "$T/err")"; fi
"$SUIT" check >/dev/null 2>&1; [ $? -eq 2 ] && pass usage-check-no-file || bad usage-check-no-file

# ---- limits ---------------------------------------------------------------

gen() { # N FORMAT   -> N lines of FORMAT with %d = 1..N on stdout
    awk -v n="$1" -v f="$2" 'BEGIN { for (i = 1; i <= n; i++) printf f "\n", i }'
}

limit_case() { # NAME N FORMAT LIMIT-WORD   (HEAD env: lines to put first)
    name=$1; n=$2; fmt=$3; word=$4
    { printf '%s' "${HEAD:-}"; gen "$n" "$fmt"; } > "$T/$name-at.conf"
    { printf '%s' "${HEAD:-}"; gen $((n + 1)) "$fmt"; } > "$T/$name-over.conf"
    if "$SUIT" check "$T/$name-at.conf" >/dev/null 2>"$T/err"; then pass "$name-at-limit"
    else bad "$name-at-limit" "$(cat "$T/err")"; fi
    hl=0; [ -n "${HEAD:-}" ] && hl=$(printf '%s' "$HEAD" | wc -l | tr -d ' ')
    "$SUIT" check "$T/$name-over.conf" >/dev/null 2>"$T/err"; rc=$?
    if [ $rc -eq 2 ] && grep -qF "$name-over.conf:$((n + 1 + hl)): $word" "$T/err"; then pass "$name-over-limit"
    else bad "$name-over-limit" "exit $rc, $(cat "$T/err")"; fi
}

limit_case limit-harness 64 '[harness h%d]' "too many harness sections (limit 64)"
limit_case limit-outfit 512 '[outfit o%d]' "too many outfit sections (limit 512)"
limit_case limit-wear 256 '[wear personal github.com/o/n%d]' "too many wear sections (limit 256)"
HEAD='[harness h]
' limit_case limit-need 256 '[need h n%d]' "too many need sections (limit 256)"
limit_case limit-upstream 128 '[upstream u%d]' "too many upstream sections (limit 128)"
HEAD='[harness h]
' limit_case limit-entries 8192 'record = r%d' "too many entries (limit 8192)"

awk 'BEGIN { s = "# "; while (length(s) < 4096) s = s "x"; print s }' > "$T/line-at.conf"
awk 'BEGIN { s = "# "; while (length(s) < 4097) s = s "x"; print s }' > "$T/line-over.conf"
if "$SUIT" check "$T/line-at.conf" >/dev/null 2>&1; then pass limit-line-at-limit; else bad limit-line-at-limit; fi
"$SUIT" check "$T/line-over.conf" >/dev/null 2>"$T/err"
if grep -qF "line-over.conf:1: line is 4097 bytes, limit is 4096" "$T/err"; then pass limit-line-over-limit; else bad limit-line-over-limit "$(cat "$T/err")"; fi

# 1048576 bytes exactly is allowed; one more is not. 32768 lines of 32 bytes.
awk 'BEGIN { for (i = 0; i < 32768; i++) print "# 123456789012345678901234567890" }' > "$T/file-at.conf"
printf '\n' >> "$T/file-at.conf"
head -c 1048576 "$T/file-at.conf" > "$T/file-at2.conf"
cp "$T/file-at2.conf" "$T/file-over.conf"; printf '\n' >> "$T/file-over.conf"
if "$SUIT" check "$T/file-at2.conf" >/dev/null 2>"$T/err"; then pass limit-file-at-limit; else bad limit-file-at-limit "$(cat "$T/err")"; fi
"$SUIT" check "$T/file-over.conf" >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 2 ] && grep -qF "file-over.conf:0: file is over the limit of 1048576 bytes" "$T/err"; then pass limit-file-over-limit; else bad limit-file-over-limit "exit $rc $(cat "$T/err")"; fi

# ---- stamp and run --------------------------------------------------------

S=$T/scratch
mkdir -p "$S/files"
for i in 1 2 3; do echo "file $i" > "$S/files/f$i"; done
export SUIT_HOME="$S/home"

"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 11 ] && [ ! -s "$T/out" ] && [ "$(wc -l < "$T/err" | tr -d ' ')" = 1 ] && grep -qF "no stamp at $SUIT_HOME/stamp" "$T/err"; then pass run-no-stamp-exits-11
else bad run-no-stamp-exits-11 "exit $rc $(cat "$T/err")"; fi
[ ! -e "$SUIT_HOME" ] && pass run-no-stamp-creates-nothing || bad run-no-stamp-creates-nothing

"$SUIT" stamp "$S/files/f1" "$S/files/f2" "$S/files/with space" "$S/files/gone" >"$T/out" 2>"$T/err"; rc=$?
[ $rc -eq 0 ] && [ ! -s "$T/out" ] && pass stamp-writes || bad stamp-writes "exit $rc $(cat "$T/err")"
if [ "$(ls "$SUIT_HOME")" = stamp ]; then pass stamp-leaves-no-temp-file; else bad stamp-leaves-no-temp-file "$(ls "$SUIT_HOME")"; fi
if [ "$(wc -l < "$SUIT_HOME/stamp" | tr -d ' ')" = 5 ]; then pass stamp-one-line-per-path; else bad stamp-one-line-per-path; fi
if [ "$(head -1 "$SUIT_HOME/stamp")" = "suit stamp 2" ]; then pass stamp-first-line-is-the-format; else bad stamp-first-line-is-the-format "$(head -1 "$SUIT_HOME/stamp")"; fi
if grep -Eq "^7 [0-9]+ [0-9]+ $S/files/f1\$" "$SUIT_HOME/stamp"; then pass stamp-line-format; else bad stamp-line-format "$(cat "$SUIT_HOME/stamp")"; fi
if grep -qxF -- "- - - $S/files/gone" "$SUIT_HOME/stamp"; then pass stamp-missing-path-recorded; else bad stamp-missing-path-recorded; fi
if [ "$(uname -s)" = Darwin ]; then want=$(stat -f %z "$S/files/f1"); else want=$(stat -c %s "$S/files/f1"); fi
case $(grep "files/f1\$" "$SUIT_HOME/stamp") in "$want "*) pass stamp-size-matches-stat ;; *) bad stamp-size-matches-stat ;; esac

"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 0 ] && [ ! -s "$T/out" ] && [ ! -s "$T/err" ]; then pass run-unchanged-silent-exit-0; else bad run-unchanged-silent-exit-0 "exit $rc"; fi

echo more >> "$S/files/f1"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 10 ] && [ "$(cat "$T/out")" = "changed: $S/files/f1" ]; then pass run-size-change-exit-10; else bad run-size-change-exit-10 "exit $rc $(cat "$T/out")"; fi
"$SUIT" stamp "$S/files/f1" "$S/files/f2" "$S/files/gone" >/dev/null 2>&1

touch -t 200001010000 "$S/files/f2"
"$SUIT" compare >"$T/out" 2>&1; rc=$?
if [ $rc -eq 10 ] && [ "$(cat "$T/out")" = "changed: $S/files/f2" ]; then pass run-mtime-only-change-exit-10; else bad run-mtime-only-change-exit-10 "exit $rc $(cat "$T/out")"; fi
"$SUIT" stamp "$S/files/f1" "$S/files/f2" "$S/files/gone" >/dev/null 2>&1

echo new > "$S/files/gone"
"$SUIT" compare >"$T/out" 2>&1; rc=$?
if [ $rc -eq 10 ] && [ "$(cat "$T/out")" = "changed: $S/files/gone" ]; then pass run-missing-path-appears-exit-10; else bad run-missing-path-appears-exit-10 "exit $rc $(cat "$T/out")"; fi
"$SUIT" stamp "$S/files/f1" "$S/files/f2" "$S/files/gone" >/dev/null 2>&1

rm "$S/files/f1" "$S/files/f2"
"$SUIT" compare >"$T/out" 2>&1; rc=$?
if [ $rc -eq 10 ] && [ "$(sort "$T/out")" = "changed: $S/files/f1
changed: $S/files/f2" ]; then pass run-reports-every-changed-path; else bad run-reports-every-changed-path "exit $rc $(cat "$T/out")"; fi

"$SUIT" stamp "$S/files/gone" >/dev/null 2>&1
printf '1 2 3\n' > "$SUIT_HOME/stamp"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 12 ] && grep -qF "stamp:1: expected SIZE MTIME_SEC MTIME_NSEC PATH" "$T/err"; then pass run-corrupt-stamp-exit-12; else bad run-corrupt-stamp-exit-12 "exit $rc $(cat "$T/err")"; fi
printf '5 1 1 /x' > "$SUIT_HOME/stamp"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 12 ] && grep -qF "stamp:1: line has no newline" "$T/err"; then pass run-truncated-stamp-exit-12; else bad run-truncated-stamp-exit-12 "exit $rc $(cat "$T/err")"; fi
: > "$SUIT_HOME/stamp"
"$SUIT" compare >/dev/null 2>&1; [ $? -eq 0 ] && pass run-empty-stamp-exit-0 || bad run-empty-stamp-exit-0
printf 'suit stamp 2\n' > "$SUIT_HOME/stamp"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 0 ] && [ ! -s "$T/out" ] && [ ! -s "$T/err" ]; then pass run-stamp-of-no-paths-exit-0; else bad run-stamp-of-no-paths-exit-0 "exit $rc $(cat "$T/err")"; fi
printf 'suit stamp 2\n1 2 3\n' > "$SUIT_HOME/stamp"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 12 ] && grep -qF "stamp:2: expected SIZE MTIME_SEC MTIME_NSEC PATH" "$T/err"; then pass run-bad-line-after-the-format-exit-12; else bad run-bad-line-after-the-format-exit-12 "exit $rc $(cat "$T/err")"; fi
# A stamp of the previous format (no first line naming it) is a change, named by the stamp's own path.
"$SUIT" stamp "$S/files/gone" >/dev/null 2>&1
tail -n +2 "$SUIT_HOME/stamp" > "$T/old-stamp"; cp "$T/old-stamp" "$SUIT_HOME/stamp"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 10 ] && [ "$(cat "$T/out")" = "changed: $SUIT_HOME/stamp" ] && [ ! -s "$T/err" ]; then pass run-old-format-stamp-is-a-change; else bad run-old-format-stamp-is-a-change "exit $rc $(cat "$T/out" "$T/err")"; fi
printf 'suit stamp 1\n' > "$SUIT_HOME/stamp"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 12 ] && grep -qF "stamp:1: expected SIZE MTIME_SEC MTIME_NSEC PATH" "$T/err"; then pass run-unknown-format-line-exit-12; else bad run-unknown-format-line-exit-12 "exit $rc $(cat "$T/err")"; fi

"$SUIT" stamp "$SUIT_HOME/nonexistent/../x" >/dev/null 2>&1; [ $? -eq 0 ] && pass stamp-odd-missing-path-ok || bad stamp-odd-missing-path-ok
"$SUIT" stamp >/dev/null 2>&1; [ $? -eq 2 ] && pass usage-stamp-no-paths || bad usage-stamp-no-paths
"$SUIT" run extra >/dev/null 2>&1; [ $? -eq 2 ] && pass usage-run-extra-arg || bad usage-run-extra-arg
for c in compare plan apply status off; do
    "$SUIT" "$c" extra >/dev/null 2>&1; [ $? -eq 2 ] && pass "usage-$c-extra-arg" || bad "usage-$c-extra-arg"
done
"$SUIT" >/dev/null 2>&1; [ $? -eq 2 ] && pass usage-no-command || bad usage-no-command
"$SUIT" frobnicate >/dev/null 2>&1; [ $? -eq 2 ] && pass usage-unknown-command || bad usage-unknown-command

# ---- the no-change run writes nothing ------------------------------------

snap() { # DIR: every path with mode, size, mtime to the nanosecond, and a content sum
    if [ "$(uname -s)" = Darwin ]; then
        find "$1" -exec stat -f '%N %Sp %z %Fm' {} + | sort
    else
        find "$1" -exec stat -c '%n %A %s %.9Y' {} + | sort
    fi
    find "$1" -type f -exec cksum {} + | sort
}

W=$T/nowrite
mkdir -p "$W/tree/sub"
i=0
while [ $i -lt 100 ]; do
    echo "content $i" > "$W/tree/sub/file$i"
    i=$((i + 1))
done
export SUIT_HOME="$W/home"
"$SUIT" stamp "$W"/tree/sub/file* >/dev/null 2>&1
snap "$W" > "$T/before"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
snap "$W" > "$T/after"
if [ $rc -eq 0 ] && [ ! -s "$T/out" ] && [ ! -s "$T/err" ]; then pass no-write-run-silent-exit-0; else bad no-write-run-silent-exit-0 "exit $rc"; fi
if [ -s "$T/before" ] && cmp -s "$T/before" "$T/after"; then pass no-write-tree-unchanged; else bad no-write-tree-unchanged "$(diff "$T/before" "$T/after" | head -5)"; fi
n=$(wc -l < "$T/before" | tr -d ' ')
[ "$n" -gt 200 ] && pass no-write-snapshot-covers-all-files || bad no-write-snapshot-covers-all-files "only $n lines"
unset SUIT_HOME

# ---- bench arguments ------------------------------------------------------

for args in "-n 0" "-n x" "-n 10001" "-q" "-n" "-e"; do
    # shellcheck disable=SC2086
    "$SUIT" bench $args >/dev/null 2>&1; rc=$?
    [ $rc -eq 2 ] && pass "bench-rejects-[$args]" || bad "bench-rejects-[$args]" "exit $rc"
done
SUIT_HOME="$T/no-such-home" "$SUIT" bench -n 3 >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "exited with status 11" "$T/err"; then pass bench-without-stamp-fails; else bad bench-without-stamp-fails "exit $rc $(cat "$T/err")"; fi

SUIT_HOME="$T/no-such-home" "$SUIT" bench -n 3 -e "$T/no-empty" >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "cannot spawn $T/no-empty" "$T/err"; then pass bench-missing-empty-program-fails; else bad bench-missing-empty-program-fails "exit $rc $(cat "$T/err")"; fi


# ---- fault injection and the remaining paths --------------------------------
# SUIT_FAULT=NAME:N[:ERRNO|short] makes the Nth call to wrapper NAME fail.
# These cases need a test build (-DSUIT_TEST); the release build has no such
# code, and test/release_clean.sh checks that.

# fcase NAME SPEC WANT_RC STDERR_SUBSTRING -- COMMAND...
fcase() {
    fname=$1; fspec=$2; fwant=$3; fmsg=$4; shift 5
    SUIT_FAULT=$fspec "$@" >"$T/fout" 2>"$T/ferr"; frc=$?
    if [ "$frc" != "$fwant" ]; then bad "$fname" "exit $frc, want $fwant: $(cat "$T/ferr")"
    elif [ -n "$fmsg" ] && ! grep -qF -- "$fmsg" "$T/ferr"; then bad "$fname" "want '$fmsg' in: $(cat "$T/ferr")"
    else pass "$fname"; fi
}

F=$T/fault
mkdir -p "$F/files" "$F/other" "$F/aa"
for n in 1 2 3; do echo "f$n" > "$F/files/f$n"; echo "o$n" > "$F/other/o$n"; done
echo x > "$F/aa/x"
export SUIT_HOME="$F/home"

# -- the SUIT_FAULT variable itself
fcase fault-spec-no-colon bogus 99 "expected NAME:N" -- "$SUIT" compare
fcase fault-spec-unknown-name frob:1 99 "unknown call name" -- "$SUIT" compare
fcase fault-spec-count-not-number read:x 99 "N must be a positive number" -- "$SUIT" compare
fcase fault-spec-count-zero read:0 99 "N must be a positive number" -- "$SUIT" compare
fcase fault-spec-count-trailing read:2x 99 "N must be a positive number" -- "$SUIT" compare
fcase fault-spec-short-on-open open:1:short 99 "short applies only to read and write" -- "$SUIT" compare
fcase fault-spec-unknown-errno read:1:EWHAT 99 "unknown errno" -- "$SUIT" compare
fcase fault-spec-errno-zero read:1:0 99 "unknown errno" -- "$SUIT" compare
fcase fault-spec-errno-trailing read:1:12x 99 "unknown errno" -- "$SUIT" compare
fcase fault-spec-numeric-errno open:1:2 2 "cannot open: No such file or directory" -- "$SUIT" check test/fixtures/example.conf
fcase fault-spec-named-errno open:1:EACCES 2 "cannot open: Permission denied" -- "$SUIT" check test/fixtures/example.conf

# -- suit check
EX=test/fixtures/example.conf
# The C library words errno 5 its own way (glibc and macOS spell it out,
# musl says "I/O error"). Ask the binary under test.
EIO=$(SUIT_FAULT=open:1 "$SUIT" check $EX 2>&1 | sed -n 's/.*cannot open: //p')
[ -n "$EIO" ] || { echo "FAIL cannot learn the errno wording"; exit 1; }
fcase fault-check-open open:1 2 "cannot open: $EIO" -- "$SUIT" check $EX
fcase fault-check-read read:1 2 "cannot read: $EIO" -- "$SUIT" check $EX
fcase fault-check-read-interrupted-retries read:1:EINTR 0 "" -- "$SUIT" check $EX
fcase fault-check-short-read read:1:short 0 "" -- "$SUIT" check $EX
fcase fault-check-close-ignored close:1 0 "" -- "$SUIT" check $EX
fcase fault-check-write write:1 1 "cannot write the dump: $EIO" -- "$SUIT" check $EX
fcase fault-check-write-interrupted-retries write:1:EINTR 0 "" -- "$SUIT" check $EX
for spec in short; do
    SUIT_FAULT=write:1:$spec "$SUIT" check $EX > "$T/shortdump" 2>/dev/null
    if cmp -s "$T/shortdump" test/fixtures/example.dump; then pass fault-check-short-write-dump-complete; else bad fault-check-short-write-dump-complete; fi
done
fcase fault-check-write-fails-after-buffer-fills write:1 1 "cannot write the dump" -- "$SUIT" check "$T/limit-entries-at.conf"
SUIT_FAULT=write:3 "$SUIT" check "$T/limit-entries-at.conf" >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "cannot write the dump" "$T/err"; then pass fault-check-write-fails-midway; else bad fault-check-write-fails-midway "exit $rc"; fi
"$SUIT" check "$T/limit-entries-at.conf" > "$T/bigdump"; rc=$?
if [ $rc -eq 0 ] && [ "$(wc -l < "$T/bigdump" | tr -d ' ')" -gt 8000 ]; then pass check-large-dump-spans-buffers; else bad check-large-dump-spans-buffers; fi
longname=$(awk 'BEGIN { for (i = 0; i < 9000; i++) printf "a" }')
"$SUIT" check "$longname" >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 2 ] && [ "$(wc -c < "$T/err" | tr -d ' ')" -le 8192 ] && [ "$(wc -l < "$T/err" | tr -d ' ')" = 1 ]; then pass err-very-long-message-is-cut-to-one-line; else bad err-very-long-message-is-cut-to-one-line "exit $rc, $(wc -c < "$T/err") bytes"; fi
: > "$T/empty-for-dump.conf"
"$SUIT" check "$T/empty-for-dump.conf" >"$T/out" 2>&1; [ $? -eq 0 ] && [ ! -s "$T/out" ] && pass check-empty-dump-writes-nothing || bad check-empty-dump-writes-nothing

# -- suit stamp
FILES="$F/files/f1 $F/files/f2"
fresh() { rm -rf "$F/home" "$F/fakehome"; mkdir -p "$F/fakehome"; }
fresh
fcase fault-stamp-getenv-absent-falls-back-to-home getenv:1 0 "" -- env HOME="$F/fakehome" "$SUIT" stamp $FILES
[ -f "$F/fakehome/.suit/stamp" ] && pass stamp-uses-home-when-suit-home-absent || bad stamp-uses-home-when-suit-home-absent
fresh
env SUIT_HOME= HOME="$F/fakehome" "$SUIT" stamp $FILES >/dev/null 2>&1
[ -f "$F/fakehome/.suit/stamp" ] && pass stamp-empty-suit-home-falls-back-to-home || bad stamp-empty-suit-home-falls-back-to-home
env -u SUIT_HOME -u HOME "$SUIT" stamp $FILES >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "neither SUIT_HOME nor HOME is set" "$T/err"; then pass stamp-no-home-at-all; else bad stamp-no-home-at-all "exit $rc"; fi
env -u SUIT_HOME HOME= "$SUIT" compare >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "neither SUIT_HOME nor HOME is set" "$T/err"; then pass run-empty-home-at-all; else bad run-empty-home-at-all "exit $rc"; fi
longhome=$(awk 'BEGIN { for (i = 0; i < 4090; i++) printf "h" }')
SUIT_HOME=/$longhome "$SUIT" stamp $FILES >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "home path is longer than" "$T/err"; then pass stamp-home-path-too-long; else bad stamp-home-path-too-long "exit $rc"; fi
fresh
fcase fault-stamp-stat-fails stat:1 1 "cannot stat $F/files/f1: $EIO" -- "$SUIT" stamp $FILES
fcase fault-stamp-stat-enoent-is-missing stat:1:ENOENT 0 "" -- "$SUIT" stamp $FILES
grep -qxF -- "- - - $F/files/f1" "$F/home/stamp" && pass stamp-injected-enoent-recorded-missing || bad stamp-injected-enoent-recorded-missing
fcase fault-stamp-stat-enotdir-is-missing stat:1:ENOTDIR 0 "" -- "$SUIT" stamp $FILES
fresh
fcase fault-stamp-mkdir mkdir:1:EACCES 1 "cannot create $F/home: Permission denied" -- "$SUIT" stamp $FILES
[ ! -e "$F/home" ] && pass stamp-mkdir-failure-leaves-nothing || bad stamp-mkdir-failure-leaves-nothing
fresh; mkdir -p "$F/home"
"$SUIT" stamp $FILES >/dev/null 2>&1
cp "$F/home/stamp" "$T/stamp-before"
for spec in open:1 write:1 fsync:1 close:1 rename:1; do
    fcase "fault-stamp-${spec%%:*}" "$spec" 1 "cannot write $F/home/stamp: $EIO" -- "$SUIT" stamp "$F/files/f3"
    if cmp -s "$F/home/stamp" "$T/stamp-before"; then pass "fault-stamp-${spec%%:*}-keeps-old-stamp"; else bad "fault-stamp-${spec%%:*}-keeps-old-stamp"; fi
    if [ "$(ls "$F/home")" = stamp ]; then pass "fault-stamp-${spec%%:*}-leaves-no-temp-file"; else bad "fault-stamp-${spec%%:*}-leaves-no-temp-file" "$(ls "$F/home")"; fi
done
fcase fault-stamp-write-interrupted-retries write:1:EINTR 0 "" -- "$SUIT" stamp $FILES
fcase fault-stamp-short-write write:1:short 0 "" -- "$SUIT" stamp $FILES
"$SUIT" compare >/dev/null 2>&1 && pass stamp-after-short-write-is-complete || bad stamp-after-short-write-is-complete
fcase fault-stamp-unlink-failure-is-ignored write:1 1 "cannot write" -- "$SUIT" stamp $FILES
for p in "" ; do
    "$SUIT" stamp "" >/dev/null 2>"$T/err"; rc=$?
    if [ $rc -eq 1 ] && grep -qF "path 1 is empty" "$T/err"; then pass stamp-empty-path-rejected; else bad stamp-empty-path-rejected "exit $rc"; fi
done
"$SUIT" stamp "$F/files/f1
x" >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "path 1 is empty, has a newline" "$T/err"; then pass stamp-newline-path-rejected; else bad stamp-newline-path-rejected "exit $rc"; fi
longpath=/$(awk 'BEGIN { for (i = 0; i < 4096; i++) printf "p" }')
"$SUIT" stamp "$F/files/f1" "$longpath" >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "path 2 is empty, has a newline, or is longer than 4095 bytes" "$T/err"; then pass stamp-too-long-path-rejected; else bad stamp-too-long-path-rejected "exit $rc"; fi
mk4095=/$(awk 'BEGIN { for (i = 0; i < 4093; i++) printf "p" }')
fcase stamp-longest-path-accepted stat:1:ENOENT 0 "" -- "$SUIT" stamp "$mk4095"

# -- suit run
S2=$F/run
fresh; mkdir -p "$S2"; cd "$S2" || exit 1
echo rel > relfile; mkdir -p d1 d2 dd
echo 1 > d1/a; echo 2 > d1/b; echo 3 > d2/a; echo 4 > dd/a
"$SUIT" stamp relfile d1/a d1/b d2/a dd/a "$S2/d1/a" "$S2/d1/b" "$S2/d2/a" /suit-no-such-root-file "$S2/d1/" "$S2/d1/gone" >/dev/null 2>&1
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 0 ] && [ ! -s "$T/out" ] && [ ! -s "$T/err" ]; then pass run-mixed-folders-unchanged; else bad run-mixed-folders-unchanged "exit $rc $(cat "$T/out")"; fi
echo more >> d1/b; echo more >> d2/a
"$SUIT" compare >"$T/out" 2>&1; rc=$?
if [ $rc -eq 10 ] && [ "$(cat "$T/out")" = "changed: d1/b
changed: d2/a
changed: $S2/d1/b
changed: $S2/d2/a" ]; then pass run-reports-changes-across-folders; else bad run-reports-changes-across-folders "exit $rc $(cat "$T/out")"; fi
"$SUIT" stamp "$S2/d1/a" "$S2/d1/b" "$S2/d1/gone" >/dev/null 2>&1
fcase fault-run-getenv-absent-falls-back-to-home getenv:1 11 "no stamp at" -- env HOME="$F/fakehome" "$SUIT" compare
fcase fault-run-open-stamp open:1 1 "cannot read $F/home/stamp: $EIO" -- "$SUIT" compare
fcase fault-run-open-stamp-enoent open:1:ENOENT 11 "no stamp at" -- "$SUIT" compare
fcase fault-run-read read:1 1 "cannot read $F/home/stamp: $EIO" -- "$SUIT" compare
fcase fault-run-read-interrupted-retries read:1:EINTR 0 "" -- "$SUIT" compare
fcase fault-run-short-reads read:1:short 0 "" -- "$SUIT" compare
fcase fault-run-close-stamp-ignored close:1 0 "" -- "$SUIT" compare
fcase fault-run-stat-fails-present-path-is-changed stat:1 10 "" -- "$SUIT" compare
fcase fault-run-folder-open-fails-falls-back-to-stat open:2:EACCES 0 "" -- "$SUIT" compare
fcase fault-run-fstatat-fails-present-path-is-changed fstatat:1 10 "" -- "$SUIT" compare
fcase fault-run-folder-close-ignored close:2 0 "" -- "$SUIT" compare
fcase fault-run-write-of-changed-line-ignored write:1 0 "" -- "$SUIT" compare
"$SUIT" stamp "$S2/d1/gone" "$S2/d1/gone2" >/dev/null 2>&1
fcase fault-run-stat-eio-on-missing-path-is-changed stat:1 10 "" -- "$SUIT" compare
fcase fault-run-stat-enotdir-on-missing-path-is-unchanged stat:1:ENOTDIR 0 "" -- "$SUIT" compare
fcase fault-run-stat-enoent-on-missing-path-is-unchanged stat:1:ENOENT 0 "" -- "$SUIT" compare
cd "$ROOT" || exit 1

# Hand-made stamps.
stamp_case() { # NAME RC MSG   (stamp text on stdin)
    cat > "$F/home/stamp"
    "$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
    if [ $rc -ne "$2" ]; then bad "$1" "exit $rc want $2: $(cat "$T/err") $(cat "$T/out")"
    elif [ -n "$3" ] && ! grep -qF -- "$3" "$T/err"; then bad "$1" "want '$3' in $(cat "$T/err")"
    else pass "$1"; fi
}
stamp_case stamp-first-field-not-a-number 12 "stamp:1: expected SIZE" <<'X'
x 1 1 /a
X
stamp_case stamp-second-field-not-a-number 12 "stamp:1: expected SIZE" <<'X'
1 x 1 /a
X
stamp_case stamp-third-field-not-a-number 12 "stamp:3: expected SIZE" <<'X'
suit stamp 2
- - - /nonexistent-a
1 1 x /a
X
stamp_case stamp-number-overflows 12 "stamp:1: expected SIZE" <<'X'
99999999999999999999 1 1 /a
X
stamp_case stamp-number-just-under-overflow-is-fine 10 "" <<'X'
suit stamp 2
922337203685477579 1 1 /a
X
stamp_case stamp-number-followed-by-a-letter 12 "stamp:1: expected SIZE" <<'X'
12x 1 1 /a
X
stamp_case stamp-negative-number 12 "stamp:1: expected SIZE" <<'X'
-1 1 1 /a
X
stamp_case stamp-number-not-followed-by-space 12 "stamp:1: expected SIZE" <<'X'
1 2 3
X
stamp_case stamp-empty-path 12 "stamp:1: path is empty" <<'X'
1 1 1 
X
stamp_case stamp-missing-marker-with-empty-path 12 "stamp:1: path is empty" <<'X'
- - - 
X
printf '1 2 3 /a' > "$F/home/stamp"
"$SUIT" compare >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 12 ] && grep -qF "stamp:1: line has no newline" "$T/err"; then pass stamp-last-line-without-newline; else bad stamp-last-line-without-newline "exit $rc"; fi
head -c 1048576 /dev/zero | tr '\0' '\n' > "$F/home/stamp"
"$SUIT" compare >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 12 ] && grep -qF "stamp:1: expected SIZE" "$T/err"; then pass stamp-exactly-at-limit-is-read; else bad stamp-exactly-at-limit-is-read "exit $rc $(cat "$T/err")"; fi
head -c 1048577 /dev/zero | tr '\0' '\n' > "$F/home/stamp"
"$SUIT" compare >/dev/null 2>"$T/err"; rc=$?
if [ $rc -eq 12 ] && grep -qF "stamp:1: stamp is larger than the limit" "$T/err"; then pass stamp-over-limit; else bad stamp-over-limit "exit $rc $(cat "$T/err")"; fi
# Only the nanoseconds differ from what the file has.
echo ns > "$F/nsfile"
"$SUIT" stamp "$F/nsfile" >/dev/null 2>&1
awk 'NR > 1 { $3 = ($3 == 1 ? 2 : 1) } { print }' "$F/home/stamp" > "$F/home/stamp.new" && mv "$F/home/stamp.new" "$F/home/stamp"
"$SUIT" compare >"$T/out" 2>&1; rc=$?
if [ $rc -eq 10 ] && [ "$(cat "$T/out")" = "changed: $F/nsfile" ]; then pass run-nanosecond-only-change-exit-10; else bad run-nanosecond-only-change-exit-10 "exit $rc $(cat "$T/out")"; fi
"$SUIT" stamp "$F/nsfile" >/dev/null 2>&1
awk 'NR > 1 { $2 = $2 + 1 } { print }' "$F/home/stamp" > "$F/home/stamp.new" && mv "$F/home/stamp.new" "$F/home/stamp"
"$SUIT" compare >"$T/out" 2>&1; rc=$?
if [ $rc -eq 10 ]; then pass run-second-only-change-exit-10; else bad run-second-only-change-exit-10 "exit $rc"; fi
printf 'suit stamp 2\n5 1 1 /suit-no-such-file\nx\n' > "$F/home/stamp"
"$SUIT" compare >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 12 ] && grep -q "^changed: /suit-no-such-file" "$T/out"; then pass run-bad-line-after-change-is-still-bad; else bad run-bad-line-after-change-is-still-bad "exit $rc"; fi

# -- suit bench
B=$F/bench
mkdir -p "$B/files"; echo b > "$B/files/b1"
export SUIT_HOME="$B/home"
"$SUIT" stamp "$B/files/b1" >/dev/null 2>&1
"$SUIT" bench -n 3 -t 1000000 -m 1048576 >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 0 ] && grep -qF "time, per-round median over empty" "$T/out" && grep -qF ": ok" "$T/out" && ! grep -qF OVER "$T/out"; then pass bench-within-budget-exit-0; else bad bench-within-budget-exit-0 "exit $rc $(cat "$T/out") $(cat "$T/err")"; fi
if grep -qF "/usr/bin/true (info only)" "$T/out" && grep -qF "suit-run over empty" "$T/out" && grep -qF "suit-run over /usr/bin/true" "$T/out" && grep -qF "median of per-round differences, suit-run over empty" "$T/out"; then pass bench-prints-the-table; else bad bench-prints-the-table; fi
"$SUIT" bench -n 3 -t -1000000 -m 1048576 >"$T/out" 2>&1; rc=$?
if [ $rc -eq 1 ] && grep -qF "budget: time" "$T/out" && grep -qF "OVER" "$T/out"; then pass bench-over-time-budget-exit-1; else bad bench-over-time-budget-exit-1 "exit $rc"; fi
"$SUIT" bench -n 3 -t 1000000 -m -1048576 >"$T/out" 2>&1; rc=$?
if [ $rc -eq 1 ] && grep -qF "budget: resident" "$T/out" && grep -qF "OVER" "$T/out"; then pass bench-over-resident-budget-exit-1; else bad bench-over-resident-budget-exit-1 "exit $rc"; fi
for args in "-n 99999999999999999999" "-n ''" "-n 12x" "-t x" "-m x" "-t 1000001" "-m -1048577" "-n 1 -q" "-q 1"; do
    eval "\"\$SUIT\" bench $args" >/dev/null 2>"$T/err"; rc=$?
    [ $rc -eq 2 ] && grep -qF usage "$T/err" && pass "bench-rejects-[$args]" || bad "bench-rejects-[$args]" "exit $rc"
done
"$SUIT" bench -n 2 -e /usr/bin/false >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "/usr/bin/false exited with status 1" "$T/err"; then pass bench-empty-program-exits-nonzero; else bad bench-empty-program-exits-nonzero "exit $rc $(cat "$T/err")"; fi
printf '#!/bin/sh\nkill -9 $$\n' > "$B/killself"; chmod +x "$B/killself"
"$SUIT" bench -n 2 -e "$B/killself" >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "killself was killed by signal 9" "$T/err"; then pass bench-empty-program-killed-by-signal; else bad bench-empty-program-killed-by-signal "exit $rc $(cat "$T/err")"; fi
fcase fault-bench-self-path self_path:1 1 "cannot find the path of this program" -- "$SUIT" bench -n 2
fcase fault-bench-clock-start clock_gettime:1 1 "cannot read the clock" -- "$SUIT" bench -n 2
fcase fault-bench-clock-stop clock_gettime:2 1 "cannot read the clock" -- "$SUIT" bench -n 2
fcase fault-bench-spawn spawn:1 1 "cannot spawn /usr/bin/true: $EIO" -- "$SUIT" bench -n 2
fcase fault-bench-spawn-in-warmup-rounds spawn:31 1 "cannot spawn" -- "$SUIT" bench -n 2
fcase fault-bench-spawn-in-measured-rounds spawn:41 1 "cannot spawn" -- "$SUIT" bench -n 2
fcase fault-bench-wait4 wait4:1 1 "wait4 failed: $EIO" -- "$SUIT" bench -n 2
fcase fault-bench-wait4-interrupted-retries wait4:1:EINTR 0 "" -- "$SUIT" bench -n 2 -t 1000000 -m 1048576
unset SUIT_HOME


# ---- suit-run, the front program ------------------------------------------
# It does the no-change compare itself and starts `suit run` only when
# something differs.

FRONT=${FRONT:-$(dirname "$SUIT")/suit-run}
R=$T/front
mkdir -p "$R/files" "$R/solo"
echo f > "$R/files/f"
export SUIT_HOME="$R/home"
"$SUIT" stamp "$R/files/f" >/dev/null 2>&1
"$FRONT" >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 0 ] && [ ! -s "$T/out" ] && [ ! -s "$T/err" ]; then pass front-unchanged-silent-exit-0; else bad front-unchanged-silent-exit-0 "exit $rc"; fi
echo more >> "$R/files/f"
"$FRONT" >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && [ ! -s "$T/out" ] && grep -qF "store:0: no wardrobe with a suit.conf" "$T/err"; then pass front-changed-hands-over-to-suit-run; else bad front-changed-hands-over-to-suit-run "exit $rc $(cat "$T/out") $(cat "$T/err")"; fi
fcase fault-front-exec exec:1 1 "suit-run: cannot run" -- "$FRONT"
fcase fault-front-self-path self_path:1 1 "suit-run: cannot find the path of this program" -- "$FRONT"
cp "$FRONT" "$R/solo/suit-run"
"$R/solo/suit-run" >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 1 ] && grep -qF "suit-run: cannot run $R/solo/suit: No such file or directory" "$T/err"; then pass front-without-suit-beside-it-fails; else bad front-without-suit-beside-it-fails "exit $rc $(cat "$T/err")"; fi
export SUIT_HOME="$R/nohome"
"$FRONT" >"$T/out" 2>"$T/err"; rc=$?
if [ $rc -eq 11 ] && grep -qF "no stamp at" "$T/err"; then pass front-no-stamp-exit-11; else bad front-no-stamp-exit-11 "exit $rc $(cat "$T/err")"; fi
unset SUIT_HOME

# -- no test names a C library's wording for an errno: Fil-C words them differently
if grep -rlF "Input/output"" error" test >/dev/null 2>&1; then bad lint-no-test-has-the-libc-eio-wording "$(grep -rlF "Input/output"" error" test)"; else pass lint-no-test-has-the-libc-eio-wording; fi
LINT=$T/lint; mkdir -p "$LINT"; printf 'Input/output'' error\n' > "$LINT/t.sh"
if grep -rlF "Input/output"" error" "$LINT" >/dev/null 2>&1; then pass lint-sees-the-wording-when-it-is-there; else bad lint-sees-the-wording-when-it-is-there; fi

# ---- install, uninstall and status --line ----------------------------------------
# Every run has HOME and SUIT_HOME in a scratch folder and the loader is a
# script that records its arguments (SUIT_LOADER, which only the test build
# reads), so nothing here touches the real LaunchAgents folder or systemd.

inst_tests() {
OLDHOME=$HOME
I=$T/inst
UIDN=$(id -u)
cat > "$T/loader.sh" <<EOF
#!/bin/sh
echo "\$@" >> "$I/calls"
st=\$(cat "$I/status" 2>/dev/null || echo 0)
[ "\$st" = kill ] && kill -9 \$\$
exit "\$st"
EOF
chmod +x "$T/loader.sh"
export SUIT_LOADER=$T/loader.sh

fresh() {
    rm -rf "$I"; mkdir -p "$I/home"; : > "$I/calls"; echo 0 > "$I/status"
    export HOME=$I/home
    unset SUIT_HOME XDG_CONFIG_HOME
    case $HOME in "$T"/*) ;; *) echo "FAIL install tests: HOME is not a scratch folder: $HOME"; exit 1 ;; esac
}
ins() { "$SUIT" "$@" >"$T/iout" 2>"$T/ierr"; irc=$?; }
t() { tname=$1; shift; if "$@" >/dev/null 2>&1; then pass "$tname"; else bad "$tname" "rc $irc: $(head -c 300 "$T/iout") $(head -c 300 "$T/ierr")"; fi; }
outhas() { grep -qxF -- "$1" "$T/iout"; }
errhas() { grep -qF -- "$1" "$T/ierr"; }
callsare() { [ "$(cat "$I/calls")" = "$1" ]; }
rcis() { [ "$irc" = "$1" ]; }
snapshot() { (cd "$HOME" && find . | sort && find . -type f | sort | xargs cksum) 2>/dev/null; }
modeis() { [ "$(ls -l "$1" | cut -c1-10)" = "$2" ]; }
NL='
'

# -- macOS: two property lists and the launchctl calls
export SUIT_PLATFORM=macos
fresh; PL=$HOME/Library/LaunchAgents
RUNP=$PL/app.zeitforge.suit.run.plist; TENDP=$PL/app.zeitforge.suit.tend.plist
ins install
t mac-install-exits-0 rcis 0
t mac-install-says-run outhas "run: installed"
t mac-install-says-tend outhas "tend: installed"
t mac-install-loads-both callsare "bootstrap gui/$UIDN $RUNP${NL}bootstrap gui/$UIDN $TENDP"
t mac-install-writes-run-plist grep -qF "<string>$(dirname "$SUIT")/suit-run</string>" "$RUNP"
t mac-install-run-every-60 grep -qF "<integer>60</integer>" "$RUNP"
t mac-install-tend-starts-suit-tend grep -qF "<string>tend</string>" "$TENDP"
t mac-install-tend-every-3600 grep -qF "<integer>3600</integer>" "$TENDP"
t mac-install-plist-mode-0644 modeis "$RUNP" -rw-r--r--
t mac-install-makes-the-log-folder test -d "$HOME/.suit/log"
t mac-install-default-home-passes-no-environment sh -c '! grep -q SUIT_HOME "$1"' x "$RUNP"
t mac-install-stderr-path grep -qF "<string>$HOME/.suit/log/run.err</string>" "$RUNP"
cp "$RUNP" "$I/run.plist.good"
: > "$I/calls"; before=$(snapshot)
ins install
t mac-install-twice-exits-0 rcis 0
t mac-install-twice-says-already-run outhas "run: already installed"
t mac-install-twice-says-already-tend outhas "tend: already installed"
t mac-install-twice-calls-no-loader callsare ""
t mac-install-twice-writes-nothing test "$before" = "$(snapshot)"
# a file changed by hand is rewritten and its timer reloaded
echo '<!-- by hand -->' >> "$RUNP"
ins install
t mac-install-after-edit-exits-0 rcis 0
t mac-install-after-edit-says-updated outhas "run: updated"
t mac-install-after-edit-leaves-tend outhas "tend: already installed"
t mac-install-after-edit-restores-the-file cmp -s "$RUNP" "$I/run.plist.good"
t mac-install-after-edit-unloads-then-loads callsare "bootout gui/$UIDN/app.zeitforge.suit.run${NL}bootstrap gui/$UIDN $RUNP${NL}bootout gui/$UIDN/app.zeitforge.suit.tend${NL}bootstrap gui/$UIDN $TENDP"
# a removed file is made again, and the other timer is loaded again too
rm "$TENDP"; : > "$I/calls"
ins install
t mac-install-after-delete-says-installed outhas "tend: installed"
t mac-install-after-delete-callsare callsare "bootout gui/$UIDN/app.zeitforge.suit.run${NL}bootstrap gui/$UIDN $RUNP${NL}bootstrap gui/$UIDN $TENDP"
head -c 30000 /dev/zero | tr '\0' a > "$RUNP"
ins install
t mac-install-over-a-huge-file-says-updated outhas "run: updated"
t mac-install-over-a-huge-file-restores cmp -s "$RUNP" "$I/run.plist.good"
sed 's/Background/Backgroun_/' "$TENDP" > "$I/tend.edit"; cat "$I/tend.edit" > "$TENDP"
ins install
t mac-install-over-same-length-text-says-updated outhas "tend: updated"
# --print changes nothing and says each file under its path
fresh; PL=$HOME/Library/LaunchAgents; RUNP=$PL/app.zeitforge.suit.run.plist; TENDP=$PL/app.zeitforge.suit.tend.plist
before=$(snapshot)
ins install --print
t mac-print-exits-0 rcis 0
t mac-print-names-the-run-file outhas "# $RUNP"
t mac-print-names-the-tend-file outhas "# $TENDP"
t mac-print-shows-the-text grep -qF "<integer>3600</integer>" "$T/iout"
t mac-print-changes-nothing test "$before" = "$(snapshot)"
t mac-print-calls-no-loader callsare ""
# a file of someone else's in the folder is never touched
mkdir -p "$PL"; printf 'not mine\n' > "$PL/other.app.plist"
ins install
t foreign-file-survives-install test "$(cat "$PL/other.app.plist")" = "not mine"
ins uninstall
t foreign-file-survives-uninstall test "$(cat "$PL/other.app.plist")" = "not mine"
t uninstall-leaves-the-folder test -d "$PL"
fresh; (umask 077; "$SUIT" install >/dev/null 2>&1)
t mac-install-mode-0644-under-umask-077 modeis "$HOME/Library/LaunchAgents/app.zeitforge.suit.run.plist" -rw-r--r--
chmod 600 "$HOME/Library/LaunchAgents/app.zeitforge.suit.run.plist"; echo '<!-- x -->' >> "$HOME/Library/LaunchAgents/app.zeitforge.suit.run.plist"
(umask 077; "$SUIT" install >/dev/null 2>&1)
t mac-install-rewrite-sets-mode-0644 modeis "$HOME/Library/LaunchAgents/app.zeitforge.suit.run.plist" -rw-r--r--

# -- uninstall
fresh; PL=$HOME/Library/LaunchAgents; RUNP=$PL/app.zeitforge.suit.run.plist; TENDP=$PL/app.zeitforge.suit.tend.plist
ins install; : > "$I/calls"
ins uninstall
t uninstall-exits-0 rcis 0
t uninstall-unloads-both callsare "bootout gui/$UIDN/app.zeitforge.suit.run${NL}bootout gui/$UIDN/app.zeitforge.suit.tend"
t uninstall-says-removed-run outhas "removed $RUNP"
t uninstall-says-removed-tend outhas "removed $TENDP"
t uninstall-removes-the-files sh -c '! [ -e "$1" ] && ! [ -e "$2" ]' x "$RUNP" "$TENDP"
: > "$I/calls"
ins uninstall
t uninstall-twice-exits-0 rcis 0
t uninstall-twice-says-not-installed outhas "not installed"
t uninstall-twice-calls-no-loader callsare ""
# a loader that says no to unloading is reported and the files still go
ins install; echo 5 > "$I/status"; : > "$I/calls"
ins uninstall
t uninstall-loader-failure-exits-0 rcis 0
t uninstall-loader-failure-is-reported errhas "exited with status 5 (already unloaded is normal)"
t uninstall-loader-failure-still-removes sh -c '! [ -e "$1" ] && ! [ -e "$2" ]' x "$RUNP" "$TENDP"
# a loader that says no to loading: the files stay and it says so
fresh; PL=$HOME/Library/LaunchAgents; RUNP=$PL/app.zeitforge.suit.run.plist; echo 7 > "$I/status"
ins install
t load-failure-exits-3 rcis 3
t load-failure-names-the-status errhas "exited with status 7"
t load-failure-says-the-files-stay errhas "the files are in place in $PL"
t load-failure-leaves-the-files test -f "$RUNP"
t load-failure-stops-at-the-first-timer callsare "bootstrap gui/$UIDN $RUNP"
fresh; echo kill > "$I/status"
ins install
t load-killed-exits-3 rcis 3
t load-killed-says-the-signal errhas "was killed by signal 9"
# SUIT_HOME other than the default is handed to the timers; the default is not
fresh; PL=$HOME/Library/LaunchAgents; RUNP=$PL/app.zeitforge.suit.run.plist
export SUIT_HOME="$I/sh home"
ins install
t other-home-exits-0 rcis 0
t other-home-is-passed-on grep -qF "<string>$I/sh home</string>" "$RUNP"
t other-home-keeps-the-log-there grep -qF "<string>$I/sh home/log/run.err</string>" "$RUNP"
t other-home-makes-the-log-folder test -d "$I/sh home/log"
fresh; export SUIT_HOME=$HOME/.suit
ins install
t default-home-spelled-out-passes-nothing sh -c '! grep -q SUIT_HOME "$1"' x "$HOME/Library/LaunchAgents/app.zeitforge.suit.run.plist"
unset SUIT_HOME
# suit-run must be beside suit, and executable
fresh; mkdir -p "$I/solo"; cp "$SUIT" "$I/solo/suit"
ins_solo() { "$I/solo/suit" "$@" >"$T/iout" 2>"$T/ierr"; irc=$?; }
ins_solo install
t no-suit-run-exits-1 rcis 1
t no-suit-run-says-so errhas "cannot use suit-run, which sits beside suit, ($I/solo/suit-run)"
t no-suit-run-writes-nothing test ! -e "$HOME/Library"
mkdir "$I/solo/suit-run"; ins_solo install
t suit-run-a-folder-refused errhas "is not an executable file"
rmdir "$I/solo/suit-run"; : > "$I/solo/suit-run"; ins_solo install
t suit-run-not-executable-refused errhas "is not an executable file"
t suit-run-refused-calls-no-loader callsare ""
ins_solo uninstall
t uninstall-needs-no-suit-run outhas "not installed"
# a program path with a newline in it cannot be written into a file
fresh; mkdir -p "$I/nl
dir"; cp "$SUIT" "$I/nl
dir/suit"; cp "$(dirname "$SUIT")/suit-run" "$I/nl
dir/suit-run"
"$I/nl
dir/suit" install >"$T/iout" 2>"$T/ierr"; irc=$?
t newline-in-path-refused rcis 1
t newline-in-path-says-so errhas "holds a control character"
# the usage
ins install --bogus
t install-extra-argument-is-usage rcis 2
ins uninstall now
t uninstall-extra-argument-is-usage rcis 2
ins status --bogus
t status-bogus-option-is-usage rcis 2
ins status --line extra
t status-line-with-more-is-usage rcis 2
ins install --print extra
t install-print-with-more-is-usage rcis 2

# -- Linux: systemd user units
export SUIT_PLATFORM=linux
fresh; UD=$HOME/.config/systemd/user
ins install
t linux-install-exits-0 rcis 0
t linux-install-says-run outhas "run: installed"
t linux-install-says-tend outhas "tend: installed"
t linux-install-reloads-then-enables-both callsare "--user daemon-reload${NL}--user enable --now suit-run.timer${NL}--user enable --now suit-tend.timer"
for f in suit-run.service suit-run.timer suit-tend.service suit-tend.timer; do t "linux-install-writes-$f" modeis "$UD/$f" -rw-r--r--; done
t linux-run-service-starts-suit-run grep -qxF "ExecStart=\"$(dirname "$SUIT")/suit-run\"" "$UD/suit-run.service"
t linux-tend-service-starts-suit-tend grep -qxF "ExecStart=\"$SUIT\" tend" "$UD/suit-tend.service"
t linux-services-are-oneshot grep -qxF "Type=oneshot" "$UD/suit-run.service"
t linux-run-timer-every-60 grep -qxF "OnUnitActiveSec=60s" "$UD/suit-run.timer"
t linux-run-timer-boot-60 grep -qxF "OnBootSec=60s" "$UD/suit-run.timer"
t linux-run-timer-accuracy grep -qxF "AccuracySec=1s" "$UD/suit-run.timer"
t linux-tend-timer-every-3600 grep -qxF "OnUnitActiveSec=3600s" "$UD/suit-tend.timer"
t linux-tend-timer-persistent grep -qxF "Persistent=true" "$UD/suit-tend.timer"
t linux-timers-want-timers-target grep -qxF "WantedBy=timers.target" "$UD/suit-tend.timer"
t linux-install-makes-no-log-folder test ! -e "$HOME/.suit"
t linux-default-home-passes-nothing sh -c '! grep -q SUIT_HOME "$1"' x "$UD/suit-run.service"
: > "$I/calls"; before=$(snapshot)
ins install
t linux-install-twice-says-already outhas "run: already installed"
t linux-install-twice-calls-no-loader callsare ""
t linux-install-twice-writes-nothing test "$before" = "$(snapshot)"
echo '# by hand' >> "$UD/suit-tend.timer"
ins install
t linux-install-after-edit-says-updated outhas "tend: updated"
t linux-install-after-edit-reloads callsare "--user daemon-reload${NL}--user enable --now suit-run.timer${NL}--user enable --now suit-tend.timer"
t linux-install-after-edit-restores test "$(tail -1 "$UD/suit-tend.timer")" = "WantedBy=timers.target"
: > "$I/calls"; before=$(snapshot)
ins install --print
t linux-print-names-all-four test "$(grep -c '^# ' "$T/iout")" = 4
t linux-print-changes-nothing test "$before" = "$(snapshot)"
ins uninstall
t linux-uninstall-disables-both callsare "--user disable --now suit-run.timer${NL}--user disable --now suit-tend.timer"
t linux-uninstall-removes-four test "$(grep -c '^removed ' "$T/iout")" = 4
t linux-uninstall-leaves-the-folder test -d "$UD"
fresh; echo 4 > "$I/status"
ins install
t linux-reload-failure-exits-3 rcis 3
t linux-reload-failure-says-the-status errhas "--user daemon-reload exited with status 4"
t linux-reload-failure-stops-there callsare "--user daemon-reload"
t linux-reload-failure-leaves-the-files test -f "$HOME/.config/systemd/user/suit-run.timer"
fresh; export XDG_CONFIG_HOME=$I/xdg
ins install
t linux-xdg-config-home-is-used test -f "$I/xdg/systemd/user/suit-run.timer"
t linux-xdg-leaves-home-alone test ! -e "$HOME/.config"
export SUIT_HOME=$I/xsh
ins install
t linux-other-home-is-passed-on grep -qxF "Environment=\"SUIT_HOME=$I/xsh\"" "$I/xdg/systemd/user/suit-run.service"
unset SUIT_HOME XDG_CONFIG_HOME
env -u HOME "$SUIT" install >"$T/iout" 2>"$T/ierr"; irc=$?
t linux-no-home-exits-1 rcis 1
t linux-no-home-says-so errhas "suit: HOME is not set"
env -u HOME XDG_CONFIG_HOME="$I/xdg" "$SUIT" install >"$T/iout" 2>"$T/ierr"; irc=$?
t linux-xdg-without-home-needs-a-suit-home errhas "neither SUIT_HOME nor HOME is set"
env -u HOME XDG_CONFIG_HOME="$I/xdg" SUIT_HOME="$I/xsh" "$SUIT" install --print >"$T/iout" 2>"$T/ierr"; irc=$?
t linux-xdg-and-suit-home-need-no-home rcis 0
t linux-xdg-and-suit-home-pass-the-home-on grep -qxF "Environment=\"SUIT_HOME=$I/xsh\"" "$T/iout"
LONG=/$(awk 'BEGIN { for (i = 0; i < 1100; i++) printf "a" }')
HOME=$LONG "$SUIT" install >"$T/iout" 2>"$T/ierr"; irc=$?
t long-home-refused errhas "HOME is longer than 1024 bytes"
XDG_CONFIG_HOME=$LONG "$SUIT" install >"$T/iout" 2>"$T/ierr"; irc=$?
t long-xdg-refused errhas "XDG_CONFIG_HOME is longer than 1024 bytes"
XDG_CONFIG_HOME=$I/xdg HOME=$LONG "$SUIT" install >"$T/iout" 2>"$T/ierr"; irc=$?
t long-home-refused-for-the-suit-home errhas "HOME is longer than 1024 bytes"
SUIT_HOME=$LONG "$SUIT" install >"$T/iout" 2>"$T/ierr"; irc=$?
t long-suit-home-refused errhas "SUIT_HOME is longer than 1024 bytes"
HOME= "$SUIT" install >"$T/iout" 2>"$T/ierr"; irc=$?
t empty-home-counts-as-unset errhas "HOME is not set"
env -u HOME "$SUIT" uninstall >"$T/iout" 2>"$T/ierr"; irc=$?
t uninstall-without-home-exits-1 rcis 1
t refused-installs-wrote-nothing test ! -e "$LONG"

# -- status --line
export SUIT_PLATFORM=macos
fresh
ins status --line
t line-not-installed-exits-0 rcis 0
t line-not-installed-says-so test "$(cat "$T/iout")" = "suit: not installed"
ins install
ins status --line
t line-ok test "$(cat "$T/iout")" = "suit ok"
t line-ok-is-silent-on-stderr test ! -s "$T/ierr"
mkdir -p "$HOME/.suit"; printf 'check mine: lint\n  a detail\n\nsync mine\n  another\n' > "$HOME/.suit/attention"
ins status --line
t line-counts-the-items test "$(cat "$T/iout")" = "suit: 2 need you"
t line-is-one-line test "$(wc -l < "$T/iout" | tr -d ' ')" = 1
t line-is-short test "$(wc -c < "$T/iout" | tr -d ' ')" -le 61
t line-has-no-trailing-space sh -c '! grep -q " $" "$1"' x "$T/iout"
ins uninstall
ins status --line
t line-attention-wins-over-not-installed test "$(cat "$T/iout")" = "suit: 2 need you"
printf 'only mine\n' > "$HOME/.suit/attention"
ins status --line
t line-one-item test "$(cat "$T/iout")" = "suit: 1 need you"
printf 'no newline' > "$HOME/.suit/attention"
ins status --line
t line-last-item-without-a-newline test "$(cat "$T/iout")" = "suit: 1 need you"
printf 'need claude statusline: run suit need claude statusline\nlint mine\n  a detail\nneed codex bare: run suit need codex bare\n' > "$HOME/.suit/attention"
ins status --line
t line-counts-need-items-with-the-others test "$(cat "$T/iout")" = "suit: 3 need you"
t line-counts-need-items-silently test ! -s "$T/ierr"
rm "$HOME/.suit/attention"
ins install; rm "$HOME/Library/LaunchAgents/app.zeitforge.suit.tend.plist"
ins status --line
t line-one-file-missing-is-not-installed test "$(cat "$T/iout")" = "suit: not installed"
mkdir "$HOME/.suit/attention"
ins status --line
t line-unreadable-attention-exits-1 rcis 1
t line-unreadable-attention-says-so errhas "cannot read"
rmdir "$HOME/.suit/attention"; head -c 131073 /dev/zero | tr '\0' a > "$HOME/.suit/attention"
ins status --line
t line-oversize-attention-exits-1 rcis 1
t line-oversize-attention-says-so errhas "is over"
rm "$HOME/.suit/attention"
env -u HOME -u SUIT_HOME "$SUIT" status --line >"$T/iout" 2>"$T/ierr"; irc=$?
t line-no-home-exits-1 rcis 1
env -u HOME SUIT_HOME="$I/sh" "$SUIT" status --line >"$T/iout" 2>"$T/ierr"; irc=$?
t line-no-home-for-the-timers-exits-1 rcis 1
t line-no-home-for-the-timers-says-so errhas "HOME is not set"

# -- every failure on the way leaves the old state or a reported partial one
fx() { fresh; PL=$HOME/Library/LaunchAgents; fcase "$@"; }
fxi() { fresh; PL=$HOME/Library/LaunchAgents; "$SUIT" install >/dev/null 2>&1; : > "$I/calls"; fcase "$@"; }
nofiles() { [ ! -e "$PL/app.zeitforge.suit.run.plist" ] && [ ! -e "$PL/app.zeitforge.suit.tend.plist" ]; }
notemp() { [ "$(ls -A "$PL" 2>/dev/null | grep -c '^\.suit-tmp')" = 0 ]; }
fx fault-install-mkdir mkdir:1 1 "cannot create the folder" -- "$SUIT" install
t fault-install-mkdir-leaves-nothing nofiles
fx fault-install-open-existing open:1:EACCES 1 "cannot open" -- "$SUIT" install
fxi fault-install-read-existing read:1 1 "cannot read" -- "$SUIT" install
fxi fault-install-read-interrupted read:1:EINTR 0 "" -- "$SUIT" install
t fault-install-read-interrupted-still-reads grep -qF "run: already installed" "$T/fout"
fx fault-install-write-open open:3 1 "cannot write" -- "$SUIT" install
t fault-install-write-open-leaves-nothing nofiles
t fault-install-write-open-loads-nothing callsare ""
fx fault-install-write write:1 1 "nothing was loaded" -- "$SUIT" install
t fault-install-write-leaves-nothing nofiles
t fault-install-write-leaves-no-temp notemp
fx fault-install-fsync fsync:1 1 "cannot write" -- "$SUIT" install
t fault-install-fsync-leaves-no-temp notemp
fx fault-install-rename rename:1 1 "cannot write" -- "$SUIT" install
t fault-install-rename-leaves-nothing nofiles
fx fault-install-second-file rename:2 1 "cannot write" -- "$SUIT" install
t fault-install-second-file-keeps-the-first test -f "$PL/app.zeitforge.suit.run.plist"
t fault-install-second-file-has-no-second test ! -e "$PL/app.zeitforge.suit.tend.plist"
t fault-install-second-file-loads-nothing callsare ""
t fault-install-second-file-leaves-no-temp notemp
ins install
t install-after-a-partial-says-already-for-the-first outhas "run: already installed"
t install-after-a-partial-finishes-the-second outhas "tend: installed"
t install-after-a-partial-loads-both callsare "bootout gui/$UIDN/app.zeitforge.suit.run${NL}bootstrap gui/$UIDN $PL/app.zeitforge.suit.run.plist${NL}bootstrap gui/$UIDN $PL/app.zeitforge.suit.tend.plist"
fx fault-install-spawn spawn:1 3 "cannot run $SUIT_LOADER" -- "$SUIT" install
t fault-install-spawn-leaves-the-files test -f "$PL/app.zeitforge.suit.run.plist"
fx fault-install-wait wait4:1 3 "cannot wait for" -- "$SUIT" install
fx fault-install-wait-interrupted wait4:1:EINTR 0 "" -- "$SUIT" install
t fault-install-wait-interrupted-still-loads test "$(wc -l < "$I/calls" | tr -d ' ')" = 2
fx fault-install-stat-suit stat:1 1 "cannot use suit" -- "$SUIT" install
fx fault-install-stat-suit-run stat:2 1 "cannot use suit-run" -- "$SUIT" install
fx fault-install-self-path self_path:1 1 "cannot find the path of this program" -- "$SUIT" install
fx fault-print-write write:1 1 "cannot write the files" -- "$SUIT" install --print
fxi fault-uninstall-unlink unlink:1 1 "cannot remove" -- "$SUIT" uninstall
t fault-uninstall-unlink-still-removes-the-other test ! -e "$PL/app.zeitforge.suit.tend.plist"
fxi fault-uninstall-lstat lstat:1:EACCES 1 "cannot look at" -- "$SUIT" uninstall
t fault-uninstall-lstat-calls-no-loader callsare ""
fxi fault-uninstall-spawn spawn:1 0 "cannot run $SUIT_LOADER" -- "$SUIT" uninstall
t fault-uninstall-spawn-still-removes nofiles
fxi fault-uninstall-wait wait4:1 0 "cannot wait for" -- "$SUIT" uninstall
t fault-uninstall-wait-still-removes nofiles
fxi fault-line-lstat lstat:1:EACCES 1 "cannot look at" -- "$SUIT" status --line
fxi fault-line-attention-open open:1:EACCES 1 "cannot open" -- "$SUIT" status --line
# folders and files the person cannot read (not as root, who can read anything)
if [ "$(id -u)" != 0 ]; then
    fresh; PL=$HOME/Library/LaunchAgents; "$SUIT" install >/dev/null 2>&1
    chmod 000 "$PL/app.zeitforge.suit.run.plist"
    ins install
    t unreadable-file-install-exits-1 rcis 1
    t unreadable-file-install-says-so errhas "cannot open"
    chmod 644 "$PL/app.zeitforge.suit.run.plist"
fi

# -- plain status says whether the timers are installed
fresh; mkdir -p "$I/sh/wardrobes"; cp "$ROOT/test/fixtures/wear.fossil" "$I/sh/wardrobes/mine.fossil"
export SUIT_HOME=$I/sh
HAD_USER=${USER+yes}; OLDUSER=${USER-}; export USER=tester
"$SUIT" store open mine >/dev/null 2>&1
PL=$HOME/Library/LaunchAgents
ins status
t status-succeeds rcis 0
t status-says-timers-not-installed outhas "timers: not installed"
ins install
ins status
t status-says-timers-installed outhas "timers: installed"
echo '<!-- by hand -->' >> "$PL/app.zeitforge.suit.run.plist"
ins status
t status-says-timers-differ outhas "timers: differ from this suit (run suit install)"
ins install
mkdir -p "$I/solo"; cp "$SUIT" "$I/solo/suit"
"$I/solo/suit" status >"$T/iout" 2>"$T/ierr"; irc=$?
t status-without-suit-run-says-differ outhas "timers: differ from this suit (run suit install)"
t status-without-suit-run-says-why errhas "cannot use suit-run"
rm "$PL/app.zeitforge.suit.tend.plist"
ins status
t status-with-one-file-missing-says-differ outhas "timers: differ from this suit (run suit install)"
SUIT_PLATFORM=linux XDG_CONFIG_HOME=$LONG "$SUIT" status >"$T/iout" 2>"$T/ierr"; irc=$?
t status-with-an-unusable-folder-exits-1 rcis 1
t status-with-an-unusable-folder-says-so errhas "XDG_CONFIG_HOME is longer than 1024 bytes"
if [ "$(id -u)" != 0 ]; then
    chmod 000 "$PL/app.zeitforge.suit.run.plist"
    ins status
    t status-unreadable-file-exits-1 rcis 1
    t status-unreadable-file-says-so errhas "cannot open"
    chmod 644 "$PL/app.zeitforge.suit.run.plist"
    chmod 000 "$PL"
    ins status
    t status-unsearchable-folder-exits-1 rcis 1
    t status-unsearchable-folder-says-so errhas "cannot look at"
    chmod 755 "$PL"
fi
ins uninstall

# -- a failed load leaves an item, and install again retries it
export SUIT_PLATFORM=macos
AT=$I/home/.suit/attention
ITEM="timers load: written but not loaded (loader.sh exit 7)"
fresh; PL=$HOME/Library/LaunchAgents; echo 7 > "$I/status"
ins install
t retry-first-failure-exits-3 rcis 3
t retry-first-failure-writes-the-item test "$(cat "$AT")" = "$ITEM"
ins status --line
t retry-status-line-counts-it test "$(cat "$T/iout")" = "suit: 1 need you"
: > "$I/calls"; ins install
t retry-still-failing-exits-3 rcis 3
t retry-still-failing-keeps-one-item test "$(cat "$AT")" = "$ITEM"
t retry-still-failing-asks-the-loader-again test -s "$I/calls"
echo 9 > "$I/status"; ins install
t retry-item-follows-the-new-status test "$(cat "$AT")" = "timers load: written but not loaded (loader.sh exit 9)"
echo 0 > "$I/status"; : > "$I/calls"; ins install
t retry-working-loader-exits-0 rcis 0
t retry-working-loader-loads callsare "bootout gui/$UIDN/app.zeitforge.suit.run${NL}bootstrap gui/$UIDN $PL/app.zeitforge.suit.run.plist${NL}bootout gui/$UIDN/app.zeitforge.suit.tend${NL}bootstrap gui/$UIDN $PL/app.zeitforge.suit.tend.plist"
t retry-working-loader-removes-the-item test ! -e "$AT"
t retry-working-loader-says-installed sh -c 'grep -qxF "run: installed" "$1" && grep -qxF "tend: installed" "$1"' x "$T/iout"
t retry-says-not-already-installed sh -c '! grep -q already "$1"' x "$T/iout"
: > "$I/calls"; ins install
t retry-after-success-says-already outhas "run: already installed"
t retry-after-success-asks-nothing callsare ""
# plain status shows the item under needs you
fresh; PL=$HOME/Library/LaunchAgents; mkdir -p "$I/sh/wardrobes"; cp "$ROOT/test/fixtures/wear.fossil" "$I/sh/wardrobes/mine.fossil"
export SUIT_HOME=$I/sh; "$SUIT" store open mine >/dev/null 2>&1; echo 7 > "$I/status"; ins install
ins status
t retry-status-shows-the-item-under-needs-you sh -c 'grep -qxF "needs you:" "$1" && grep -qxF "$2" "$1"' x "$T/iout" "$ITEM"
unset SUIT_HOME
# an item that is the last line and has no newline is found
fresh; PL=$HOME/Library/LaunchAgents; echo 7 > "$I/status"; ins install
printf 'check mine: lint\n\n%s' "$ITEM" > "$AT"; echo 0 > "$I/status"
ins install
t retry-finds-an-item-without-a-newline rcis 0
t retry-without-a-newline-keeps-the-lint-item test "$(cat "$AT")" = "check mine: lint"
# another item is left alone, both ways
fresh; PL=$HOME/Library/LaunchAgents; mkdir -p "$HOME/.suit"; printf 'check mine: lint\n  a detail\n' > "$HOME/.suit/attention"; echo 7 > "$I/status"
ins install
t retry-keeps-the-lint-item sh -c 'grep -qxF "check mine: lint" "$1" && grep -qxF "  a detail" "$1" && grep -qxF "$2" "$1"' x "$AT" "$ITEM"
ins status --line
t retry-two-items-are-counted test "$(cat "$T/iout")" = "suit: 2 need you"
echo 0 > "$I/status"; ins install
t retry-success-keeps-the-lint-item test "$(cat "$AT")" = "check mine: lint${NL}  a detail"
t retry-success-after-lint-exits-0 rcis 0
ins uninstall
t retry-uninstall-keeps-the-lint-item test "$(cat "$AT")" = "check mine: lint${NL}  a detail"
# a plain successful install removes the item and uninstall removes it too
fresh; PL=$HOME/Library/LaunchAgents; echo 7 > "$I/status"; ins install
echo 0 > "$I/status"; rm "$PL/app.zeitforge.suit.tend.plist"; ins install
t retry-rewrite-removes-the-item test ! -e "$AT"
fresh; PL=$HOME/Library/LaunchAgents; echo 7 > "$I/status"; ins install
ins uninstall
t retry-uninstall-removes-the-item test ! -e "$AT"
t retry-uninstall-exits-0 rcis 0
mkdir -p "$HOME/.suit"; printf '%s\n' "$ITEM" > "$AT"
ins uninstall
t retry-uninstall-when-not-installed-removes-the-item test ! -e "$AT"
# a loader that cannot be started
fresh; PL=$HOME/Library/LaunchAgents
SUIT_LOADER=$T/no-such-loader "$SUIT" install >"$T/iout" 2>"$T/ierr"; irc=$?
t retry-no-loader-exits-3 rcis 3
t retry-no-loader-writes-the-item test "$(cat "$AT")" = "timers load: written but not loaded (no-such-loader could not run)"
# the linux loader
export SUIT_PLATFORM=linux
fresh; echo 3 > "$I/status"
ins install
t retry-linux-failure-exits-3 rcis 3
t retry-linux-failure-writes-the-item test "$(cat "$AT")" = "timers load: written but not loaded (loader.sh exit 3)"
echo 0 > "$I/status"; ins install
t retry-linux-working-loader-exits-0 rcis 0
t retry-linux-working-loader-removes-the-item test ! -e "$AT"
export SUIT_PLATFORM=macos
# every failure branch
PL=$HOME/Library/LaunchAgents
fxf() { fresh; PL=$HOME/Library/LaunchAgents; echo 7 > "$I/status"; fcase "$@"; }
fxp() { fresh; PL=$HOME/Library/LaunchAgents; echo 7 > "$I/status"; "$SUIT" install >/dev/null 2>&1; echo 0 > "$I/status"; : > "$I/calls"; fcase "$@"; }
fxf fault-retry-item-write-keeps-the-load-failure rename:3 3 "cannot write $AT" -- "$SUIT" install
t fault-retry-item-write-also-says-the-load-failure grep -qF "exited with status 7" "$T/ferr"
t fault-retry-item-write-leaves-no-item test ! -e "$AT"
export SUIT_PLATFORM=linux
fresh; echo 7 > "$I/status"
NSL=$(printf %s "$HOME" | tr -cd / | wc -c | tr -d ' ')
fcase fault-retry-item-folder-keeps-the-load-failure mkdir:$((NSL + 4)) 3 "cannot create $HOME/.suit" -- "$SUIT" install
t fault-retry-item-folder-also-says-the-load-failure grep -qF "exited with status 7" "$T/ferr"
export SUIT_PLATFORM=macos
fxf fault-retry-item-open-keeps-the-load-failure open:5:EACCES 3 "cannot open $AT" -- "$SUIT" install
t fault-retry-item-open-also-says-the-load-failure grep -qF "exited with status 7" "$T/ferr"
fxp fault-retry-has-open open:3:EACCES 1 "cannot open $AT" -- "$SUIT" install
t fault-retry-has-open-loads-nothing callsare ""
fxp fault-retry-has-read read:7 1 "cannot read $AT" -- "$SUIT" install
fxp fault-retry-remove-unlink unlink:1 1 "cannot remove $AT" -- "$SUIT" install
t fault-retry-remove-unlink-did-load test -s "$I/calls"
fxp fault-retry-remove-open open:4:EACCES 1 "cannot open $AT" -- "$SUIT" install
fresh; PL=$HOME/Library/LaunchAgents; echo 7 > "$I/status"; "$SUIT" install >/dev/null 2>&1; echo 0 > "$I/status"
printf 'check mine: lint\n' >> "$AT"
fcase fault-retry-remove-rename rename:1 1 "cannot write $AT" -- "$SUIT" install
fxp fault-retry-uninstall-unlink unlink:1 1 "cannot remove $AT" -- "$SUIT" uninstall
t fault-retry-uninstall-unlink-still-removes-the-timers nofiles
fresh; PL=$HOME/Library/LaunchAgents; mkdir -p "$HOME/.suit"; printf '%s\n' "$ITEM" > "$AT"
fcase fault-retry-uninstall-not-installed-unlink unlink:1 1 "cannot remove $AT" -- "$SUIT" uninstall

if [ -n "$HAD_USER" ]; then export USER=$OLDUSER; else unset USER; fi
export HOME=$OLDHOME
unset SUIT_HOME SUIT_PLATFORM SUIT_LOADER XDG_CONFIG_HOME
}

# a build without the test hooks would run the real loader: leave it alone
if strings -a "$SUIT" | grep -q SUIT_LOADER; then inst_tests; else pass install-tests-skipped-without-the-test-hooks; fi

# ---- hooks: suit-run hook EVENT, suit hook EVENT, suit hooks ----------------------

hook_tests() {
SR=${SUIT%/*}/suit-run
HK=$T/hook
HH=$HK/home
SL=$HH/slots/hook
HK_OLDTMP=${TMPDIR-}
export HOOKLOG=$HK/log TMPDIR=$HK/tmp SUIT_HOME=$HH
HIN=$T/hook-in
mkdir -p "$HIN"
printf 'a\0b\0\0\377\n' > "$HIN/nul"
head -c 1048576 /dev/urandom > "$HIN/1m"
printf 'hello there\n' > "$HIN/text"
: > "$HIN/empty"
CK0=4294967295:0
PLATFORM_TRUE=/usr/bin/true

hk_fresh() {
    rm -rf "$HK"
    mkdir -p "$SL" "$HK/progs" "$HK/tmp"
    : > "$HOOKLOG"
}
# NAME STATUS: a program that logs its name, argument, event and input checksum
hk_prog() {
    {
        cat <<'X'
#!/bin/sh
printf '%s %s ev=%s in=%s\n' "${0##*/}" "$1" "$SUIT_HOOK_EVENT" "$(cksum | tr ' ' :)" >> "$HOOKLOG"
X
        echo "exit $2"
    } > "$HK/progs/$1"
    chmod +x "$HK/progs/$1"
}
# EVENT NAME PROG: $SL/EVENT/NAME is a link to progs/PROG
hk_link() { mkdir -p "$SL/$1"; ln -s "$HK/progs/$3" "$SL/$1/$2"; }
# the log line a program writes: NAME EVENT CHECKSUM
ex() { printf '%s %s ev=%s in=%s\n' "$1" "$2" "$2" "$3"; }
ck() { cksum < "$1" | tr ' ' :; }
# run the dispatcher with the caller's standard input; status in hrc
hk_run() { "$SR" hook "$@" > "$HK/out" 2> "$HK/err"; hrc=$?; }
# NAME RC LOG
hk_expect() {
    if [ "$hrc" != "$2" ]; then bad "$1" "exit $hrc, want $2: $(cat "$HK/err")"
    elif [ "$(cat "$HOOKLOG")" != "$3" ]; then bad "$1" "log: $(cat "$HOOKLOG") $(cat "$HK/err" "$T/ferr" 2>/dev/null)"
    else pass "$1"; fi
}
# NAME FILE TEXT: FILE contains TEXT
hk_has() { if grep -qF -- "$3" "$2"; then pass "$1"; else bad "$1" "no '$3' in: $(cat "$2")"; fi; }
# NAME: no spool file is left in the home folder or the temporary folder
hk_nospool() {
    if [ -z "$(ls -A "$HK/tmp")" ] && ! ls -A "$HH" | grep -q '^\.suit-tmp'; then pass "$1"
    else bad "$1" "$(ls -A "$HK/tmp" "$HH")"; fi
}
# NAME: the dispatcher printed nothing
hk_silent() { if [ ! -s "$HK/out" ] && [ ! -s "$HK/err" ]; then pass "$1"; else bad "$1" "$(cat "$HK/out" "$HK/err")"; fi; }

# the same cases for suit-run hook and suit hook: P is the program, N the prefix
hk_basics() {
    SR=$1; N=$2
    hk_fresh; hk_prog a 0; ln -s "$HK/progs/a" "$SL/Stop"
    hk_run Stop < "$HIN/text"
    hk_expect "$N-one-program-by-a-direct-link" 0 "$(ex Stop Stop "$(ck "$HIN/text")")"
    hk_silent "$N-one-program-adds-no-output"
    hk_fresh; { echo '#!/bin/sh'; echo 'echo "$0 $1 $#"'; } > "$HK/progs/argv"; chmod +x "$HK/progs/argv"
    cp "$HK/progs/argv" "$SL/Stop"
    hk_run Stop < "$HIN/empty"
    if [ "$(cat "$HK/out")" = "$SL/Stop Stop 1" ]; then pass "$N-a-file-is-run-with-its-path-and-the-event"; else bad "$N-a-file-is-run-with-its-path-and-the-event" "$(cat "$HK/out")"; fi
    hk_fresh; hk_prog a 0; hk_prog b 0; hk_prog c 0
    hk_link Stop b b; hk_link Stop a a; hk_link Stop c c; ln -s "$HK/progs/a" "$SL/Stop/.hidden"
    hk_run Stop < "$HIN/nul"
    k=$(ck "$HIN/nul")
    hk_expect "$N-a-folder-runs-in-name-order-and-skips-dot-files" 0 "$(ex a Stop "$k")
$(ex b Stop "$k")
$(ex c Stop "$k")"
    hk_fresh; hk_prog a 0; hk_prog b 2; hk_prog c 0
    hk_link Stop a a; hk_link Stop b b; hk_link Stop c c
    hk_run Stop < "$HIN/empty"
    hk_expect "$N-exit-2-stops-the-rest" 2 "$(ex a Stop $CK0)
$(ex b Stop $CK0)"
    hk_fresh; hk_prog a 0; hk_prog b 3; hk_prog c 5
    hk_link Stop a a; hk_link Stop b b; hk_link Stop c c
    hk_run Stop < "$HIN/empty"
    hk_expect "$N-first-non-zero-is-the-status-and-all-run" 3 "$(ex a Stop $CK0)
$(ex b Stop $CK0)
$(ex c Stop $CK0)"
    hk_fresh
    for i in a b; do
        { echo '#!/bin/sh'; echo "echo out-$i"; echo "echo err-$i >&2"; } > "$HK/progs/$i"; chmod +x "$HK/progs/$i"
        hk_link Stop $i $i
    done
    hk_run Stop < "$HIN/empty"
    if [ "$hrc" = 0 ] && [ "$(cat "$HK/out")" = "out-a
out-b" ] && [ "$(cat "$HK/err")" = "err-a
err-b" ]; then pass "$N-program-output-is-passed-through-in-order"; else bad "$N-program-output-is-passed-through-in-order" "$hrc $(cat "$HK/out" "$HK/err")"; fi
    hk_fresh; hk_prog a 0
    hk_run Nothing < "$HIN/text"
    if [ "$hrc" = 0 ]; then pass "$N-absent-event-exits-0"; else bad "$N-absent-event-exits-0" "$hrc"; fi
    hk_silent "$N-absent-event-prints-nothing"
}
hk_basics "$SR" suit-run
hk_basics "$SUIT" suit-hook
SR=${SUIT%/*}/suit-run

# -- the event name
hk_fresh
for e in A.b_c-1 "$(head -c 64 /dev/zero | tr '\0' x)"; do
    hk_run "$e" < "$HIN/text"
    if [ "$hrc" = 0 ]; then pass "event-name-ok-[$e]"; else bad "event-name-ok-[$e]" "$hrc $(cat "$HK/err")"; fi
done
long=$(head -c 65 /dev/zero | tr '\0' x)
for e in '' "$long" a/b . .. .hid 'a b' 'x*' 'a:b'; do
    hk_run "$e" < "$HIN/text"
    if [ "$hrc" = 64 ] && grep -qF "suit: hook: the event is 1 to 64" "$HK/err"; then pass "event-name-refused-[$e]"; else bad "event-name-refused-[$e]" "$hrc $(cat "$HK/err")"; fi
done
"$SR" hook > "$HK/out" 2> "$HK/err" < "$HIN/text"; hrc=$?
if [ "$hrc" = 64 ] && grep -qF "usage: suit-run hook EVENT" "$HK/err"; then pass hook-without-event-is-a-usage-error; else bad hook-without-event-is-a-usage-error "$hrc"; fi
"$SR" hook a b > "$HK/out" 2> "$HK/err" < "$HIN/text"; hrc=$?
if [ "$hrc" = 64 ]; then pass hook-with-two-words-is-a-usage-error; else bad hook-with-two-words-is-a-usage-error "$hrc"; fi
"$SR" bogus > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 11 ]; then pass other-words-still-reach-the-no-change-run; else bad other-words-still-reach-the-no-change-run "$hrc"; fi
"$SUIT" hook > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 2 ] && grep -qF usage "$HK/err"; then pass suit-hook-needs-an-event; else bad suit-hook-needs-an-event "$hrc"; fi
"$SUIT" hooks extra > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 2 ] && grep -qF usage "$HK/err"; then pass suit-hooks-takes-no-arguments; else bad suit-hooks-takes-no-arguments "$hrc"; fi

# -- an absent event reads nothing
hk_fresh
printf 'keep me' > "$HK/in"
{ "$SR" hook Stop > "$HK/out" 2> "$HK/err"; hrc=$?; cat > "$HK/rest"; } < "$HK/in"
if [ "$hrc" = 0 ] && [ "$(cat "$HK/rest")" = "keep me" ]; then pass absent-event-leaves-standard-input-unread; else bad absent-event-leaves-standard-input-unread "$hrc $(cat "$HK/rest")"; fi
hk_silent absent-event-prints-nothing
rm -rf "$HH/slots"; mkdir -p "$HH"; : > "$HH/slots"
hk_run Stop < "$HIN/text"
if [ "$hrc" = 0 ]; then pass slots-that-is-a-file-is-absent; else bad slots-that-is-a-file-is-absent "$hrc"; fi
rm -rf "$HH"
hk_run Stop < "$HIN/text"
if [ "$hrc" = 0 ]; then pass no-home-folder-is-absent; else bad no-home-folder-is-absent "$hrc"; fi
hk_fresh; mkdir -p "$SL/Stop"; printf 'keep me' > "$HK/in"
{ "$SR" hook Stop > "$HK/out" 2> "$HK/err"; hrc=$?; cat > "$HK/rest"; } < "$HK/in"
if [ "$hrc" = 0 ] && [ "$(cat "$HK/rest")" = "keep me" ]; then pass empty-folder-runs-nothing-and-reads-nothing; else bad empty-folder-runs-nothing-and-reads-nothing "$hrc"; fi
hk_fresh; hk_prog a 0; mkdir -p "$HK/folder"; ln -s "$HK/progs/a" "$HK/folder/x"; ln -s "$HK/folder" "$SL/Stop"
hk_run Stop < "$HIN/text"
hk_expect a-link-to-a-folder-is-a-folder 0 "$(ex x Stop "$(ck "$HIN/text")")"

# -- the same bytes reach every program
hk_same() { # NAME FILE: three programs see FILE
    hk_fresh; hk_prog a 0; hk_prog b 0; hk_prog c 0
    hk_link Stop a a; hk_link Stop b b; hk_link Stop c c
    hk_run Stop < "$2"
    k=$(ck "$2")
    hk_expect "$1" 0 "$(ex a Stop "$k")
$(ex b Stop "$k")
$(ex c Stop "$k")"
    hk_nospool "$1-leaves-no-temporary-file"
}
hk_same same-input-empty "$HIN/empty"
hk_same same-input-text "$HIN/text"
hk_same same-input-with-nul-bytes "$HIN/nul"
hk_same same-input-1-mib "$HIN/1m"
hk_fresh; hk_prog a 0; hk_prog b 0; hk_link Stop a a; hk_link Stop b b
cat "$HIN/1m" | "$SR" hook Stop > "$HK/out" 2> "$HK/err"; hrc=$?
k=$(ck "$HIN/1m")
hk_expect same-input-from-a-pipe 0 "$(ex a Stop "$k")
$(ex b Stop "$k")"
: > "$HOOKLOG"; "$SR" hook Stop > "$HK/out" 2> "$HK/err" <&-; hrc=$?
hk_expect closed-standard-input-is-empty-input 0 "$(ex a Stop $CK0)
$(ex b Stop $CK0)"
: > "$HOOKLOG"; "$SR" hook Stop > "$HK/out" 2> "$HK/err" < /dev/null; hrc=$?
hk_expect dev-null-standard-input-is-empty-input 0 "$(ex a Stop $CK0)
$(ex b Stop $CK0)"
: > "$HOOKLOG"
python3 -I - "$SR" > "$HK/out" 2> "$HK/err" <<'PY'
import pty, subprocess, sys
m, s = pty.openpty()
sys.exit(subprocess.run([sys.argv[1], 'hook', 'Stop'], stdin=s, timeout=20).returncode)
PY
hrc=$?
hk_expect terminal-standard-input-is-empty-input 0 "$(ex a Stop $CK0)
$(ex b Stop $CK0)"
# the cap: exactly 16 MiB passes, one more byte is refused and runs nothing
: > "$HOOKLOG"
head -c 16777216 /dev/zero | "$SR" hook Stop > "$HK/out" 2> "$HK/err"; hrc=$?
k=$(head -c 16777216 /dev/zero | cksum | tr ' ' :)
hk_expect input-of-exactly-16-mib-passes 0 "$(ex a Stop "$k")
$(ex b Stop "$k")"
: > "$HOOKLOG"
head -c 16777217 /dev/zero | "$SR" hook Stop > "$HK/out" 2> "$HK/err"; hrc=$?
hk_expect input-over-16-mib-exits-65-and-runs-nothing 65 ""
hk_has input-over-16-mib-names-the-event "$HK/err" "suit: hook Stop: standard input is over 16 MiB"
hk_nospool input-over-16-mib-leaves-no-temporary-file

# a program that writes to its standard input cannot change what the next reads.
# Two writers, because not every echo reports a failed write: a descriptor that
# took writes would let both succeed.
hk_fresh; hk_prog b 0
{ echo '#!/bin/sh'; echo 'if dd if=/dev/zero bs=1 count=1 >&0 2>/dev/null && /bin/echo x >&0 2>/dev/null; then echo wrote > "$HOOKLOG.w"; else echo failed > "$HOOKLOG.w"; fi'; } > "$HK/progs/w"; chmod +x "$HK/progs/w"
hk_link Stop a w; hk_link Stop b b
hk_run Stop < "$HIN/text"
hk_expect a-program-cannot-write-to-its-input-and-the-next-sees-the-same-bytes 0 "$(ex b Stop "$(ck "$HIN/text")")"
if [ "$(cat "$HOOKLOG.w")" = failed ]; then pass a-program-writing-to-its-input-fails; else bad a-program-writing-to-its-input-fails "$(cat "$HOOKLOG.w")"; fi

# -- statuses
hk_fresh; hk_prog a 4; hk_prog b 2; hk_prog c 9
hk_link Stop a a; hk_link Stop b b; hk_link Stop c c
hk_run Stop < "$HIN/empty"
hk_expect exit-2-after-another-failure-exits-2 2 "$(ex a Stop $CK0)
$(ex b Stop $CK0)"
hk_fresh; hk_prog a 4; hk_prog b 0; hk_prog c 2
hk_link Stop a a; hk_link Stop b b; hk_link Stop c c
hk_run Stop < "$HIN/empty"
hk_expect exit-2-from-the-last-wins-over-an-earlier-status 2 "$(ex a Stop $CK0)
$(ex b Stop $CK0)
$(ex c Stop $CK0)"
hk_fresh; hk_prog a 0; hk_prog b 0
hk_link Stop a a; hk_link Stop b b
hk_run Stop < "$HIN/empty"
hk_expect all-zero-exits-0 0 "$(ex a Stop $CK0)
$(ex b Stop $CK0)"
hk_fresh; hk_prog a 126; hk_link Stop a a; hk_prog b 255; hk_link Stop b b
hk_run Stop < "$HIN/empty"
hk_expect status-of-the-first-failing-program-is-kept 126 "$(ex a Stop $CK0)
$(ex b Stop $CK0)"
hk_fresh; { echo '#!/bin/sh'; echo 'kill -TERM $$'; } > "$HK/progs/sig"; chmod +x "$HK/progs/sig"
hk_prog b 0
hk_link Stop a sig; hk_link Stop b b
hk_run Stop < "$HIN/empty"
hk_expect a-program-killed-by-a-signal-is-128-plus-the-signal 143 "$(ex b Stop $CK0)"
hk_fresh; hk_prog a 0; hk_prog z 0
hk_link Stop a a; ln -s "$HK/nowhere" "$SL/Stop/bad"; : > "$HK/progs/plain"; ln -s "$HK/progs/plain" "$SL/Stop/noexec"; hk_link Stop z z
hk_run Stop < "$HIN/empty"
hk_expect a-dangling-link-and-a-file-that-cannot-run-fail-and-the-rest-run 126 "$(ex a Stop $CK0)
$(ex z Stop $CK0)"
hk_has dangling-link-says-so "$HK/err" "suit: hook Stop/bad: cannot run: No such file or directory"
hk_has non-executable-target-says-so "$HK/err" "suit: hook Stop/noexec: cannot run: Permission denied"
hk_fresh; ln -s "$HK/nowhere" "$SL/Stop"
hk_run Stop < "$HIN/empty"
if [ "$hrc" = 126 ] && grep -qF "suit: hook Stop: cannot run: No such file or directory" "$HK/err"; then pass a-single-dangling-link-exits-126; else bad a-single-dangling-link-exits-126 "$hrc $(cat "$HK/err")"; fi
hk_fresh; hk_prog z 0; mkdir -p "$SL/Stop"
for n in $(seq 1 64); do ln -s "$HK/progs/z" "$SL/Stop/p$(printf %02d "$n")"; done
hk_run Stop < "$HIN/empty"
if [ "$hrc" = 0 ] && [ "$(wc -l < "$HOOKLOG" | tr -d ' ')" = 64 ]; then pass sixty-four-programs-run; else bad sixty-four-programs-run "$hrc"; fi
ln -s "$HK/progs/z" "$SL/Stop/p65"
: > "$HOOKLOG"
hk_run Stop < "$HIN/empty"
hk_expect sixty-five-programs-are-an-error 1 ""
hk_has sixty-five-programs-says-so "$HK/err" "suit: hook Stop: more than 64 programs"

# -- suit hooks
hk_fresh; rm -rf "$HH/slots"
"$SUIT" hooks > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 0 ] && [ ! -s "$HK/out" ] && [ ! -s "$HK/err" ]; then pass hooks-lists-nothing-without-a-slots-folder; else bad hooks-lists-nothing-without-a-slots-folder "$hrc"; fi
hk_fresh
"$SUIT" hooks > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 0 ] && [ ! -s "$HK/out" ]; then pass hooks-lists-nothing-when-there-are-none; else bad hooks-lists-nothing-when-there-are-none "$hrc"; fi
hk_prog a 0
hk_link Stop a a; ln -s "$HK/nowhere" "$SL/Stop/dangling"; : > "$HK/progs/plain"; ln -s "$HK/progs/plain" "$SL/Stop/noexec"
ln -s "$HK" "$SL/Stop/dir"; ln -s "$HK/progs/a" "$SL/Stop/.hidden"
ln -s "$HK/progs/a" "$SL/Start"; cp "$HK/progs/a" "$SL/File"
mkdir "$SL/bad event"; ln -s "$HK/progs/a" "$SL/bad event/x"; mkdir "$SL/.dot"
"$SUIT" hooks > "$HK/out" 2> "$HK/err"; hrc=$?
cat > "$HK/want" <<EOF
File - -> $SL/File
Start - -> $HK/progs/a
Stop a -> $HK/progs/a
Stop dangling -> $HK/nowhere (missing)
Stop dir -> $HK (not executable)
Stop noexec -> $HK/progs/plain (not executable)
EOF
if [ "$hrc" = 0 ] && cmp -s "$HK/out" "$HK/want"; then pass hooks-lists-every-program-in-order; else bad hooks-lists-every-program-in-order "$hrc $(cat "$HK/out" "$HK/err")"; fi
if [ ! -s "$HOOKLOG" ]; then pass hooks-runs-nothing; else bad hooks-runs-nothing; fi
mkdir "$SL/Crowd"; for n in $(seq 1 65); do ln -s "$HK/progs/a" "$SL/Crowd/p$n"; done
"$SUIT" hooks > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 1 ] && grep -qF "suit: hook Crowd: more than 64 programs" "$HK/err" && grep -qF "Stop a ->" "$HK/out"; then pass hooks-reports-a-crowded-event-and-lists-the-rest; else bad hooks-reports-a-crowded-event-and-lists-the-rest "$hrc $(cat "$HK/err")"; fi
rm -rf "$SL"; mkdir -p "$SL"; for n in $(seq 1 65); do mkdir "$SL/e$n"; done
"$SUIT" hooks > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 1 ] && grep -qF "more than 64 events" "$HK/err"; then pass hooks-with-too-many-events-is-an-error; else bad hooks-with-too-many-events-is-an-error "$hrc $(cat "$HK/err")"; fi
env -u SUIT_HOME -u HOME "$SUIT" hooks > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 1 ] && grep -qF "neither SUIT_HOME nor HOME is set" "$HK/err"; then pass hooks-needs-a-home; else bad hooks-needs-a-home "$hrc"; fi
env -u SUIT_HOME -u HOME "$SR" hook Stop > "$HK/out" 2> "$HK/err"; hrc=$?
if [ "$hrc" = 1 ] && grep -qF "neither SUIT_HOME nor HOME is set" "$HK/err"; then pass hook-needs-a-home; else bad hook-needs-a-home "$hrc"; fi

# -- every failure branch
hk_fw() {
    hk_fresh; hk_prog a 0; hk_prog b 0; hk_link Stop a a; hk_link Stop b b
    printf 'some input' > "$HK/in"; INCK=$(ck "$HK/in")
}
hkf() { hk_fw; fcase "$@" < "$HK/in"; hrc=$frc; }
hkf fault-hook-stat-of-stdin-is-taken-as-closed fstat:1 0 "" -- "$SR" hook Stop
hk_expect fault-hook-stat-of-stdin-gives-empty-input 0 "$(ex a Stop $CK0)
$(ex b Stop $CK0)"
hkf fault-hook-dev-null-open fstat:1,open:1 1 "suit: hook Stop: cannot open /dev/null: $EIO" -- "$SR" hook Stop
hkf fault-hook-spool-in-home-falls-back-to-tmpdir open:1 0 "" -- "$SR" hook Stop
hk_expect fault-hook-spool-fallback-gives-the-input 0 "$(ex a Stop "$INCK")
$(ex b Stop "$INCK")"
hk_nospool fault-hook-spool-fallback-leaves-no-temporary-file
hkf fault-hook-spool-both-fail open:1,open:2 1 "suit: hook Stop: cannot make a temporary file: $EIO" -- "$SR" hook Stop
hkf fault-hook-spool-both-fail-without-tmpdir open:1,open:2 1 "cannot make a temporary file" -- env -u TMPDIR "$SR" hook Stop
hkf fault-hook-spool-both-fail-with-a-huge-tmpdir open:1,open:2 1 "cannot make a temporary file" -- env TMPDIR="$(head -c 5000 /dev/zero | tr '\0' x)" "$SR" hook Stop
hkf fault-hook-spool-home-lost getenv:2 1 "neither SUIT_HOME nor HOME is set" -- env -u HOME "$SR" hook Stop
hkf fault-hook-spool-reopen-in-home open:2 1 "suit: hook Stop: cannot reopen the temporary file: $EIO" -- "$SR" hook Stop
hk_expect fault-hook-spool-reopen-in-home-runs-nothing 1 ""
hk_nospool fault-hook-spool-reopen-in-home-leaves-no-temporary-file
hkf fault-hook-spool-reopen-in-tmpdir open:1,open:3 1 "suit: hook Stop: cannot reopen the temporary file: $EIO" -- "$SR" hook Stop
hk_expect fault-hook-spool-reopen-in-tmpdir-runs-nothing 1 ""
hk_nospool fault-hook-spool-reopen-in-tmpdir-leaves-no-temporary-file
hkf fault-hook-spool-unlink unlink:1 1 "suit: hook Stop: cannot remove $HH/.suit-tmp.hook." -- "$SR" hook Stop
rm -f "$HH"/.suit-tmp.hook.*
hkf fault-hook-read read:1 1 "suit: hook Stop: cannot read standard input: $EIO" -- "$SR" hook Stop
hk_nospool fault-hook-read-leaves-no-temporary-file
hkf fault-hook-read-interrupted-retries read:1:EINTR 0 "" -- "$SR" hook Stop
hk_expect fault-hook-read-interrupted-gives-the-input 0 "$(ex a Stop "$INCK")
$(ex b Stop "$INCK")"
hkf fault-hook-short-read read:1:short 0 "" -- "$SR" hook Stop
hk_expect fault-hook-short-read-gives-the-input 0 "$(ex a Stop "$INCK")
$(ex b Stop "$INCK")"
hkf fault-hook-write write:1 1 "suit: hook Stop: cannot write the input: $EIO" -- "$SR" hook Stop
hk_nospool fault-hook-write-leaves-no-temporary-file
hkf fault-hook-short-write write:1:short 0 "" -- "$SR" hook Stop
hk_expect fault-hook-short-write-gives-the-input 0 "$(ex a Stop "$INCK")
$(ex b Stop "$INCK")"
hkf fault-hook-dup2 dup2:1 1 "suit: hook Stop: cannot set up input: $EIO" -- "$SR" hook Stop
hkf fault-hook-rewind lseek:1 1 "suit: hook Stop/a: cannot rewind the input: $EIO" -- "$SR" hook Stop
hkf fault-hook-rewind-before-the-second-program lseek:2 1 "cannot rewind the input" -- "$SR" hook Stop
hkf fault-hook-setenv setenv:1 1 "suit: hook Stop: cannot set the environment: $EIO" -- "$SR" hook Stop
hkf fault-hook-spawn spawn:1 126 "suit: hook Stop/a: cannot run: $EIO" -- "$SR" hook Stop
hk_expect fault-hook-spawn-failure-lets-the-rest-run 126 "$(ex b Stop "$INCK")"
# the program that is not waited for may still be running when the next case
# rewrites the scripts, so it is not a script
hk_fw; rm "$HK/progs/a"; ln -s "$PLATFORM_TRUE" "$HK/progs/a"; fcase fault-hook-wait wait4:1 1 "suit: hook Stop/a: cannot wait: $EIO" -- "$SR" hook Stop < "$HK/in"
hkf fault-hook-wait-interrupted-retries wait4:1:EINTR 0 "" -- "$SR" hook Stop
hk_expect fault-hook-wait-interrupted-runs-both 0 "$(ex a Stop "$INCK")
$(ex b Stop "$INCK")"
hkf fault-hook-list-folder listdir:1 1 "suit: hook Stop: cannot read $SL/Stop: $EIO" -- "$SR" hook Stop
hkf fault-hook-look-at-slot lstat:1:EACCES 1 "suit: hook Stop: cannot look at $SL/Stop: Permission denied" -- "$SR" hook Stop
hkf fault-hooks-list-events listdir:1 1 "suit: cannot read $SL: $EIO" -- "$SUIT" hooks
hkf fault-hooks-list-programs listdir:2 1 "suit: hook Stop: cannot read $SL/Stop: $EIO" -- "$SUIT" hooks
hkf fault-hooks-look-at-slot lstat:1:EACCES 1 "suit: hook Stop: cannot look at" -- "$SUIT" hooks
hkf fault-hooks-read-link readlink:1 1 "suit: cannot read the link $SL/Stop/a: $EIO" -- "$SUIT" hooks
hkf fault-hooks-lstat-of-a-program lstat:2 0 "" -- "$SUIT" hooks
hk_has fault-hooks-lstat-of-a-program-lists-the-path "$T/fout" "Stop a -> $SL/Stop/a"
hkf fault-hooks-write write:1 1 "suit: cannot write the list: $EIO" -- "$SUIT" hooks
hkf fault-hooks-write-interrupted-retries write:1:EINTR 0 "" -- "$SUIT" hooks
hkf fault-hook-via-suit-spool-open fstat:1,open:1 1 "cannot open /dev/null" -- "$SUIT" hook Stop
hk_nospool fault-hook-leaves-no-temporary-file-at-the-end
hk_fresh
rm -rf "$HK"
unset HOOKLOG SUIT_HOME
if [ -n "$HK_OLDTMP" ]; then export TMPDIR=$HK_OLDTMP; else unset TMPDIR; fi
}
hook_tests

# ---- suit check with no file: the wardrobes' configs as one set -------------

stack_check_tests() {
    SK=$T/stackcheck
    rm -rf "$SK"; mkdir -p "$SK/store/only"
    cp test/fixtures/example.conf "$SK/store/only/suit.conf"
    out=$(SUIT_HOME=$SK "$SUIT" check 2>"$T/err"); rc=$?
    if [ $rc -eq 0 ] && [ "$out" = "$(cat test/fixtures/example.dump)" ]; then pass check-no-file-one-wardrobe-is-check-file; else bad check-no-file-one-wardrobe-is-check-file "exit $rc $(cat "$T/err")"; fi
    rm -rf "$SK/store/only"; mkdir -p "$SK/store/b" "$SK/store/a"
    printf '[harness h]\nrecord = r\n[outfit o]\ninclude = p\n' > "$SK/store/a/suit.conf"
    printf '[outfit p]\nskills = x\n[wear user]\noutfits = o\n' > "$SK/store/b/suit.conf"
    want='harness h
harness h record = r
outfit o
outfit o include = p
outfit p
outfit p skills = x
wear user
wear user outfits = o'
    out=$(SUIT_HOME=$SK "$SUIT" check 2>"$T/err"); rc=$?
    if [ $rc -eq 0 ] && [ "$out" = "$want" ]; then pass check-no-file-merges-the-wardrobes; else bad check-no-file-merges-the-wardrobes "exit $rc $out $(cat "$T/err")"; fi
    printf '[outfit o]\n' > "$SK/store/b/suit.conf"
    out=$(SUIT_HOME=$SK "$SUIT" check 2>"$T/err"); rc=$?
    if [ $rc -eq 2 ] && [ -z "$out" ] && grep -qF "store/b/suit.conf:1: duplicate section [outfit o]; first at $SK/store/a/suit.conf:3" "$T/err"; then pass check-no-file-reports-the-first-error; else bad check-no-file-reports-the-first-error "exit $rc $(cat "$T/err")"; fi
    rm -rf "$SK/store"
    out=$(SUIT_HOME=$SK "$SUIT" check 2>"$T/err"); rc=$?
    if [ $rc -eq 2 ] && grep -qF "store:0: no wardrobe with a suit.conf" "$T/err"; then pass check-no-file-without-a-wardrobe; else bad check-no-file-without-a-wardrobe "exit $rc $(cat "$T/err")"; fi
    env -u SUIT_HOME -u HOME "$SUIT" check >/dev/null 2>"$T/err"; rc=$?
    if [ $rc -eq 1 ] && grep -qF "neither SUIT_HOME nor HOME is set" "$T/err"; then pass check-no-file-without-a-home; else bad check-no-file-without-a-home "exit $rc $(cat "$T/err")"; fi
    "$SUIT" check a b >/dev/null 2>"$T/err"; rc=$?
    if [ $rc -eq 2 ] && grep -qF "usage: suit check [FILE]" "$T/err"; then pass check-with-two-files-is-usage; else bad check-with-two-files-is-usage "exit $rc"; fi
}
stack_check_tests

echo "run.sh: $total cases, $failed failed"
[ "$failed" -eq 0 ]
