#!/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-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" run >"$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 ' ')" = 4 ]; then pass stamp-one-line-per-path; else bad stamp-one-line-per-path; 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" run >"$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" run >"$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" run >"$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" run >"$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" run >"$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" run >"$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" run >"$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" run >/dev/null 2>&1; [ $? -eq 0 ] && pass run-empty-stamp-exit-0 || bad run-empty-stamp-exit-0

"$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
"$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" run >"$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" run
fcase fault-spec-unknown-name frob:1 99 "unknown call name" -- "$SUIT" run
fcase fault-spec-count-not-number read:x 99 "N must be a positive number" -- "$SUIT" run
fcase fault-spec-count-zero read:0 99 "N must be a positive number" -- "$SUIT" run
fcase fault-spec-count-trailing read:2x 99 "N must be a positive number" -- "$SUIT" run
fcase fault-spec-short-on-open open:1:short 99 "short applies only to read and write" -- "$SUIT" run
fcase fault-spec-unknown-errno read:1:EWHAT 99 "unknown errno" -- "$SUIT" run
fcase fault-spec-errno-zero read:1:0 99 "unknown errno" -- "$SUIT" run
fcase fault-spec-errno-trailing read:1:12x 99 "unknown errno" -- "$SUIT" run
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" run >/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" run >/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" run >"$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" run >"$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" run
fcase fault-run-open-stamp open:1 1 "cannot read $F/home/stamp: $EIO" -- "$SUIT" run
fcase fault-run-open-stamp-enoent open:1:ENOENT 11 "no stamp at" -- "$SUIT" run
fcase fault-run-read read:1 1 "cannot read $F/home/stamp: $EIO" -- "$SUIT" run
fcase fault-run-read-interrupted-retries read:1:EINTR 0 "" -- "$SUIT" run
fcase fault-run-short-reads read:1:short 0 "" -- "$SUIT" run
fcase fault-run-close-stamp-ignored close:1 0 "" -- "$SUIT" run
fcase fault-run-stat-fails-present-path-is-changed stat:1 10 "" -- "$SUIT" run
fcase fault-run-folder-open-fails-falls-back-to-stat open:2:EACCES 0 "" -- "$SUIT" run
fcase fault-run-fstatat-fails-present-path-is-changed fstatat:1 10 "" -- "$SUIT" run
fcase fault-run-folder-close-ignored close:2 0 "" -- "$SUIT" run
fcase fault-run-write-of-changed-line-ignored write:1 0 "" -- "$SUIT" run
"$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" run
fcase fault-run-stat-enotdir-on-missing-path-is-unchanged stat:1:ENOTDIR 0 "" -- "$SUIT" run
fcase fault-run-stat-enoent-on-missing-path-is-unchanged stat:1:ENOENT 0 "" -- "$SUIT" run
cd "$ROOT" || exit 1

# Hand-made stamps.
stamp_case() { # NAME RC MSG   (stamp text on stdin)
    cat > "$F/home/stamp"
    "$SUIT" run >"$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:2: expected SIZE" <<'X'
- - - /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'
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" run >/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" run >/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" run >/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 '{ $3 = ($3 == 1 ? 2 : 1); print }' "$F/home/stamp" > "$F/home/stamp.new" && mv "$F/home/stamp.new" "$F/home/stamp"
"$SUIT" run >"$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 '{ $2 = $2 + 1; print }' "$F/home/stamp" > "$F/home/stamp.new" && mv "$F/home/stamp.new" "$F/home/stamp"
"$SUIT" run >"$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 '5 1 1 /suit-no-such-file\nx\n' > "$F/home/stamp"
"$SUIT" run >"$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 over empty" "$T/out" && grep -qF "suit over /usr/bin/true" "$T/out" && grep -qF "median of per-round differences, suit 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-measured-rounds spawn:31 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

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