#!/bin/sh
# Shell tests for the store: open, status, commit, update, back. They run on
# test/fixtures/wardrobe.fossil, so they need no stock fossil; the cases that
# compare against stock fossil say so and skip when it is not installed.
# SUIT names the binary under test (default build/dev/suit).

SUIT=${SUIT:-build/dev/suit}
case $SUIT in /*) ;; *) SUIT=$PWD/$SUIT ;; esac
ROOT=$PWD
FIXTURE=$ROOT/test/fixtures/wardrobe.fossil
LINKS=$ROOT/test/fixtures/wardrobe-link.fossil
LINKS_V1=$ROOT/test/fixtures/wardrobe-link-v1.fossil
mkdir -p build/tmp
T=$(mktemp -d "$ROOT/build/tmp/store.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}"
}
skip() { echo "skip $1: $2"; }
have_fossil() { command -v fossil >/dev/null 2>&1; }

export USER=tester
unset LOGNAME

# check NAME WANT_RC [STDERR_SUBSTRING] -- COMMAND...   (output in $T/out, $T/err)
check() {
    cname=$1; cwant=$2; cmsg=$3; shift 4
    "$@" >"$T/out" 2>"$T/err"; crc=$?
    if [ "$crc" != "$cwant" ]; then bad "$cname" "exit $crc, want $cwant: $(cat "$T/err")"
    elif [ -n "$cmsg" ] && ! grep -qF -- "$cmsg" "$T/err"; then bad "$cname" "want '$cmsg' in: $(cat "$T/err")"
    else pass "$cname"; fi
}

# fresh NAME: a new SUIT_HOME with the fixture wardrobe as NAME
fresh() {
    rm -rf "$T/home"
    mkdir -p "$T/home/wardrobes"
    cp "$FIXTURE" "$T/home/wardrobes/$1.fossil"
    export SUIT_HOME="$T/home"
}

# tree DIR: every file with its content sum and mode bits, to compare two trees
tree() {
    (cd "$1" && find . \( -name .fslckout -o -name '.suit-tmp.*' \) -prune -o -type f -print | sort | while read -r f; do
        if [ -x "$f" ]; then m=x; else m=-; fi
        printf '%s %s %s\n' "$f" "$(cksum < "$f")" "$m"
    done)
}

store=$T/home/store

# fan FUNC NAME...: FUNC NAME in a subshell of its own for each NAME, up to
# TEST_JOBS at a time (default 1: one after another); each one's output goes
# to $T/fan/FUNC.NAME. fan_show prints those files in order and counts their
# ok and FAIL lines, since a subshell's counters are lost.
fan() {
    ffn=$1; shift; mkdir -p "$T/fan"; fq=; fall=
    for fnm in "$@"; do
        if [ "${TEST_JOBS:-1}" -le 1 ]; then ( "$ffn" "$fnm" ) >"$T/fan/$ffn.$fnm" 2>&1; continue; fi
        if [ "$(set -- $fq; echo $#)" -ge "$TEST_JOBS" ]; then
            ffirst=${fq%% *}; wait "$ffirst"; fq=${fq#"$ffirst"}; fq=${fq# }
        fi
        ( "$ffn" "$fnm" ) >"$T/fan/$ffn.$fnm" 2>&1 &
        fq=${fq:+$fq }$!; fall="$fall $!"
    done
    # not a bare wait: the http server's deadline timer is also a child
    [ -z "$fall" ] || wait $fall
}
fan_show() {
    ffn=$1; shift
    for fnm in "$@"; do
        cat "$T/fan/$ffn.$fnm"
        total=$((total + $(grep -c '^ok ' "$T/fan/$ffn.$fnm") + $(grep -c '^FAIL ' "$T/fan/$ffn.$fnm")))
        failed=$((failed + $(grep -c '^FAIL ' "$T/fan/$ffn.$fnm")))
    done
}

# ---- open -------------------------------------------------------------------

fresh wd
check open-new-store 0 "" -- "$SUIT" store open wd
tree "$store/wd" > "$T/tree1"
if [ "$(wc -l < "$T/tree1" | tr -d ' ')" = 4 ] && grep -q "^./run.sh .* x$" "$T/tree1" && grep -q "^./skills/gamma.md .* -$" "$T/tree1" && [ ! -e "$store/wd/skills/beta" ]; then pass open-extracts-tip-files-and-modes; else bad open-extracts-tip-files-and-modes "$(cat "$T/tree1")"; fi
[ "$(cat "$store/wd/skills/alpha/SKILL.md")" = "alpha v2" ] && pass open-file-contents || bad open-file-contents
check open-twice-is-idempotent 0 "" -- "$SUIT" store open wd
tree "$store/wd" > "$T/tree2"
cmp -s "$T/tree1" "$T/tree2" && pass open-twice-changes-nothing || bad open-twice-changes-nothing
check status-clean-after-open 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass status-clean-prints-nothing || bad status-clean-prints-nothing "$(cat "$T/out")"

check open-bad-name 2 "is not a wardrobe name" -- "$SUIT" store open 'bad/name'
check open-empty-name 2 "is not a wardrobe name" -- "$SUIT" store open ''
check open-no-such-wardrobe 1 "no wardrobe at $T/home/wardrobes/nosuch.fossil" -- "$SUIT" store open nosuch
check open-no-user 1 "cannot tell who you are" -- env -u USER -u LOGNAME "$SUIT" store open wd
check open-empty-user 1 "cannot tell who you are" -- env USER= "$SUIT" store open wd
check open-empty-user-and-logname 1 "cannot tell who you are" -- env USER= LOGNAME= "$SUIT" store open wd
check open-user-from-logname 0 "" -- env -u USER LOGNAME=other "$SUIT" store open wd
check open-no-home-at-all 1 "neither SUIT_HOME nor HOME is set" -- env -u SUIT_HOME -u HOME "$SUIT" store open wd

# -- the folders open makes
for n in 1 2 3; do
    fresh wd
    check "open-mkdir-$n-fails" 1 "cannot create" -- env SUIT_FAULT=mkdir:$n:EACCES "$SUIT" store open wd
done

# -- a wardrobe that is not one
fresh wd
printf 'this is not a database' > "$T/home/wardrobes/wd.fossil"
check open-corrupt-wardrobe 1 "store wd: open the wardrobe failed" -- "$SUIT" store open wd
fresh wd
: > "$T/home/wardrobes/wd.fossil"
check open-empty-wardrobe-file 1 "failed" -- "$SUIT" store open wd

# -- an open that stops part way is finished by the next one
fresh wd
check open-stops-at-first-file-write 1 "extract the files failed" -- env SUIT_FAULT=rename:2 "$SUIT" store open wd
check open-resumes-after-a-stop 0 "" -- "$SUIT" store open wd
tree "$store/wd" > "$T/tree3"
cmp -s "$T/tree1" "$T/tree3" && pass open-resume-matches-fresh-open || bad open-resume-matches-fresh-open "$(diff "$T/tree1" "$T/tree3")"
check status-clean-after-resume 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass status-clean-after-resume-prints-nothing || bad status-clean-after-resume-prints-nothing "$(cat "$T/out")"
if ls "$store/wd"/.suit-tmp.* "$store/wd"/*/.suit-tmp.* >/dev/null 2>&1; then bad failed-open-leaves-no-temp-file; else pass failed-open-leaves-no-temp-file; fi

# ---- status ------------------------------------------------------------------

fresh wd
"$SUIT" store open wd >/dev/null 2>&1
cp "$FIXTURE" "$T/home/wardrobes/other.fossil"
check status-before-open 1 "open the working copy failed" -- "$SUIT" store status other
printf -- '---\nedited\n' > "$store/wd/skills/alpha/SKILL.md"
printf 'new\n' > "$store/wd/skills/delta.md"
mkdir -p "$store/wd/newdir/deeper"
printf 'deep\n' > "$store/wd/newdir/deeper/file.md"
rm "$store/wd/agents/reviewer.md"
chmod -x "$store/wd/run.sh"
"$SUIT" store status wd > "$T/status" 2>"$T/err"; rc=$?
sort "$T/status" > "$T/status.sorted"
want='added newdir/deeper/file.md
added skills/delta.md
deleted agents/reviewer.md
edited run.sh
edited skills/alpha/SKILL.md'
if [ $rc -eq 0 ] && [ "$(cat "$T/status.sorted")" = "$want" ]; then pass status-lists-edits-additions-deletions; else bad status-lists-edits-additions-deletions "rc $rc: $(cat "$T/status")"; fi
"$SUIT" store status wd > "$T/status2" 2>/dev/null
sort "$T/status2" | cmp -s - "$T/status.sorted" && pass status-twice-is-the-same || bad status-twice-is-the-same
# status looks and changes nothing: an untracked file stays untracked
printf 'x\n' > "$T/probe"
printf 'tmp\n' > "$store/wd/.suit-tmp.123.4"
"$SUIT" store status wd 2>/dev/null | grep -q suit-tmp && bad status-hides-our-temp-names || pass status-hides-our-temp-names
rm -f "$store/wd/.suit-tmp.123.4"

# ---- commit ------------------------------------------------------------------

check commit-everything 0 "" -- "$SUIT" commit wd -m "local work"
grep -q "^checked in [0-9a-f]\{12\}$" "$T/out" && pass commit-says-what-it-did || bad commit-says-what-it-did "$(cat "$T/out")"
check status-clean-after-commit 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass status-after-commit-prints-nothing || bad status-after-commit-prints-nothing "$(cat "$T/out")"
check commit-clean-does-nothing 0 "" -- "$SUIT" commit wd -m "nothing"
[ ! -s "$T/out" ] && pass commit-clean-prints-nothing || bad commit-clean-prints-nothing
printf 'more\n' >> "$store/wd/run.sh"
check commit-empty-message-fails-on-real-changes 1 "check in failed" -- "$SUIT" commit wd -m ""
check commit-usage-no-message 2 "usage" -- "$SUIT" commit wd
check commit-usage-wrong-flag 2 "usage" -- "$SUIT" commit wd -x text
check store-usage-missing-name 2 "usage" -- "$SUIT" store open
check store-usage-unknown-verb 2 "usage" -- "$SUIT" store frobnicate wd
check back-usage 2 "usage" -- "$SUIT" back
cp "$FIXTURE" "$T/home/wardrobes/nowhere.fossil"
check store-commit-before-open 1 "open the working copy failed" -- "$SUIT" commit nowhere -m x

# ---- update ------------------------------------------------------------------
# Two stores on one repository file: y is behind, x makes the next version.

fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
printf -- '---\nalpha v3\n' > "$store/x/skills/alpha/SKILL.md"
printf 'epsilon v3\n' > "$store/x/skills/epsilon.md"
rm "$store/x/skills/gamma.md"
chmod +x "$store/x/skills/epsilon.md"
"$SUIT" commit x -m "third" >/dev/null 2>&1
tree "$store/y" > "$T/y-before"

check update-conflict-with-an-untracked-file 13 "" -- sh -c 'printf "mine\n" > "$1/skills/epsilon.md"; "$2" store update y' sh "$store/y" "$SUIT"
if [ "$(cat "$T/out")" = "conflict skills/epsilon.md" ]; then pass update-conflict-names-the-file; else bad update-conflict-names-the-file "$(cat "$T/out")"; fi
rm "$store/y/skills/epsilon.md"
tree "$store/y" > "$T/y-after-conflict"
cmp -s "$T/y-before" "$T/y-after-conflict" && pass update-conflict-changes-nothing || bad update-conflict-changes-nothing

printf 'local edit\n' > "$store/y/agents/reviewer.md"
check update-refuses-with-local-changes 12 "" -- "$SUIT" store update y
[ "$(cat "$T/out")" = "edited agents/reviewer.md" ] && pass update-refusal-lists-the-files || bad update-refusal-lists-the-files "$(cat "$T/out")"
check update-refuses-with-a-deleted-file 12 "" -- sh -c 'cp "$1/agents/reviewer.md" "$1/keep"; rm "$1/agents/reviewer.md"; "$2" store update y' sh "$store/y" "$SUIT"
grep -q "^deleted agents/reviewer.md$" "$T/out" && pass update-refusal-lists-deletions || bad update-refusal-lists-deletions "$(cat "$T/out")"

# Start clean for the cases that update.
fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
printf -- '---\nalpha v3\n' > "$store/x/skills/alpha/SKILL.md"
printf 'epsilon v3\n' > "$store/x/skills/epsilon.md"
rm "$store/x/skills/gamma.md"
chmod +x "$store/x/skills/epsilon.md"
printf '#!/bin/sh\necho v3\n' > "$store/x/run.sh"
"$SUIT" commit x -m "third" >/dev/null 2>&1
tree "$store/y" > "$T/y-v2"
check update-to-new-tip 0 "" -- "$SUIT" store update y
grep -q "^updated to [0-9a-f]\{12\}$" "$T/out" && pass update-says-the-version || bad update-says-the-version "$(cat "$T/out")"
tree "$store/y" > "$T/y-v3"
tree "$store/x" > "$T/x-v3"
cmp -s "$T/y-v3" "$T/x-v3" && pass update-makes-y-identical-to-x || bad update-makes-y-identical-to-x "$(diff "$T/y-v3" "$T/x-v3")"
grep -q "^./skills/epsilon.md .* x$" "$T/y-v3" && grep -q "^./run.sh .* x$" "$T/y-v3" && [ ! -e "$store/y/skills/gamma.md" ] && pass update-adds-removes-and-keeps-modes || bad update-adds-removes-and-keeps-modes
check status-clean-after-update 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-update-prints-nothing || bad status-after-update-prints-nothing "$(cat "$T/out")"
check update-at-the-tip 0 "" -- "$SUIT" store update y
tree "$store/y" > "$T/y-v3b"
cmp -s "$T/y-v3" "$T/y-v3b" && pass update-at-the-tip-changes-nothing || bad update-at-the-tip-changes-nothing

# -- back
check back-after-update 0 "" -- "$SUIT" back y
grep -q "^back at [0-9a-f]\{12\}$" "$T/out" && pass back-says-the-version || bad back-says-the-version "$(cat "$T/out")"
tree "$store/y" > "$T/y-back"
cmp -s "$T/y-v2" "$T/y-back" && pass back-restores-the-previous-bytes-and-modes || bad back-restores-the-previous-bytes-and-modes "$(diff "$T/y-v2" "$T/y-back")"
check status-clean-after-back 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-back-prints-nothing || bad status-after-back-prints-nothing "$(cat "$T/out")"
check back-twice-has-nothing 14 "nothing to go back to" -- "$SUIT" back y
check update-again-after-back 0 "" -- "$SUIT" store update y
tree "$store/y" > "$T/y-v3c"
cmp -s "$T/y-v3" "$T/y-v3c" && pass update-after-back-reaches-the-tip-again || bad update-after-back-reaches-the-tip-again
printf 'after\n' >> "$store/y/run.sh"
"$SUIT" commit y -m "y moves on" >/dev/null 2>&1
check back-after-a-commit 14 "cannot go back: the store has changed since the update" -- "$SUIT" back y

# -- an update that fails part way puts every file back
fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
for f in skills/alpha/SKILL.md skills/gamma.md agents/reviewer.md; do printf -- '---\nv3 of %s\n' "$f" > "$store/x/$f"; done
"$SUIT" commit x -m third >/dev/null 2>&1
tree "$store/y" > "$T/y-v2"
check update-stops-when-a-write-fails 1 "update failed" -- env SUIT_FAULT=rename:3 "$SUIT" store update y
grep -q "the files are back at the version they were at" "$T/err" && pass update-failure-puts-files-back || bad update-failure-puts-files-back "$(cat "$T/err")"
tree "$store/y" > "$T/y-failed"
cmp -s "$T/y-v2" "$T/y-failed" && pass update-failure-leaves-old-bytes || bad update-failure-leaves-old-bytes "$(diff "$T/y-v2" "$T/y-failed")"
if ls "$store/y"/.suit-tmp.* "$store/y"/*/.suit-tmp.* >/dev/null 2>&1; then bad update-failure-leaves-no-temp-file; else pass update-failure-leaves-no-temp-file; fi
check status-clean-after-failed-update 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-failed-update-prints-nothing || bad status-after-failed-update-prints-nothing "$(cat "$T/out")"
check update-and-put-back-both-fail 1 "could not put the files back" -- env SUIT_FAULT=rename:3,rename:4 "$SUIT" store update y

# -- repair after the update and the put-back both failed
[ -f "$T/home/y.journal" ] && pass failed-put-back-leaves-a-journal || bad failed-put-back-leaves-a-journal
cp "$T/home/y.journal" "$T/journal.good"
tree "$store/y" > "$T/y-half"
cmp -s "$T/y-v2" "$T/y-half" && bad store-is-half-updated "the files did not change" || pass store-is-half-updated
for cmd in "store status y" "store open y" "store update y" "commit y -m x" "back y"; do
    # shellcheck disable=SC2086
    check "journal-stops-[$cmd]" 15 "store y has an unfinished update; run \`suit store repair y\`" -- "$SUIT" $cmd
done
check repair-after-double-failure 0 "" -- "$SUIT" store repair y
grep -q "^repaired; back at [0-9a-f]\{12\}$" "$T/out" && pass repair-says-the-version || bad repair-says-the-version "$(cat "$T/out")"
tree "$store/y" > "$T/y-repaired"
cmp -s "$T/y-v2" "$T/y-repaired" && pass repair-restores-the-old-bytes || bad repair-restores-the-old-bytes "$(diff "$T/y-v2" "$T/y-repaired")"
[ ! -e "$T/home/y.journal" ] && pass repair-removes-the-journal || bad repair-removes-the-journal
check status-clean-after-repair 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-repair-prints-nothing || bad status-after-repair-prints-nothing "$(cat "$T/out")"
check repair-twice-is-a-no-op 0 "" -- "$SUIT" store repair y
[ "$(cat "$T/out")" = "nothing to repair" ] && pass second-repair-says-nothing-to-repair || bad second-repair-says-nothing-to-repair "$(cat "$T/out")"
tree "$store/y" > "$T/y-repaired2"
cmp -s "$T/y-repaired" "$T/y-repaired2" && pass second-repair-changes-nothing || bad second-repair-changes-nothing
check update-after-repair 0 "" -- "$SUIT" store update y
tree "$store/x" > "$T/x-now"; tree "$store/y" > "$T/y-now"
cmp -s "$T/x-now" "$T/y-now" && pass update-after-repair-reaches-the-new-version || bad update-after-repair-reaches-the-new-version

# -- repair without a journal never throws edits away
printf 'my edit\n' > "$store/y/agents/reviewer.md"
check repair-refuses-local-edits 12 "" -- "$SUIT" store repair y
[ "$(cat "$T/out")" = "edited agents/reviewer.md" ] && pass repair-refusal-lists-the-edits || bad repair-refusal-lists-the-edits "$(cat "$T/out")"
[ "$(cat "$store/y/agents/reviewer.md")" = "my edit" ] && pass repair-refusal-keeps-the-edit || bad repair-refusal-keeps-the-edit

# -- the journal, read badly
write_journal() { cp "$T/journal.good" "$T/home/y.journal"; }
write_journal
# The C library words errno 5 its own way (glibc and macOS spell it out,
# musl shortens it). Ask the binary under test.
EIO=$(SUIT_FAULT=open:1 "$SUIT" check test/fixtures/example.conf 2>&1 | sed -n 's/.*cannot open: //p')
[ -n "$EIO" ] || { echo "FAIL cannot learn the errno wording"; exit 1; }
check repair-journal-open-fails 1 "cannot read $T/home/y.journal: $EIO" -- env SUIT_FAULT=open:1 "$SUIT" store repair y
check repair-journal-read-fails 1 "could not be read: $EIO" -- env SUIT_FAULT=read:1 "$SUIT" store repair y
printf 'garbage' > "$T/home/y.journal"
check repair-damaged-journal 1 "is damaged" -- "$SUIT" store repair y
awk 'BEGIN { for (i = 0; i < 40; i++) printf "from-this-is-not-a-journal-line-%d\n", i }' > "$T/home/y.journal"
check repair-oversized-journal 1 "is damaged" -- "$SUIT" store repair y
printf 'from ffffffffffffffffffffffffffffffffffffffff\nto ffffffffffffffffffffffffffffffffffffffff\n' > "$T/home/y.journal"
check repair-journal-names-an-unknown-version 1 "names a version this wardrobe does not have" -- "$SUIT" store repair y
write_journal
check repair-journal-read-interrupted-retries 0 "" -- env SUIT_FAULT=read:1:EINTR "$SUIT" store repair y
write_journal
check repair-journal-short-reads 0 "" -- env SUIT_FAULT=read:1:short "$SUIT" store repair y
[ ! -e "$T/home/y.journal" ] && pass repair-after-a-good-journal-removes-it || bad repair-after-a-good-journal-removes-it
check update-cannot-write-the-journal 1 "cannot write $T/home/y.journal: $EIO" -- env SUIT_FAULT=open:1 "$SUIT" store update y
[ ! -e "$T/home/y.journal" ] && pass failed-journal-write-leaves-no-journal || bad failed-journal-write-leaves-no-journal

# -- a crash in the middle of an update, then repair
fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
mkdir -p "$store/x/many"
i=0
while [ $i -lt 100 ]; do printf 'old %d\n' $i > "$store/x/many/f$i"; i=$((i + 1)); done
"$SUIT" commit x -m many >/dev/null 2>&1
"$SUIT" store update y >/dev/null 2>&1
i=0
while [ $i -lt 100 ]; do printf 'new %d\n' $i > "$store/x/many/f$i"; i=$((i + 1)); done
"$SUIT" commit x -m many2 >/dev/null 2>&1
tree "$store/y" > "$T/y-pre-crash"
SUIT_FAULT=rename:2:delay "$SUIT" store update y >/dev/null 2>&1 &
victim=$!
i=0
while [ ! -f "$T/home/y.journal" ] && [ $i -lt 400 ]; do sleep 0.05; i=$((i + 1)); done
sleep 0.5
kill -9 "$victim" 2>/dev/null
wait "$victim" 2>/dev/null
[ -f "$T/home/y.journal" ] && pass killed-update-leaves-its-journal || bad killed-update-leaves-its-journal
tree "$store/y" > "$T/y-crashed"
cmp -s "$T/y-pre-crash" "$T/y-crashed" && bad killed-update-had-started "no file had changed" || pass killed-update-had-started
check killed-update-blocks-status 15 "unfinished update" -- "$SUIT" store status y
check repair-after-kill 0 "" -- "$SUIT" store repair y
tree "$store/y" > "$T/y-after-kill"
cmp -s "$T/y-pre-crash" "$T/y-after-kill" && pass repair-after-kill-restores-the-old-bytes || bad repair-after-kill-restores-the-old-bytes "$(diff "$T/y-pre-crash" "$T/y-after-kill" | head -4)"
check status-clean-after-kill-and-repair 0 "" -- "$SUIT" store status y
[ ! -s "$T/out" ] && pass status-after-kill-and-repair-prints-nothing || bad status-after-kill-and-repair-prints-nothing "$(cat "$T/out")"
check update-after-kill-and-repair 0 "" -- "$SUIT" store update y
tree "$store/x" > "$T/x-after"; tree "$store/y" > "$T/y-after"
cmp -s "$T/x-after" "$T/y-after" && pass update-after-kill-and-repair-reaches-the-new-version || bad update-after-kill-and-repair-reaches-the-new-version

# -- symlinks are refused, with the path
rm -rf "$T/home"; mkdir -p "$T/home/wardrobes"; export SUIT_HOME="$T/home"
cp "$LINKS" "$T/home/wardrobes/ln.fossil"
check open-refuses-a-version-with-a-symlink 16 "this version of the wardrobe has a symlink at link.md; symlinks are not supported" -- "$SUIT" store open ln
[ ! -e "$store/ln/skills" ] && pass refused-open-extracts-nothing || bad refused-open-extracts-nothing
cp "$LINKS_V1" "$T/home/wardrobes/zz.fossil"
"$SUIT" store open zz >/dev/null 2>&1
cp "$LINKS" "$T/home/wardrobes/zz.fossil"
tree "$store/zz" > "$T/zz-before"
check update-refuses-a-version-with-a-symlink 16 "has a symlink at link.md" -- "$SUIT" store update zz
tree "$store/zz" > "$T/zz-after"
cmp -s "$T/zz-before" "$T/zz-after" && pass refused-update-changes-nothing || bad refused-update-changes-nothing
[ ! -e "$T/home/zz.journal" ] && pass refused-update-writes-no-journal || bad refused-update-writes-no-journal

fresh wd
"$SUIT" store open wd >/dev/null 2>&1
ln -s agents/reviewer.md "$store/wd/skills/ref.md"
mkdir -p "$store/wd/sub/deep"
ln -s ../../run.sh "$store/wd/sub/deep/runlink"
ln -s agents "$store/wd/dirlink"
printf 'a real change\n' > "$store/wd/skills/gamma.md"
check commit-refuses-symlinks 3 "dirlink: symlink, not supported" -- "$SUIT" commit wd -m links
grep -qF "skills/ref.md: symlink, not supported" "$T/err" && grep -qF "sub/deep/runlink: symlink, not supported" "$T/err" && pass commit-names-every-symlink || bad commit-names-every-symlink "$(cat "$T/err")"
"$SUIT" store status wd 2>/dev/null | grep -q "^edited skills/gamma.md$" && pass refused-commit-keeps-the-change || bad refused-commit-keeps-the-change
rm "$store/wd/skills/ref.md" "$store/wd/sub/deep/runlink" "$store/wd/dirlink"
check commit-after-removing-the-symlinks 0 "" -- "$SUIT" commit wd -m "no links now"
deep=$store/wd
i=0; while [ $i -lt 70 ]; do deep=$deep/d; i=$((i + 1)); done
mkdir -p "$deep"
check commit-refuses-folders-nested-too-deep 1 "are nested more than 64 deep" -- "$SUIT" commit wd -m deep
rm -rf "$store/wd/d"

for spec in open:2 write:2 fsync:2 close:2; do
    fresh x
    ln -s x.fossil "$T/home/wardrobes/y.fossil"
    "$SUIT" store open x >/dev/null 2>&1
    "$SUIT" store open y >/dev/null 2>&1
    printf -- '---\nv3\n' > "$store/x/skills/alpha/SKILL.md"
    "$SUIT" commit x -m third >/dev/null 2>&1
    tree "$store/y" > "$T/y-pre"
    SUIT_FAULT=$spec "$SUIT" store update y >/dev/null 2>&1; rc=$?
    tree "$store/y" > "$T/y-post"
    if [ $rc -ne 1 ] || ! cmp -s "$T/y-pre" "$T/y-post"; then bad "update-fault-${spec%%:*}-keeps-old-bytes" "rc $rc"; else pass "update-fault-${spec%%:*}-keeps-old-bytes"; fi
done

# -- no reader ever sees half a file
files=150
fresh x
ln -s x.fossil "$T/home/wardrobes/y.fossil"
"$SUIT" store open x >/dev/null 2>&1
"$SUIT" store open y >/dev/null 2>&1
mkdir -p "$store/x/many"
i=0
while [ $i -lt $files ]; do
    awk -v n=$i 'BEGIN { for (k = 0; k < 400; k++) printf "old content of file %d line %d\n", n, k }' > "$store/x/many/f$i"
    i=$((i + 1))
done
"$SUIT" commit x -m many >/dev/null 2>&1
"$SUIT" store update y >/dev/null 2>&1
i=0; : > "$T/old"; : > "$T/new"
while [ $i -lt $files ]; do
    cksum < "$store/y/many/f$i" | sed "s/^/f$i /" >> "$T/old"
    awk -v n=$i 'BEGIN { for (k = 0; k < 400; k++) printf "new content of file %d line %d\n", n, k }' > "$store/x/many/f$i"
    i=$((i + 1))
done
"$SUIT" commit x -m many2 >/dev/null 2>&1
i=0
while [ $i -lt $files ]; do
    cksum < "$store/x/many/f$i" | sed "s/^/f$i /" >> "$T/new"
    i=$((i + 1))
done
# One rename in 20 ms, so the update takes seconds and a reader has time to look.
SUIT_FAULT=rename:1:delay "$SUIT" store update y >/dev/null 2>&1 &
updater=$!
seen_old=0; seen_new=0; wrong=0; rounds=0
while kill -0 "$updater" 2>/dev/null && [ $rounds -lt 400 ]; do
    i=0
    while [ $i -lt $files ]; do
        line="f$i $(cksum < "$store/y/many/f$i" 2>/dev/null)"
        if grep -qxF -- "$line" "$T/old"; then seen_old=$((seen_old + 1))
        elif grep -qxF -- "$line" "$T/new"; then seen_new=$((seen_new + 1))
        else wrong=$((wrong + 1)); fi
        i=$((i + 1))
    done
    rounds=$((rounds + 1))
done
wait "$updater"; urc=$?
if [ "$urc" -eq 0 ] && [ "$wrong" -eq 0 ] && [ "$seen_old" -gt 0 ] && [ "$seen_new" -gt 0 ]; then pass reader-never-sees-a-half-written-file; else bad reader-never-sees-a-half-written-file "update $urc, $wrong half-written reads, $seen_old old, $seen_new new"; fi
echo "   (a reader looked $((seen_old + seen_new + wrong)) times: $seen_old old, $seen_new new, $wrong neither)"
tree "$store/y" > "$T/y-many"
tree "$store/x" > "$T/x-many"
cmp -s "$T/y-many" "$T/x-many" && pass concurrent-update-ends-identical-to-source || bad concurrent-update-ends-identical-to-source

# ---- stock fossil ------------------------------------------------------------

if have_fossil; then
    # A check-in made by suit is readable by stock fossil.
    fresh wd
    "$SUIT" store open wd >/dev/null 2>&1
    printf -- '---\nfossil reads this\n' > "$store/wd/skills/alpha/SKILL.md"
    printf 'new file\n' > "$store/wd/skills/zeta.md"
    "$SUIT" commit wd -m "made by suit" >/dev/null 2>&1
    R=$T/home/wardrobes/wd.fossil
    if fossil timeline -R "$R" -n 3 2>/dev/null | grep -q "made by suit (user: tester"; then pass fossil-timeline-shows-the-checkin; else bad fossil-timeline-shows-the-checkin; fi
    [ "$(fossil cat skills/alpha/SKILL.md -R "$R" -r tip 2>/dev/null)" = "$(printf -- '---\nfossil reads this')" ] && pass fossil-cat-reads-edited-file || bad fossil-cat-reads-edited-file
    [ "$(fossil cat skills/zeta.md -R "$R" -r tip 2>/dev/null)" = "new file" ] && pass fossil-cat-reads-added-file || bad fossil-cat-reads-added-file
    fossil test-integrity -R "$R" >/dev/null 2>&1 && pass fossil-integrity-after-suit-checkin || bad fossil-integrity-after-suit-checkin
    rm "$store/wd/agents/reviewer.md"
    "$SUIT" commit wd -m "deleted by suit" >/dev/null 2>&1
    fossil cat agents/reviewer.md -R "$R" -r tip >/dev/null 2>&1 && bad fossil-sees-the-deletion || pass fossil-sees-the-deletion

    # Trunk's only newer check-in moved to another branch: nowhere to update to.
    fresh wd
    "$SUIT" store open wd >/dev/null 2>&1
    R=$T/home/wardrobes/wd.fossil
    mkdir "$T/co"
    (cd "$T/co" && fossil open "$R" >/dev/null 2>&1 && printf 'elsewhere\n' > elsewhere.md && fossil add elsewhere.md >/dev/null 2>&1 && fossil commit --branch other --user fixture -m "other branch" >/dev/null 2>&1)
    before=$(tree "$store/wd" | cksum)
    check update-with-no-leaf-on-the-branch-stays-put 0 "" -- "$SUIT" store update wd
    grep -q "^updated to [0-9a-f]\{12\}$" "$T/out" && pass update-with-no-leaf-says-the-version || bad update-with-no-leaf-says-the-version "$(cat "$T/out")"
    [ "$(tree "$store/wd" | cksum)" = "$before" ] && pass update-with-no-leaf-changes-nothing || bad update-with-no-leaf-changes-nothing
    rm -rf "$T/co"

    # Differential: about 600 files, an executable script, and a deletion across
    # two check-ins. The store matches stock fossil's checkout at each version.
    D=$T/diff
    rm -rf "$D"; mkdir -p "$D/co" "$D/home/wardrobes"
    (
        cd "$D/co" || exit 1
        fossil new --admin-user fixture "$D/big.fossil" >/dev/null 2>&1
        fossil open "$D/big.fossil" >/dev/null 2>&1
        d=0
        while [ $d -lt 30 ]; do
            mkdir -p "skills/s$d/ref"
            f=0
            while [ $f -lt 20 ]; do
                awk -v d=$d -v f=$f 'BEGIN { for (k = 0; k < 30; k++) printf "skill %d file %d line %d\n", d, f, k }' > "skills/s$d/ref/f$f.md"
                f=$((f + 1))
            done
            d=$((d + 1))
        done
        printf '#!/bin/sh\necho big\n' > run.sh; chmod +x run.sh
        fossil add . >/dev/null 2>&1
        fossil commit --user fixture -m one >/dev/null 2>&1
        cp "$D/big.fossil" "$D/v1.fossil"
        sleep 1
        printf 'changed\n' >> skills/s3/ref/f4.md
        printf '#!/bin/sh\necho big two\n' > run.sh
        fossil rm skills/s7/ref/f9.md >/dev/null 2>&1
        printf 'added later\n' > skills/s7/ref/extra.md
        fossil add skills/s7/ref/extra.md >/dev/null 2>&1
        fossil commit --user fixture -m two >/dev/null 2>&1
        cp "$D/big.fossil" "$D/v2.fossil"
    )
    count=$(cd "$D/co" && find skills -type f | wc -l | tr -d ' ')
    [ "$count" -ge 600 ] && pass differential-wardrobe-has-about-600-files || bad differential-wardrobe-has-about-600-files "$count files"
    export SUIT_HOME="$D/home"
    cp "$D/v1.fossil" "$D/home/wardrobes/big.fossil"
    "$SUIT" store open big >/dev/null 2>&1
    rm -rf "$D/fco1"; mkdir "$D/fco1"
    (cd "$D/fco1" && fossil open "$D/v1.fossil" >/dev/null 2>&1)
    tree "$D/fco1" > "$T/f-v1"
    tree "$D/home/store/big" > "$T/s-v1"
    cmp -s "$T/f-v1" "$T/s-v1" && pass differential-v1-store-equals-fossil-checkout || bad differential-v1-store-equals-fossil-checkout "$(diff "$T/f-v1" "$T/s-v1" | head -5)"
    cp "$D/v2.fossil" "$D/home/wardrobes/big.fossil"
    check differential-update-to-v2 0 "" -- "$SUIT" store update big
    rm -rf "$D/fco2"; mkdir "$D/fco2"
    (cd "$D/fco2" && fossil open "$D/v2.fossil" >/dev/null 2>&1)
    tree "$D/fco2" > "$T/f-v2"
    tree "$D/home/store/big" > "$T/s-v2"
    cmp -s "$T/f-v2" "$T/s-v2" && pass differential-v2-store-equals-fossil-checkout || bad differential-v2-store-equals-fossil-checkout "$(diff "$T/f-v2" "$T/s-v2" | head -5)"
    grep -q "^./run.sh .* x$" "$T/s-v2" && pass differential-executable-bit-kept || bad differential-executable-bit-kept
    [ ! -e "$D/home/store/big/skills/s7/ref/f9.md" ] && pass differential-deleted-file-is-gone || bad differential-deleted-file-is-gone
    check back-in-the-differential-store 0 "" -- "$SUIT" back big
    tree "$D/home/store/big" > "$T/s-back"
    cmp -s "$T/f-v1" "$T/s-back" && pass differential-back-equals-v1 || bad differential-back-equals-v1
else
    skip differential "stock fossil is not installed"
    skip fossil-reads-suit-checkins "stock fossil is not installed"
fi

# ---- the lint: each rule through suit lint -------------------------------------

lintcase() { printf '%s\n' "$4" > "$store/wd/lintme.txt"; check "$1" "$2" "$3" -- "$SUIT" lint wd; }
fresh wd
"$SUIT" store open wd >/dev/null 2>&1
lintcase lint-clean-store 0 "" "nothing to see"
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass lint-clean-prints-nothing || bad lint-clean-prints-nothing
lintcase lint-private-key 3 "lintme.txt:1: token-shaped value" "x -----BEGIN RSA PRIVATE KEY----- x"
lintcase lint-certificate-is-fine 0 "" "-----BEGIN CERTIFICATE-----"
lintcase lint-private-key-must-share-a-line 0 "" "-----BEGIN
PRIVATE KEY-----"
lintcase lint-aws-key 3 "token-shaped" "id AKIAABCDEFGHIJKLMNOP."
lintcase lint-aws-key-15-is-fine 0 "" "AKIAABCDEFGHIJKLMNO"
lintcase lint-aws-key-lower-case-is-fine 0 "" "AKIAabcdefghijklmnop"
for p in ghp_ gho_ ghs_ github_pat_; do
    lintcase "lint-$p-20" 3 "token-shaped" "t ${p}abcdefghij0123456789"
    lintcase "lint-$p-19-is-fine" 0 "" "t ${p}abcdefghij012345678"
done
lintcase lint-sk-20 3 "token-shaped" "sk-abcdefghij0123456789"
lintcase lint-sk-19-is-fine 0 "" "sk-abcdefghij012345678"
lintcase lint-sk-with-dash-and-underscore 3 "token-shaped" "sk-abc-def_ghi-0123456789"
for p in xoxb- xoxp- xoxa-; do
    lintcase "lint-$p-10" 3 "token-shaped" "$p""0123456789"
    lintcase "lint-$p-9-is-fine" 0 "" "$p""012345678"
done
for w in token secret password passwd api_key apikey api-key; do
    lintcase "lint-credential-$w" 3 "token-shaped" "$w = abcdefghijklmnopqrstuvwx"
done
lintcase lint-credential-quoted-colon 3 "token-shaped" "\"My_API_Key\" :  \"abcdefghij0123456789+/=-_\""
lintcase lint-credential-mixed-case 3 "token-shaped" "PassWord=AbCdEfGhIjKlMnOpQrStUvWx"
lintcase lint-credential-inside-a-word 3 "token-shaped" "my_tokens_list: abcdefghijklmnopqrstuvwx"
lintcase lint-credential-23-is-fine 0 "" "secret = abcdefghijklmnopqrstuvw"
lintcase lint-credential-with-a-space-is-fine 0 "" "secret = abcdefghijklmnop rstuvwxyzabc"
lintcase lint-credential-dollar-is-fine 0 "" 'token = $TOKEN_FROM_THE_ENVIRONMENT_X'
lintcase lint-credential-brace-is-fine 0 "" 'token = ${TOKEN_FROM_THE_ENVIRONMENT}'
lintcase lint-credential-angle-is-fine 0 "" 'password: <your password goes here please>'
lintcase lint-credential-mustache-is-fine 0 "" 'password: {{ lookup_the_password_here }}'
lintcase lint-credential-all-the-same-is-fine 0 "" 'secret = xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
lintcase lint-credential-no-value-is-fine 0 "" 'token ='
lintcase lint-credential-no-separator-is-fine 0 "" 'secret abcdefghijklmnopqrstuvwxyz0123'
for t in "Co-Authored-By: someone" "Generated WITH a tool" "generated by AI" "Claude-Session: x" "written by ai" "Assisted By AI"; do
    lintcase "lint-attribution-$(echo "$t" | tr ' :' '__')" 3 "lintme.txt:1: attribution text" "see $t"
done
lintcase lint-attribution-near-miss-is-fine 0 "" "co-authored by hand; generated by hand; assisted by a friend"

# ---- the lint: binary files, suit.lint, skills, sizes ---------------------------

rm -f "$store/wd/lintme.txt"
printf 'AKIAABCDEFGHIJKLMNOP\0\ngenerated with\n' > "$store/wd/blob.bin"
check lint-skips-a-binary-file 0 "" -- "$SUIT" lint wd
{ head -c 8191 /dev/zero | tr '\0' 'a'; printf '\nAKIAABCDEFGHIJKLMNOP\0'; } > "$store/wd/late.bin"
check lint-nul-after-the-probe-is-text 3 "late.bin:2: token-shaped" -- "$SUIT" lint wd
rm "$store/wd/late.bin" "$store/wd/blob.bin"
printf 'Co-Authored-By: x\nAKIAABCDEFGHIJKLMNOP\n' > "$store/wd/notes.txt"
printf 'allow notes.txt\n' > "$store/wd/suit.lint"
check lint-allow-exempts-a-file 0 "" -- "$SUIT" lint wd
printf 'allow other.txt\n' > "$store/wd/suit.lint"
check lint-allow-is-for-that-file-only 3 "notes.txt:1: attribution text" -- "$SUIT" lint wd
grep -qF "notes.txt:2: token-shaped" "$T/err" && pass lint-reports-every-line || bad lint-reports-every-line "$(cat "$T/err")"
printf 'plain\nsome ACME-Internal text\n' > "$store/wd/notes.txt"
printf 'forbid acme-internal\n' > "$store/wd/suit.lint"
check lint-forbid-any-letter-case 3 "notes.txt:2: text this wardrobe forbids" -- "$SUIT" lint wd
printf 'forbid acme\nallow notes.txt\n' > "$store/wd/suit.lint"
check lint-forbid-and-allow 0 "" -- "$SUIT" lint wd
printf 'frobnicate x\n' > "$store/wd/suit.lint"
check lint-bad-suit-lint-is-a-problem 3 "suit.lint:1:" -- "$SUIT" lint wd
printf 'forbid acme\n' > "$store/wd/suit.lint"
printf 'ok\n' > "$store/wd/notes.txt"
check lint-suit-lint-is-not-scanned-for-its-own-forbid 0 "" -- "$SUIT" lint wd
rm "$store/wd/suit.lint"
mkdir "$store/wd/suit.lint"
check lint-suit-lint-unreadable 1 "suit.lint: cannot read: " -- "$SUIT" lint wd
rmdir "$store/wd/suit.lint"
{ printf 'ok\n'; head -c 65537 /dev/zero | tr '\0' 'a'; printf '\n'; } > "$store/wd/long.txt"
check lint-line-over-64-KiB 3 "long.txt:2: line is longer than 64 KiB" -- "$SUIT" lint wd
rm "$store/wd/long.txt"
head -c 4194305 /dev/zero | tr '\0' 'a' > "$store/wd/huge.txt"
check lint-file-over-4-MiB 3 "huge.txt: larger than 4 MiB, not scanned" -- "$SUIT" lint wd
yes aaaaaaaaaaaaaaa | head -c 4194304 > "$store/wd/huge.txt"
check lint-file-of-4-MiB-is-scanned 0 "" -- "$SUIT" lint wd
rm "$store/wd/huge.txt"
mkdir -p "$store/wd/skills/nohead" "$store/wd/skills/none" "$store/wd/skills/good"
printf 'text\n' > "$store/wd/skills/nohead/SKILL.md"
printf 'text\n' > "$store/wd/skills/nohead/extra.md"
printf 'text\n' > "$store/wd/skills/none/extra.md"
printf '%s\n' '---' 'name: x' '---' > "$store/wd/skills/good/SKILL.md"
check lint-skill-without-a-header 3 "skills/nohead/SKILL.md:1: no header" -- "$SUIT" lint wd
check lint-skill-without-a-skill-file 3 "skills/none: no SKILL.md" -- "$SUIT" lint wd
[ "$(grep -c nohead "$T/err")" = 1 ] && pass lint-says-a-skill-once || bad lint-says-a-skill-once "$(cat "$T/err")"
grep -q good "$T/err" && bad lint-good-skill-is-fine "$(cat "$T/err")" || pass lint-good-skill-is-fine
rm -rf "$store/wd/skills/nohead" "$store/wd/skills/none"
mkdir "$store/wd/skills/dir"; mkdir "$store/wd/skills/dir/SKILL.md"; printf 'x\n' > "$store/wd/skills/dir/SKILL.md/f"
check lint-skill-file-that-is-a-folder 3 "skills/dir: no SKILL.md" -- "$SUIT" lint wd
rm -rf "$store/wd/skills/dir"

# ---- the lint: what it looks at, and what goes wrong -----------------------------

fresh wd
"$SUIT" store open wd >/dev/null 2>&1
rm -rf "$store/wd/skills/alpha"
rm "$store/wd/agents/reviewer.md"
check lint-does-not-look-at-deleted-files-or-folders 0 "" -- "$SUIT" lint wd
check lint-stat-of-a-deleted-skill-folder-fails 1 "cannot read skills/alpha: $EIO" -- env SUIT_FAULT=lstat:2:EIO "$SUIT" lint wd
i=0; while [ $i -lt 1000 ]; do echo 'AKIAABCDEFGHIJKLMNOP'; i=$((i + 1)); done > "$store/wd/many.txt"
check lint-reports-the-first-problems 3 "many.txt:1: token-shaped value" -- "$SUIT" lint wd
[ "$(wc -l < "$T/err" | tr -d ' ')" -le 400 ] && grep -q '^\.\.\. and [0-9][0-9]* more$' "$T/err" && pass lint-counts-the-problems-it-left-out || bad lint-counts-the-problems-it-left-out "$(tail -2 "$T/err")"
rm "$store/wd/many.txt"
fresh wd
"$SUIT" store open wd >/dev/null 2>&1
printf 'x\n' > "$store/wd/lintme.txt"
mkdir -p "$store/wd/skills/gd"
printf -- '---\n' > "$store/wd/skills/gd/SKILL.md"
check lint-store-with-new-files-is-clean 0 "" -- "$SUIT" lint wd
check lint-open-of-suit-lint-fails 1 "suit.lint: cannot open: $EIO" -- env SUIT_FAULT=open:1:EIO "$SUIT" lint wd
check lint-open-of-a-file-fails 1 "cannot read lintme.txt: $EIO" -- env SUIT_FAULT=open:2:EIO "$SUIT" lint wd
check lint-open-of-skill-file-fails 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=open:3:EIO "$SUIT" lint wd
check lint-open-of-skill-file-fails-in-the-scan 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=open:4:EIO "$SUIT" lint wd
check lint-read-of-a-file-fails 1 "cannot read lintme.txt: $EIO" -- env SUIT_FAULT=read:1:EIO "$SUIT" lint wd
check lint-read-of-a-skill-file-fails 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=read:3:EIO "$SUIT" lint wd
check lint-read-interrupted-retries 0 "" -- env SUIT_FAULT=read:1:EINTR "$SUIT" lint wd
check lint-stat-of-a-file-fails 1 "cannot read lintme.txt: $EIO" -- env SUIT_FAULT=lstat:1:EIO "$SUIT" lint wd
check lint-stat-of-a-skill-file-fails 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=lstat:2:EIO "$SUIT" lint wd
check lint-stat-of-a-skill-file-fails-in-the-scan 1 "cannot read skills/gd/SKILL.md: $EIO" -- env SUIT_FAULT=lstat:3:EIO "$SUIT" lint wd
check lint-before-open 1 "no wardrobe at" -- "$SUIT" lint nowhere
check lint-usage 2 "usage" -- "$SUIT" lint
check lint-usage-extra-word 2 "usage" -- "$SUIT" lint wd more
check lint-name-is-checked 2 "is not a wardrobe name" -- "$SUIT" lint "bad/name"
ln -s lintme.txt "$store/wd/link.txt"
check lint-symlink 3 "link.txt: symlink, not supported" -- "$SUIT" lint wd
rm "$store/wd/link.txt"
tree "$store/wd" > "$T/l-before"; cksum < "$T/home/wardrobes/wd.fossil" > "$T/l-repo"
printf 'Generated with a tool\n' > "$store/wd/lintme.txt"
"$SUIT" lint wd >/dev/null 2>&1
printf 'x\n' > "$store/wd/lintme.txt"
tree "$store/wd" > "$T/l-after"; cksum < "$T/home/wardrobes/wd.fossil" > "$T/l-repo2"
cmp -s "$T/l-before" "$T/l-after" && cmp -s "$T/l-repo" "$T/l-repo2" && pass lint-changes-nothing || bad lint-changes-nothing

# ---- commit runs the lint; a large deletion is held ------------------------------

fresh wd
"$SUIT" store open wd >/dev/null 2>&1
printf 'one\n' > "$store/wd/one.txt"
check commit-clean-change-is-checked-in 0 "" -- "$SUIT" commit wd -m "a clean one"
grep -q '^checked in [0-9a-f]\{12\}$' "$T/out" && pass commit-clean-says-what-it-did || bad commit-clean-says-what-it-did "$(cat "$T/out")"
printf 'two\nAKIAABCDEFGHIJKLMNOP\n' > "$store/wd/two.txt"
printf 'one more\n' >> "$store/wd/one.txt"
tree "$store/wd" > "$T/c-before"; cksum < "$T/home/wardrobes/wd.fossil" > "$T/c-repo"
check commit-refused-by-the-lint 3 "two.txt:2: token-shaped value" -- "$SUIT" commit wd -m "no"
tree "$store/wd" > "$T/c-after"; cksum < "$T/home/wardrobes/wd.fossil" > "$T/c-repo2"
cmp -s "$T/c-before" "$T/c-after" && cmp -s "$T/c-repo" "$T/c-repo2" && pass refused-commit-changes-nothing || bad refused-commit-changes-nothing
[ ! -s "$T/out" ] && pass refused-commit-prints-no-check-in || bad refused-commit-prints-no-check-in
"$SUIT" store status wd 2>/dev/null | grep -q '^added two.txt$' && pass refused-commit-keeps-the-changes || bad refused-commit-keeps-the-changes
printf 'two\n' > "$store/wd/two.txt"
check commit-after-the-fix 0 "" -- "$SUIT" commit wd -m "fixed"
check commit-usage-extra-argument 2 "usage" -- "$SUIT" commit wd -m x y
check commit-usage-too-many-arguments 2 "usage" -- "$SUIT" commit wd -m x --confirm-deletions y
check commit-usage-wrong-last-word 2 "usage" -- "$SUIT" commit wd -m x --confirm
check commit-usage-confirm-without-message 2 "usage" -- "$SUIT" commit wd --confirm-deletions x y

# 26 files on top of the fixture's four: 30 tracked. BASE30 and BASE29 are those wardrobes.
mkbase() {
    fresh base
    "$SUIT" store open base >/dev/null 2>&1
    i=1; while [ $i -le "$1" ]; do printf 'f%s\n' "$i" > "$store/base/f$i.txt"; i=$((i + 1)); done
    "$SUIT" commit base -m "files" >/dev/null 2>&1
}
mkbase 26; cp "$T/home/wardrobes/base.fossil" "$T/base30.fossil"
mkbase 25; cp "$T/home/wardrobes/base.fossil" "$T/base29.fossil"
# deleting BASE N: a fresh wardrobe "wd" from BASE with the first N files deleted
deleting() {
    fresh wd; cp "$1" "$T/home/wardrobes/wd.fossil"
    "$SUIT" store open wd >/dev/null 2>&1
    i=1; while [ $i -le "$2" ]; do rm "$store/wd/f$i.txt"; i=$((i + 1)); done
}
deleting "$T/base30.fossil" 5
check commit-deleting-5-of-30-is-not-held 0 "" -- "$SUIT" commit wd -m del
deleting "$T/base30.fossil" 6
check commit-deleting-6-of-30-a-fifth-is-not-held 0 "" -- "$SUIT" commit wd -m del
deleting "$T/base30.fossil" 7
check commit-deleting-7-of-30-is-held 4 "held wd: 7 of 30 files deleted" -- "$SUIT" commit wd -m del
"$SUIT" store status wd 2>/dev/null | grep -c '^deleted f' | grep -q '^7$' && pass held-commit-checks-nothing-in || bad held-commit-checks-nothing-in
check commit-held-deletions-confirmed 0 "" -- "$SUIT" commit wd -m del --confirm-deletions
grep -q '^checked in ' "$T/out" && pass confirmed-commit-checks-in || bad confirmed-commit-checks-in
deleting "$T/base29.fossil" 6
check commit-deleting-6-of-29-just-over-a-fifth-is-held 4 "held wd: 6 of 29 files deleted" -- "$SUIT" commit wd -m del
deleting "$T/base30.fossil" 26
check commit-deleting-most-of-it-is-held 4 "held wd: 26 of 30 files deleted" -- "$SUIT" commit wd -m del
check commit-confirm-when-held-by-size 0 "" -- "$SUIT" commit wd -m del --confirm-deletions

# ---- tend ------------------------------------------------------------------------

att=$T/home/attention
fresh wd
"$SUIT" store open wd >/dev/null 2>&1
check tend-with-nothing-to-do 0 "" -- "$SUIT" tend wd
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && [ ! -e "$att" ] && pass tend-with-nothing-to-do-writes-nothing || bad tend-with-nothing-to-do-writes-nothing
printf 'one\n' > "$store/wd/one.txt"
printf 'two\n' > "$store/wd/two.txt"
check tend-checks-in-a-clean-change 0 "" -- "$SUIT" tend wd
grep -q '^checked in [0-9a-f]\{12\}$' "$T/out" && pass tend-says-what-it-did || bad tend-says-what-it-did "$(cat "$T/out")"
[ ! -s "$T/err" ] && [ ! -e "$att" ] && pass tend-clean-leaves-no-attention || bad tend-clean-leaves-no-attention
"$SUIT" store status wd 2>&1 | grep -q . && bad tend-leaves-the-store-clean || pass tend-leaves-the-store-clean
if have_fossil; then
    fossil timeline -R "$T/home/wardrobes/wd.fossil" -n 1 2>/dev/null | grep -qF "Edits on this machine: 2 files" && pass tend-message-without-a-machine-name || bad tend-message-without-a-machine-name
    "$SUIT" machine laptop >/dev/null 2>&1
    printf 'three\n' > "$store/wd/three.txt"
    "$SUIT" tend wd >/dev/null 2>&1
    fossil timeline -R "$T/home/wardrobes/wd.fossil" -n 1 2>/dev/null | grep -qF "Edits on laptop: 1 files" && pass tend-message-names-the-machine || bad tend-message-names-the-machine
else
    skip tend-message "stock fossil is not installed"
    "$SUIT" machine laptop >/dev/null 2>&1
fi
printf 'bad\nco-authored-by: me\n' > "$store/wd/bad.txt"
printf 'AKIAABCDEFGHIJKLMNOP\n' > "$store/wd/two.txt"
check tend-lint-failure 3 "bad.txt:2: attribution text" -- "$SUIT" tend wd
[ ! -s "$T/out" ] && pass tend-lint-failure-checks-nothing-in || bad tend-lint-failure-checks-nothing-in
[ "$(sed -n 1p "$att")" = "lint wd" ] && grep -qx "  bad.txt:2: attribution text" "$att" && grep -qx "  two.txt:1: token-shaped value" "$att" && [ "$(wc -l < "$att" | tr -d ' ')" = 3 ] && pass tend-writes-the-lint-item || bad tend-writes-the-lint-item "$(cat "$att")"
"$SUIT" tend wd >/dev/null 2>&1; [ "$(wc -l < "$att" | tr -d ' ')" = 3 ] && pass tend-again-does-not-repeat-the-item || bad tend-again-does-not-repeat-the-item
printf 'lint other\n  x.txt:1: y\n' >> "$att"
printf 'bad\n' > "$store/wd/bad.txt"
check tend-lint-failure-with-the-other-items 3 "two.txt:1: token-shaped" -- "$SUIT" tend wd
grep -q '^lint other$' "$att" && grep -q '^  x.txt:1: y$' "$att" && pass tend-keeps-other-wardrobes-items || bad tend-keeps-other-wardrobes-items "$(cat "$att")"
printf 'two\n' > "$store/wd/two.txt"
check tend-after-the-fix 0 "" -- "$SUIT" tend wd
grep -q '^lint wd$' "$att" && bad tend-success-removes-its-item || pass tend-success-removes-its-item
[ "$(cat "$att")" = "lint other
  x.txt:1: y" ] && pass tend-success-keeps-the-others || bad tend-success-keeps-the-others "$(cat "$att")"
printf 'lint wd\n  z:1: w\n' >> "$att"
check tend-nothing-to-do-removes-the-item 0 "" -- "$SUIT" tend wd
grep -q '^lint wd$' "$att" && bad tend-nothing-to-do-clears-its-item || pass tend-nothing-to-do-clears-its-item
rm "$att"
printf 'lint wd\n  z:1: w\n' > "$att"
check tend-nothing-to-do-and-last-item 0 "" -- "$SUIT" tend wd
[ ! -e "$att" ] && pass tend-removes-the-file-when-empty || bad tend-removes-the-file-when-empty
check tend-usage 2 "usage" -- "$SUIT" tend a b
check tend-before-open 1 "no wardrobe at" -- "$SUIT" tend nowhere

# ---- tend: held deletions, the attention file, and failures ----------------------

deleting "$T/base30.fossil" 5
check tend-deleting-5-of-30-is-checked-in 0 "" -- "$SUIT" tend wd
deleting "$T/base30.fossil" 6
check tend-deleting-a-fifth-is-checked-in 0 "" -- "$SUIT" tend wd
deleting "$T/base30.fossil" 7
att=$T/home/attention
check tend-deleting-7-of-30-is-held 4 "held wd: 7 of 30 files deleted" -- "$SUIT" tend wd
[ "$(cat "$att")" = "held wd: 7 of 30 files deleted" ] && pass tend-writes-the-held-item || bad tend-writes-the-held-item "$(cat "$att")"
"$SUIT" store status wd 2>/dev/null | grep -c '^deleted f' | grep -q '^7$' && pass held-tend-checks-nothing-in || bad held-tend-checks-nothing-in
printf 'z\n' > "$store/wd/f1.txt"
i=2; while [ $i -le 7 ]; do printf 'f%s\n' "$i" > "$store/wd/f$i.txt"; i=$((i + 1)); done
check tend-after-the-files-are-back 0 "" -- "$SUIT" tend wd
[ ! -e "$att" ] && pass tend-removes-the-held-item || bad tend-removes-the-held-item "$(cat "$att")"
deleting "$T/base29.fossil" 6
check tend-deleting-6-of-29-is-held 4 "held wd: 6 of 29 files deleted" -- "$SUIT" tend wd
check commit-says-the-same-when-held 4 "held wd: 6 of 29 files deleted" -- "$SUIT" commit wd -m x
rm -f "$att"
check tend-held-attention-write-fails 1 "cannot write $att: $EIO" -- env SUIT_FAULT=rename:1:EIO "$SUIT" tend wd
check commit-confirms-what-tend-held 0 "" -- "$SUIT" commit wd -m x --confirm-deletions

# ---- the attention file and its failures ------------------------------------------

attn() { fresh wd; "$SUIT" store open wd >/dev/null 2>&1; att=$T/home/attention; "$SUIT" machine laptop >/dev/null 2>&1; }
attn
printf 'AKIAABCDEFGHIJKLMNOP\n' > "$store/wd/a.txt"
seed() { printf 'lint other\n  x:1: y\n' > "$att"; }
seed
check attention-open-fails 1 "cannot open $att: $EIO" -- env SUIT_FAULT=open:3:EIO "$SUIT" tend wd
check attention-temporary-file-fails 1 "cannot write $att: $EIO" -- env SUIT_FAULT=open:4:EIO "$SUIT" tend wd
check attention-read-fails 1 "cannot read $att: $EIO" -- env SUIT_FAULT=read:3:EIO "$SUIT" tend wd
check attention-rename-fails 1 "cannot write $att: $EIO" -- env SUIT_FAULT=rename:1:EIO "$SUIT" tend wd
[ "$(cat "$att")" = "lint other
  x:1: y" ] && pass attention-failed-write-keeps-the-file || bad attention-failed-write-keeps-the-file "$(cat "$att")"
check attention-read-interrupted-retries 3 "a.txt:1: token-shaped" -- env SUIT_FAULT=read:3:EINTR "$SUIT" tend wd
head -c 131073 /dev/zero | tr '\0' 'a' > "$att"
check attention-file-too-big 1 "$att is over 131072 bytes" -- "$SUIT" tend wd
yes 'lint o' | head -c 131000 > "$att"
check attention-file-would-be-too-big 1 "$att would be over 131072 bytes" -- "$SUIT" tend wd
rm -f "$att"
rm "$store/wd/a.txt"
printf 'lint wd\n  x:1: y\n' > "$att"
check attention-nothing-to-do-open-fails 1 "cannot open $att: $EIO" -- env SUIT_FAULT=open:2:EIO "$SUIT" tend wd
check attention-remove-fails 1 "cannot remove $att: $EIO" -- env SUIT_FAULT=unlink:1:EIO "$SUIT" tend wd
check attention-remove-of-a-vanished-file-is-fine 0 "" -- env SUIT_FAULT=unlink:1:ENOENT "$SUIT" tend wd
rm -f "$att"
printf 'ok\n' > "$store/wd/a.txt"
printf 'lint wd\n  x:1: y\n' > "$att"
check tend-machine-file-open-fails 1 "cannot open $T/home/machine: $EIO" -- env SUIT_FAULT=open:3:EIO "$SUIT" tend wd
check tend-clearing-the-item-fails 1 "cannot open $att: $EIO" -- env SUIT_FAULT=open:4:EIO "$SUIT" tend wd
"$SUIT" store status wd 2>/dev/null | grep -q '^added a.txt$' && bad tend-checked-in-before-clearing || pass tend-checked-in-before-clearing
printf 'ok2\n' > "$store/wd/a.txt"
printf 'bad name\n' > "$T/home/machine"
check tend-bad-machine-name 1 "machine" -- "$SUIT" tend wd
"$SUIT" store status wd 2>/dev/null | grep -q '^edited a.txt$' && pass tend-bad-machine-name-checks-nothing-in || bad tend-bad-machine-name-checks-nothing-in

# ---- status shows what needs you ---------------------------------------------------

fresh mine
"$SUIT" store open mine >/dev/null 2>&1
: > "$store/mine/suit.conf"
export HOME=$T/home-dir; mkdir -p "$HOME"
check status-without-attention 0 "" -- "$SUIT" status
grep -q 'needs you' "$T/out" && bad status-says-nothing-needs-you || pass status-says-nothing-needs-you
printf 'lint mine\n  skills/x.md:3: token-shaped value\nheld other: 7 of 30 files deleted\n' > "$T/home/attention"
check status-with-attention 0 "" -- "$SUIT" status
[ "$(sed -n '/^needs you:$/,$p' "$T/out")" = "needs you:
lint mine
  skills/x.md:3: token-shaped value
held other: 7 of 30 files deleted" ] && pass status-lists-what-needs-you || bad status-lists-what-needs-you "$(cat "$T/out")"
check status-attention-unreadable 1 "cannot open $T/home/attention: $EIO" -- env SUIT_FAULT=open:4:EIO "$SUIT" status

# ---- more of the attention file; deletions that were already unmanaged -------------

deleting "$T/base30.fossil" 7
att=$T/home/attention
printf 'lint wd\n  q\nlonger wd\n  y\nlint wx\n  z\n' > "$att"
check tend-held-keeps-items-of-other-kinds-and-names 4 "held wd" -- "$SUIT" tend wd
[ "$(cat "$att")" = "lint wd
  q
longer wd
  y
lint wx
  z
held wd: 7 of 30 files deleted" ] && pass attention-keeps-other-kinds-and-names || bad attention-keeps-other-kinds-and-names "$(cat "$att")"
check commit-with-an-empty-message-fails-after-deleting 1 "check in failed" -- "$SUIT" commit wd -m "" --confirm-deletions
check lint-sees-files-already-unmanaged 0 "" -- "$SUIT" lint wd
check commit-counts-files-already-unmanaged 4 "held wd: 7 of 30 files deleted" -- "$SUIT" commit wd -m x
check commit-confirms-files-already-unmanaged 0 "" -- "$SUIT" commit wd -m x --confirm-deletions
attn
printf 'AKIAABCDEFGHIJKLMNOP\n' > "$store/wd/a.txt"
printf 'lint wx\n  z\nlint wd\n  a.txt:1: token-shaped valuf\n' > "$att"
check tend-replaces-an-item-of-the-same-length 3 "a.txt:1: token-shaped value" -- "$SUIT" tend wd
[ "$(cat "$att")" = "lint wx
  z
lint wd
  a.txt:1: token-shaped value" ] && pass attention-replaces-the-item-in-place-of-the-old || bad attention-replaces-the-item-in-place-of-the-old "$(cat "$att")"
rm "$store/wd/a.txt"
fresh wd
"$SUIT" store open wd >/dev/null 2>&1
rm "$store/wd/agents/reviewer.md"
ln -s ../run.sh "$store/wd/agents/reviewer.md"
check lint-tracked-file-replaced-by-a-symlink 3 "agents/reviewer.md: symlink, not supported" -- "$SUIT" lint wd
[ "$(wc -l < "$T/err" | tr -d ' ')" = 1 ] && pass lint-says-a-symlink-once || bad lint-says-a-symlink-once "$(cat "$T/err")"
fresh mine
"$SUIT" store open mine >/dev/null 2>&1
: > "$store/mine/suit.conf"
printf 'lint zz' > "$T/home/attention"
check status-attention-without-a-final-newline 0 "" -- "$SUIT" status
[ "$(sed -n '/^needs you:$/,$p' "$T/out")" = "needs you:
lint zz" ] && pass status-shows-a-last-line-without-a-newline || bad status-shows-a-last-line-without-a-newline "$(cat "$T/out")"

# ---- remote, login, sync -----------------------------------------------------

export HOME=$T/h0
mkdir -p "$HOME"
RT=$T/net
rm -rf "$RT"; mkdir -p "$RT"
fresh wd
mkdir -p "$SUIT_HOME"

check remote-none-is-reported 1 "no remote is set for wd" -- "$SUIT" remote wd
check remote-set 0 "" -- "$SUIT" remote wd "file://$RT/r.fossil"
check remote-show 0 "" -- "$SUIT" remote wd
[ "$(cat "$T/out")" = "file://$RT/r.fossil" ] && pass remote-show-prints-the-address || bad remote-show-prints-the-address "$(cat "$T/out")"
[ "$(cat "$SUIT_HOME/remotes")" = "wd file://$RT/r.fossil" ] && pass remotes-file-is-one-line || bad remotes-file-is-one-line "$(cat "$SUIT_HOME/remotes")"
check remote-set-http 0 "" -- "$SUIT" remote wd http://example.com:8080/repo
check remote-replaces 0 "" -- "$SUIT" remote wd https://example.com/repo
[ "$(wc -l < "$SUIT_HOME/remotes" | tr -d ' ')" = 1 ] && pass remote-replace-keeps-one-line || bad remote-replace-keeps-one-line
check remote-second-wardrobe 0 "" -- "$SUIT" remote aa http://h/p
[ "$(cut -d' ' -f1 "$SUIT_HOME/remotes" | tr '\n' ' ')" = "aa wd " ] && pass remotes-are-sorted-by-name || bad remotes-are-sorted-by-name "$(cat "$SUIT_HOME/remotes")"
check remote-clear 0 "" -- "$SUIT" remote wd --none
check remote-cleared-is-none 1 "no remote is set for wd" -- "$SUIT" remote wd
check remote-clear-of-none-is-fine 0 "" -- "$SUIT" remote wd --none
check remote-bad-name 2 "is not a wardrobe name" -- "$SUIT" remote 'bad name' http://h/p
check remote-bad-scheme 2 "starts with file://, http:// or https://" -- "$SUIT" remote wd ftp://h/p
check remote-relative-file 2 "needs an absolute path" -- "$SUIT" remote wd file://rel/x
check remote-file-query 2 "no query, fragment or % escape" -- "$SUIT" remote wd 'file:///a?b'
check remote-http-no-path 2 "http://HOST[:PORT]/PATH" -- "$SUIT" remote wd http://host
check remote-http-query 2 "no query, fragment or % escape" -- "$SUIT" remote wd 'http://host/a#b'
check remote-bad-host 2 "the host is letters" -- "$SUIT" remote wd 'http://ho_st/p'
check remote-empty-host 2 "the host is letters" -- "$SUIT" remote wd 'http://:80/p'
check remote-bad-port 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:0/p
check remote-port-too-big 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:65536/p
check remote-port-letters 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:8a/p
check remote-port-long 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:123456/p
check remote-port-empty 2 "the port is 1 to 65535" -- "$SUIT" remote wd http://host:/p
check remote-space 2 "printable characters only" -- "$SUIT" remote wd 'http://host/a b'
check remote-empty-url 2 "1 to 1024 characters" -- "$SUIT" remote wd ''
check remote-long-url 2 "1 to 1024 characters" -- "$SUIT" remote wd "http://h/$(printf 'a%.0s' $(seq 1 1100))"
check remote-user-in-address 2 "credentials do not go in the address" -- "$SUIT" remote wd http://alice@host/p
check remote-password-in-address 2 "credentials do not go in the address" -- "$SUIT" remote wd http://alice:hunter2xyz@host/p
check remote-password-in-https-address 2 "credentials do not go in the address" -- "$SUIT" remote wd https://alice:hunter2xyz@host/p
grep -q hunter2xyz "$T/out" "$T/err" "$SUIT_HOME/remotes" 2>/dev/null && bad address-password-never-echoed || pass address-password-never-echoed

# the remotes file: every strict error, with its line number
bad_remotes() {
    printf '%s' "$2" > "$SUIT_HOME/remotes"
    check "remotes-$1" 1 "remotes:$3" -- "$SUIT" remote wd
}
bad_remotes no-newline 'wd file:///a' "1: line has no newline"
bad_remotes one-field "wd
" "1: expected NAME URL"
bad_remotes extra-field "wd file:///a x
" "1: expected NAME URL"
bad_remotes bad-name "a/b file:///a
" "1: not a wardrobe name"
bad_remotes bad-url "wd ftp://x/y
" "1: an address starts with"
bad_remotes duplicate "wd file:///a
wd file:///b
" "2: duplicate remote for wd"
bad_remotes nul-byte "wd file:///a$(printf '\001')
" "1: an address has printable characters only"
printf 'wd file:///a\0b\n' > "$SUIT_HOME/remotes"
check remotes-nul-byte-in-line 1 "remotes:1: NUL byte in line" -- "$SUIT" remote wd
{ printf 'wd http://h/'; head -c 1400 /dev/zero | tr '\0' a; printf '\n'; } > "$SUIT_HOME/remotes"
check remotes-line-too-long 1 "remotes:1: line is over the limit" -- "$SUIT" remote wd
head -c 70000 /dev/zero | tr '\0' a > "$SUIT_HOME/remotes"
check remotes-file-too-big 1 "file is 65537 bytes, limit is 65536" -- "$SUIT" remote wd
: > "$SUIT_HOME/remotes"
for i in $(seq 1 256); do echo "w$i file:///a" ; done > "$SUIT_HOME/remotes"
check remotes-full-file-reads 0 "" -- "$SUIT" remote w256
echo "w257 file:///a" >> "$SUIT_HOME/remotes"
check remotes-too-many-in-file 1 "too many remotes (limit 256)" -- "$SUIT" remote wd
sed -i.bak '$d' "$SUIT_HOME/remotes"; rm "$SUIT_HOME/remotes.bak"
check remote-too-many-to-add 1 "too many remotes (limit 256)" -- "$SUIT" remote wd http://h/p
check remote-replace-when-full 0 "" -- "$SUIT" remote w1 http://h/p
: > "$SUIT_HOME/remotes"
for i in $(seq 1 64); do printf 'w%d http://h/%s\n' "$i" "$(head -c 1000 /dev/zero | tr '\0' a)"; done > "$SUIT_HOME/remotes"
check remote-file-too-big-to-write 1 "cannot write" -- "$SUIT" remote wd "http://h/$(head -c 1000 /dev/zero | tr '\0' b)"
check remote-open-fails 1 "cannot read: $EIO" -- env SUIT_FAULT=open:1 "$SUIT" remote wd
check remote-read-fails 1 "cannot read: $EIO" -- env SUIT_FAULT=read:1 "$SUIT" remote wd
check remote-write-fails 1 "cannot write $SUIT_HOME/remotes: $EIO" -- env SUIT_FAULT=rename:1 "$SUIT" remote wd http://h/p
check remote-no-home 1 "" -- env -u SUIT_HOME HOME= "$SUIT" remote wd
rm -f "$SUIT_HOME/remotes"

# ---- login and logout ---------------------------------------------------------

SECRET=s3cr3t-9f2k
CRED=$SUIT_HOME/credentials
rm -f "$CRED"
login() { printf '%s\n' "$2" | "$SUIT" login "$1" "$3"; }
checkl() { cn=$1; cw=$2; cm=$3; cs=$4; shift 4; printf '%s\n' "$cs" | "$@" >"$T/out" 2>"$T/err"; cr=$?
    if [ "$cr" != "$cw" ]; then bad "$cn" "exit $cr, want $cw: $(cat "$T/err")"
    elif [ -n "$cm" ] && ! grep -qF -- "$cm" "$T/err"; then bad "$cn" "want '$cm' in: $(cat "$T/err")"
    else pass "$cn"; fi; }
checkl login-writes-the-file 0 "" "$SECRET" "$SUIT" login wd alice
[ "$(cat "$CRED")" = "wd alice $SECRET" ] && pass credentials-is-one-line || bad credentials-is-one-line
[ "$(ls -l "$CRED" | cut -c1-10)" = "-rw-------" ] && pass credentials-is-mode-0600 || bad credentials-is-mode-0600 "$(ls -l "$CRED")"
rm "$CRED"
(umask 0; printf '%s\n' "$SECRET" | "$SUIT" login wd alice)
[ "$(ls -l "$CRED" | cut -c1-10)" = "-rw-------" ] && pass credentials-is-0600-under-any-umask || bad credentials-is-0600-under-any-umask
checkl login-replaces 0 "" "other-secret-1" "$SUIT" login wd bob
[ "$(cat "$CRED")" = "wd bob other-secret-1" ] && pass login-replaces-the-line || bad login-replaces-the-line
checkl login-second 0 "" "second-secret-2" "$SUIT" login aa carol
[ "$(cut -d' ' -f1,2 "$CRED" | tr '\n' ' ')" = "aa carol wd bob " ] && pass logins-are-sorted-by-name || bad logins-are-sorted-by-name
check logout 0 "" -- "$SUIT" logout wd
[ "$(cat "$CRED")" = "aa carol second-secret-2" ] && pass logout-removes-only-its-line || bad logout-removes-only-its-line
check logout-of-nothing 0 "" -- "$SUIT" logout wd
[ "$(cat "$CRED")" = "aa carol second-secret-2" ] && pass logout-of-nothing-changes-nothing || bad logout-of-nothing-changes-nothing
check logout-last 0 "" -- "$SUIT" logout aa
[ ! -s "$CRED" ] && [ "$(ls -l "$CRED" | cut -c1-10)" = "-rw-------" ] && pass logout-of-the-last-leaves-an-empty-private-file || bad logout-of-the-last-leaves-an-empty-private-file
printf 'nonl-secret' | "$SUIT" login wd alice
[ "$(cat "$CRED")" = "wd alice nonl-secret" ] && pass login-takes-a-last-line-without-newline || bad login-takes-a-last-line-without-newline
checkl login-empty-secret 2 "the secret is 1 to 256 printable characters, no space" "" "$SUIT" login wd alice
checkl login-secret-with-space 2 "the secret is 1 to 256" "two words" "$SUIT" login wd alice
checkl login-secret-with-control 2 "the secret is 1 to 256" "$(printf 'a\001b')" "$SUIT" login wd alice
checkl login-secret-too-long 1 "cannot read the secret" "$(head -c 300 /dev/zero | tr '\0' x)" "$SUIT" login wd alice
checkl login-secret-just-too-long-with-newline 2 "the secret is 1 to 256" "$(head -c 257 /dev/zero | tr '\0' x)" "$SUIT" login wd alice
checkl login-secret-longest 0 "" "$(head -c 256 /dev/zero | tr '\0' x)" "$SUIT" login wd alice
checkl login-bad-user 2 "not a user name" "$SECRET" "$SUIT" login wd 'a b'
checkl login-bad-name 2 "is not a wardrobe name" "$SECRET" "$SUIT" login 'a b' alice
check logout-bad-name 2 "is not a wardrobe name" -- "$SUIT" logout 'a b'
printf '%s\n' "$SECRET" | env SUIT_FAULT=read:1 "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "cannot read the secret" "$T/err" && pass login-stdin-read-fails || bad login-stdin-read-fails "$(cat "$T/err")"
printf '%s\n' "$SECRET" | env SUIT_FAULT=read:1:EINTR "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 0 ] && pass login-stdin-interrupted-retries || bad login-stdin-interrupted-retries "$(cat "$T/err")"
printf '%s\n' "$SECRET" | env SUIT_FAULT=rename:1 "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "cannot write $CRED: $EIO" "$T/err" && pass login-write-fails || bad login-write-fails "$(cat "$T/err")"
check logout-write-fails 1 "cannot write $CRED: $EIO" -- env SUIT_FAULT=rename:1 "$SUIT" logout wd
check logout-open-fails 1 "credentials:0: cannot read: $EIO" -- env SUIT_FAULT=open:1 "$SUIT" logout wd
check logout-stat-fails 1 "cannot look at it: $EIO" -- env SUIT_FAULT=stat:1 "$SUIT" logout wd
check logout-no-home 1 "" -- env -u SUIT_HOME HOME= "$SUIT" logout wd
printf '%s\n' "$SECRET" | env -u SUIT_HOME HOME= "$SUIT" login wd alice >/dev/null 2>&1; [ $? = 1 ] && pass login-no-home || bad login-no-home

# the credentials file: permissions and every strict error. The secret is
# never in a message.
printf 'wd alice %s\n' "$SECRET" > "$CRED"
for m in 640 604 660 666 644 620 602; do
    chmod $m "$CRED"
    printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"
    [ $? = 1 ] && grep -q "credentials:0: group or other can use it" "$T/err" && pass "login-refuses-mode-$m" || bad "login-refuses-mode-$m" "$(cat "$T/err")"
    check "logout-refuses-mode-$m" 1 "group or other can use it" -- "$SUIT" logout wd
done
[ "$(cat "$CRED")" = "wd alice $SECRET" ] && pass refused-login-leaves-the-file || bad refused-login-leaves-the-file
chmod 400 "$CRED"
checkl login-over-a-read-only-owner-file 0 "" "$SECRET" "$SUIT" login wd bob
[ "$(ls -l "$CRED" | cut -c1-10)" = "-r--------" ] && pass login-keeps-the-mode-it-found || bad login-keeps-the-mode-it-found "$(ls -l "$CRED")"
chmod 600 "$CRED"
rm "$CRED"; mkdir "$CRED"
checkl login-refuses-a-folder 1 "not a regular file" "$SECRET" "$SUIT" login wd alice
rmdir "$CRED"
bad_creds() {
    printf '%s' "$2" > "$CRED"; chmod 600 "$CRED"
    printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"
    [ $? = 1 ] && grep -q "credentials:$3" "$T/err" && pass "credentials-$1" || bad "credentials-$1" "$(cat "$T/err")"
    grep -q "$SECRET\|hunter2" "$T/out" "$T/err" && bad "credentials-$1-leaks" "$(cat "$T/err")"
}
bad_creds no-newline 'wd alice hunter2xx' "1: line has no newline"
bad_creds two-fields "wd alice
" "1: expected NAME USER SECRET"
bad_creds space-in-secret "wd alice hunter2 xx
" "1: expected NAME USER SECRET"
bad_creds bad-name "a/b alice hunter2xx
" "1: not a wardrobe name"
bad_creds bad-user "wd a@b hunter2xx
" "1: not a user name"
bad_creds control-in-secret "wd alice hunter$(printf '\001')2
" "1: the secret is 1 to 256"
bad_creds empty-secret "wd alice 
" "1: the secret is 1 to 256"
bad_creds four-fields "wd alice hunter2xx more
" "1: expected NAME USER SECRET"
bad_creds duplicate "wd alice hunter2xx
wd bob hunter3xx
" "2: duplicate login for wd"
printf 'wd alice hunter2\0xx\n' > "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "credentials:1: NUL byte in line" "$T/err" && pass credentials-nul-byte || bad credentials-nul-byte "$(cat "$T/err")"
{ printf 'wd alice '; head -c 1400 /dev/zero | tr '\0' a; printf '\n'; } > "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "credentials:1: line is over the limit" "$T/err" && pass credentials-line-too-long || bad credentials-line-too-long "$(cat "$T/err")"
head -c 70000 /dev/zero | tr '\0' a > "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "credentials:0: file is 65537 bytes" "$T/err" && pass credentials-file-too-big || bad credentials-file-too-big "$(cat "$T/err")"
for i in $(seq 1 256); do echo "w$i alice $SECRET"; done > "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login w1 bob >"$T/out" 2>"$T/err"; [ $? = 0 ] && pass login-replaces-in-a-full-file || bad login-replaces-in-a-full-file "$(cat "$T/err")"
printf '%s\n' "$SECRET" | "$SUIT" login new alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "too many logins (limit 256)" "$T/err" && pass login-too-many || bad login-too-many "$(cat "$T/err")"
echo "w257 alice $SECRET" >> "$CRED"
check logout-too-many-in-file 1 "credentials:257: too many logins (limit 256)" -- "$SUIT" logout w1
for i in $(seq 1 250); do printf 'w%d alice %s\n' "$i" "$(head -c 250 /dev/zero | tr '\0' k)"; done > "$CRED"
chmod 600 "$CRED"
[ "$(wc -c < "$CRED" | tr -d ' ')" = 65392 ] && pass the-big-credentials-file-reads-as-it-should || bad the-big-credentials-file-reads-as-it-should "$(wc -c < "$CRED")"
printf '%s\n' "$(head -c 250 /dev/zero | tr '\0' y)" | "$SUIT" login zz alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "cannot write $CRED: " "$T/err" && pass login-file-too-big-to-write || bad login-file-too-big-to-write "$(cat "$T/err")"
rm -f "$CRED"

# the last corners of the two parsers
check remote-port-below-digits 2 "the port is 1 to 65535" -- "$SUIT" remote wd 'http://host:8-/p'
check remote-non-ascii 2 "printable characters only" -- "$SUIT" remote wd "http://host/$(printf '\303\251')"
checkl login-secret-non-ascii 2 "the secret is 1 to 256" "$(printf 's\303\251')" "$SUIT" login wd alice
checkl login-user-too-long 2 "not a user name" "$SECRET" "$SUIT" login wd "$(head -c 65 /dev/zero | tr '\0' u)"
printf 'wd file:///a b c\n' > "$SUIT_HOME/remotes"
check remotes-four-fields 1 "remotes:1: expected NAME URL" -- "$SUIT" remote wd
printf 'wd alice sec ret more\n' > "$CRED"; chmod 600 "$CRED"
printf '%s\n' "$SECRET" | "$SUIT" login wd alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "credentials:1: expected NAME USER SECRET" "$T/err" && pass credentials-five-fields || bad credentials-five-fields "$(cat "$T/err")"
printf 'wd file:///a\n' > "$SUIT_HOME/remotes"
check remote-read-interrupted-retries 0 "" -- env SUIT_FAULT=read:1:EINTR "$SUIT" remote wd
rm -f "$SUIT_HOME/remotes"
# a credentials file that overflows with entries still to write
for i in $(seq 1 250); do printf 'w%d alice %s\n' "$i" "$(head -c 250 /dev/zero | tr '\0' k)"; done > "$CRED"
echo 'zzz u s' >> "$CRED"; chmod 600 "$CRED"
printf '%s\n' "$(head -c 250 /dev/zero | tr '\0' y)" | "$SUIT" login w1a alice >"$T/out" 2>"$T/err"; [ $? = 1 ] && grep -q "cannot write $CRED: " "$T/err" && pass login-overflows-with-entries-left || bad login-overflows-with-entries-left "$(cat "$T/err")"
rm -f "$CRED"

# wrong argument counts
check remote-with-no-name 2 "usage:" -- "$SUIT" remote
check remote-with-too-many 2 "usage:" -- "$SUIT" remote wd http://h/p extra
check login-with-no-user 2 "usage:" -- "$SUIT" login wd
check logout-with-no-name 2 "usage:" -- "$SUIT" logout
check sync-with-no-name 2 "usage:" -- "$SUIT" sync

# ---- sync over file:// ---------------------------------------------------------
# libfossil's file:// channel runs stock `fossil test-http`, so these need it.

if have_fossil; then
RT=$T/net
rm -rf "$RT"; mkdir -p "$RT"
newremote() { # the remote's repository: the fixture, with fossil's own background process off
    cp "$FIXTURE" "$RT/R.fossil"
    fossil settings backoffice-disable 1 -R "$RT/R.fossil" >/dev/null 2>&1
}
newremote
mach() { # mach NAME: a machine with its own home, the fixture wardrobe as wd, its store open
    SUIT_HOME=$RT/$1; export SUIT_HOME; S=$SUIT_HOME/store/wd
    rm -rf "$SUIT_HOME"; mkdir -p "$SUIT_HOME/wardrobes"
    cp "$FIXTURE" "$SUIT_HOME/wardrobes/wd.fossil"
    "$SUIT" store open wd >/dev/null 2>&1
    "$SUIT" remote wd "file://$RT/R.fossil"
}
on() { SUIT_HOME=$RT/$1; export SUIT_HOME; S=$SUIT_HOME/store/wd; }
leaves() { fossil leaves -R "$RT/R.fossil" | grep -c '^ *('; }

mach A
mach B
on A
check sync-with-nothing-to-do 0 "" -- "$SUIT" sync wd
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass sync-with-nothing-to-do-says-nothing || bad sync-with-nothing-to-do-says-nothing "$(cat "$T/out" "$T/err")"
printf 'one\n' > "$S/new.txt"
check tend-checks-in-then-syncs 0 "" -- "$SUIT" tend wd
grep -q '^checked in' "$T/out" && pass tend-still-checks-in || bad tend-still-checks-in "$(cat "$T/out")"
fossil cat new.txt -r tip -R "$RT/R.fossil" > "$T/got" 2>/dev/null; [ "$(cat "$T/got")" = one ] && pass tend-pushed-its-check-in || bad tend-pushed-its-check-in
on B
check sync-brings-the-working-copy-forward 0 "" -- "$SUIT" sync wd
grep -q '^updated to' "$T/out" && pass sync-says-it-updated || bad sync-says-it-updated "$(cat "$T/out")"
[ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/B/store/wd")" ] && pass two-machines-are-byte-identical || bad two-machines-are-byte-identical
check sync-again-is-quiet 0 "" -- "$SUIT" sync wd
[ ! -s "$T/out" ] && pass sync-again-says-nothing || bad sync-again-says-nothing "$(cat "$T/out")"
[ "$(leaves)" = 1 ] && pass remote-has-one-leaf || bad remote-has-one-leaf "$(leaves)"

# edits on both machines to different files merge cleanly
newremote; mach A; mach B
printf 'base\nmid\nend\n' > "$RT/A/store/wd/shared.txt"
on A; "$SUIT" tend wd >/dev/null 2>&1
on B; "$SUIT" sync wd >/dev/null 2>&1
echo 'a-only' > "$RT/A/store/wd/only-a.txt"
echo 'b-only' > "$RT/B/store/wd/only-b.txt"
on A; "$SUIT" tend wd >/dev/null 2>&1
printf 'alpha\n' > "$RT/B/machine"
on B; check tend-merges-a-fork 0 "" -- "$SUIT" tend wd
[ "$(leaves)" = 1 ] && pass clean-merge-leaves-one-leaf-on-the-remote || bad clean-merge-leaves-one-leaf-on-the-remote "$(leaves)"
fossil timeline -n 1 -R "$RT/R.fossil" | grep -q 'Merge edits from alpha' && pass merge-check-in-names-the-machine || bad merge-check-in-names-the-machine "$(fossil timeline -n 1 -R "$RT/R.fossil")"
[ -f "$RT/B/store/wd/only-a.txt" ] && [ -f "$RT/B/store/wd/only-b.txt" ] && pass merge-has-both-edits || bad merge-has-both-edits
on A; check sync-takes-the-merge 0 "" -- "$SUIT" sync wd
[ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/B/store/wd")" ] && pass merged-machines-are-byte-identical || bad merged-machines-are-byte-identical
newremote; mach A; mach B
on A; echo a1 > "$S/p.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo b1 > "$S/q.txt"; "$SUIT" commit wd -m local >/dev/null 2>&1
check sync-merges-without-a-machine-name 0 "" -- "$SUIT" sync wd
fossil timeline -n 1 -R "$RT/R.fossil" | grep -q 'Merge edits from this machine' && pass merge-without-a-machine-file-says-this-machine || bad merge-without-a-machine-file-says-this-machine
# the same edit made on both machines
newremote; mach A; mach B
on A; echo same > "$S/s.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo same > "$S/s.txt"; "$SUIT" commit wd -m local >/dev/null 2>&1
check sync-merges-identical-edits 0 "" -- "$SUIT" sync wd
[ "$(leaves)" = 2 ] && [ "$(cat "$RT/B/store/wd/s.txt")" = same ] && [ ! -e "$RT/B/wd.journal" ] && pass identical-edits-change-nothing-and-the-fork-stays-open || bad identical-edits-change-nothing-and-the-fork-stays-open "$(leaves)"

# edits to the same lines: nothing in the working copy changes, the attention
# file says so, and the local check-ins still reach the remote
base_pair() { # base_pair FILE...: both machines hold these files, checked in
    newremote
    mach A; mach B; on A
    for f in "$@"; do printf 'one\ntwo\nthree\n' > "$S/$f"; done
    "$SUIT" tend wd >/dev/null 2>&1; on B; "$SUIT" sync wd >/dev/null 2>&1
}
conflict_outcome() { # conflict_outcome NAME N: B syncs against a remote A has changed
    on B; before=$(tree "$RT/B/store/wd")
    check "$1-exits-13" 13 "" -- "$SUIT" sync wd
    [ "$(tree "$RT/B/store/wd")" = "$before" ] && pass "$1-changes-no-file" || bad "$1-changes-no-file"
    [ "$(cat "$RT/B/attention")" = "conflict wd: $2 files changed both here and on the remote" ] && pass "$1-writes-the-attention-line" || bad "$1-writes-the-attention-line" "$(cat "$RT/B/attention")"
    grep -rq '<<<<<<<\|>>>>>>>' "$RT/B/store/wd" && bad "$1-writes-no-marker" || pass "$1-writes-no-marker"
    [ "$(leaves)" = 2 ] && pass "$1-pushes-the-local-check-in" || bad "$1-pushes-the-local-check-in" "$(leaves)"
    "$SUIT" sync wd >/dev/null 2>&1; [ "$(grep -c '^conflict' "$RT/B/attention")" = 1 ] && pass "$1-attention-is-not-repeated" || bad "$1-attention-is-not-repeated"
}
base_pair c.txt d.txt
on A; printf 'one\nA\nthree\n' > "$S/c.txt"; printf 'one\nA\nthree\n' > "$S/d.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/c.txt"; printf 'one\nB\nthree\n' > "$S/d.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome same-lines 2
grep -q 'conflict c.txt' "$T/out" && pass conflict-names-the-file || bad conflict-names-the-file "$(cat "$T/out")"
base_pair c.txt
on A; rm "$S/c.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/c.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome edit-and-delete 1
base_pair
on A; printf 'a\000b\n' > "$S/bin.dat"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'a\000c\n' > "$S/bin.dat"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome added-both-sides-binary 1
base_pair bin.dat
on A; printf 'a\000b\n' > "$S/bin.dat"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'a\000c\n' > "$S/bin.dat"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome binary-edited-both-sides 1
base_pair
on A; echo from-a > "$S/clash.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo mine > "$S/mine.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1; echo untracked > "$S/clash.txt"
conflict_outcome added-over-an-untracked-file 1
[ "$(cat "$RT/B/store/wd/clash.txt")" = untracked ] && pass untracked-file-is-kept || bad untracked-file-is-kept

base_pair c.txt
on A; printf 'one\nA\nthree\n' > "$S/c.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; rm "$S/c.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
conflict_outcome delete-and-edit 1
base_pair c.txt d.txt
on A; rm "$S/c.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/d.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
check delete-there-and-edit-another-file-merges 0 "" -- "$SUIT" sync wd
[ ! -e "$RT/B/store/wd/c.txt" ] && [ "$(sed -n 2p "$RT/B/store/wd/d.txt")" = B ] && pass delete-and-edit-of-different-files-merge || bad delete-and-edit-of-different-files-merge
base_pair c.txt d.txt
on A; rm "$S/c.txt"; printf 'one\nA\nthree\n' > "$S/d.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/c.txt"; printf 'one\nB\nthree\n' > "$S/d.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
before=$(tree "$RT/B/store/wd")
"$SUIT" sync wd > "$T/out" 2>"$T/err"; [ $? = 13 ] && [ "$(grep -c '^conflict' "$T/out")" = 2 ] && grep -q '2 files changed both' "$RT/B/attention" && pass two-kinds-of-conflict-are-counted-together || bad two-kinds-of-conflict-are-counted-together "$(cat "$T/out")"
# a fork that does not conflict is merged even when the attention file holds an old conflict
base_pair c.txt
printf 'conflict wd: 1 files changed both here and on the remote\nlint other\n' > "$RT/B/attention"
on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo b > "$S/b.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
check sync-merges-a-fork-after-an-old-conflict 0 "" -- "$SUIT" sync wd
[ "$(cat "$RT/B/attention")" = "lint other" ] && pass old-conflict-line-is-cleared-by-the-merge || bad old-conflict-line-is-cleared-by-the-merge "$(cat "$RT/B/attention")"
printf 'conflict wd: 1 files changed both here and on the remote\n' > "$RT/B/attention"
check sync-with-no-fork-clears-the-old-conflict 0 "" -- "$SUIT" sync wd
[ ! -e "$RT/B/attention" ] && pass no-fork-clears-the-conflict-line || bad no-fork-clears-the-conflict-line
printf 'conflict wd: 1 files changed both here and on the remote\n' > "$RT/B/attention"
check sync-cannot-clear-the-old-conflict 1 "" -- env SUIT_FAULT=unlink:1 "$SUIT" sync wd
# local changes: the pull is done, nothing in the working copy changes
newremote; mach A; mach B; on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo mine > "$S/run.sh"; before=$(tree "$RT/B/store/wd")
check sync-with-local-changes 12 "local changes: run suit commit or wait for suit tend" -- "$SUIT" sync wd
[ "$(tree "$RT/B/store/wd")" = "$before" ] && pass sync-with-local-changes-changes-no-file || bad sync-with-local-changes-changes-no-file
fossil timeline -n 1 -R "$RT/B/wardrobes/wd.fossil" | grep -q 'Edits on this machine' && pass sync-with-local-changes-still-pulls || bad sync-with-local-changes-still-pulls "$(fossil timeline -n 2 -R "$RT/B/wardrobes/wd.fossil")"
[ "$(leaves)" = 1 ] && pass sync-with-local-changes-pushes-nothing || bad sync-with-local-changes-pushes-nothing

# a remote that cannot be used: the message names it, the store stays as it was
newremote; mach A; on A
echo kept > "$S/keep.txt"; before=$(tree "$S")
"$SUIT" remote wd "file://$RT/nope.fossil"
check sync-remote-file-missing 17 "sync wd: $RT/nope.fossil failed" -- "$SUIT" sync wd
echo junk > "$RT/junk.fossil"
"$SUIT" remote wd "file://$RT/junk.fossil"
check sync-remote-not-a-repository 17 "sync wd: $RT/junk.fossil failed" -- "$SUIT" sync wd
"$SUIT" remote wd http://127.0.0.1:1/r
check sync-remote-refuses-connection 17 "sync wd: 127.0.0.1:1 failed" -- "$SUIT" sync wd
"$SUIT" remote wd https://example.invalid/r
check sync-https-is-refused 18 "this build of suit cannot use https yet" -- "$SUIT" sync wd
[ "$(tree "$S")" = "$before" ] && [ ! -e "$RT/A/attention" ] && pass failed-syncs-leave-the-store-and-attention-alone || bad failed-syncs-leave-the-store-and-attention-alone
"$SUIT" remote wd --none
check sync-without-a-remote-is-quiet 0 "" -- "$SUIT" sync wd
"$SUIT" remote wd "file://$RT/R.fossil"
check sync-of-a-missing-wardrobe 1 "no wardrobe at" -- "$SUIT" sync nothere
printf 'wd file://\n' > "$RT/A/remotes"
check sync-with-a-bad-remotes-file 1 "remotes:1:" -- "$SUIT" sync wd
rm "$RT/A/remotes"
"$SUIT" remote wd "file://$RT/R.fossil"
printf 'wd alice %s\n' "$SECRET" > "$RT/A/credentials"; chmod 644 "$RT/A/credentials"
check sync-refuses-open-credentials 1 "group or other can use it" -- "$SUIT" sync wd
grep -q "$SECRET" "$T/out" "$T/err" && bad open-credentials-secret-not-printed || pass open-credentials-secret-not-printed
rm "$RT/A/credentials"
printf 'from 1\nto 2\n' > "$RT/A/wd.journal"
check sync-with-an-unfinished-update 15 "unfinished update" -- "$SUIT" sync wd
check tend-with-an-unfinished-update 15 "unfinished update" -- "$SUIT" tend wd
rm "$RT/A/wd.journal"
printf 'bad name!\n' > "$RT/A/machine"
newremote; mach A; mach B
on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; echo b > "$S/b.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1; printf 'bad name!\n' > "$RT/B/machine"
before=$(tree "$RT/B/store/wd")
check sync-with-a-bad-machine-file 1 "not a machine name" -- "$SUIT" sync wd
[ "$(tree "$RT/B/store/wd")" = "$before" ] && [ ! -e "$RT/B/wd.journal" ] && pass bad-machine-file-changes-nothing || bad bad-machine-file-changes-nothing
rm "$RT/B/machine"
# the attention file cannot be written when a conflict is found: exit 1, nothing changed
base_pair c.txt
on A; printf 'one\nA\nthree\n' > "$S/c.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; printf 'one\nB\nthree\n' > "$S/c.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
before=$(tree "$RT/B/store/wd")
check conflict-attention-write-fails 1 "" -- env SUIT_FAULT=rename:1 "$SUIT" sync wd
[ "$(tree "$RT/B/store/wd")" = "$before" ] && pass failed-attention-write-changes-no-file || bad failed-attention-write-changes-no-file

# every failed system call during a sync leaves the working copy whole: the
# files it had or the files it was going to have, never a mixture
sweep_fault() { # sweep_fault RT3:SCENARIO:FAULT,...: SCENARIO's setup in a private $RT, then calls 1 to 40 of each FAULT fail in turn
    # The private $RT is as deep and its name as long as $T/net, and the machines
    # and the remote are made in it, so the path the remote is recorded under is
    # the one it is read from: which step call number N falls in depends on both.
    RT=$T/${1%%:*}; swspec=${1#*:}; scen=${swspec%%:*}; swfaults=$(echo "${swspec#*:}" | tr , ' ')
    rm -rf "$RT"; mkdir -p "$RT"
    newremote; mach A; mach B
    on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
    if [ "$scen" = forked ]; then on B; echo b > "$S/b.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1; fi
    cp -R "$RT/B" "$RT/Bsnap"; cp "$RT/R.fossil" "$RT/Rsnap"
    on B; want_before=$(tree "$RT/B/store/wd")
    "$SUIT" sync wd >/dev/null 2>&1; want_after=$(tree "$RT/B/store/wd")
    sbad=""; shits=0
    for sname in $swfaults; do
        sn=1
        while [ $sn -le 40 ]; do
            rm -rf "$RT/B"; cp -R "$RT/Bsnap" "$RT/B"; cp "$RT/Rsnap" "$RT/R.fossil"
            SUIT_FAULT=$sname:$sn "$SUIT" sync wd >/dev/null 2>&1; src=$?
            [ -e "$RT/B/wd.journal" ] && { "$SUIT" store repair wd >/dev/null 2>&1 || sbad="$sbad repair-$sname-$sn"; }
            now=$(tree "$RT/B/store/wd")
            if [ "$src" != 0 ]; then
                shits=$((shits + 1))
                { [ "$now" = "$want_before" ] || [ "$now" = "$want_after" ]; } || sbad="$sbad mixed-$sname-$sn"
                [ -z "$("$SUIT" store status wd 2>&1)" ] || sbad="$sbad dirty-$sname-$sn"
            fi
            sn=$((sn + 1))
        done
    done
    echo "$shits $sbad"
}
sweep() { # sweep SCENARIO (behind or forked): try every fault; side by side, one worker per fault
    sw_kind=$(echo "$1" | cut -c1); sw_all=rename,write,open,read,unlink,mkdir,fsync,stat
    if [ "${TEST_JOBS:-1}" -le 1 ]; then sw_list="${sw_kind}00:$1:$sw_all"
    else
        sw_list=; sw_i=0
        for sw_f in $(echo "$sw_all" | tr , ' '); do
            sw_i=$((sw_i + 1)); sw_list="$sw_list ${sw_kind}0$sw_i:$1:$sw_f"
        done
    fi
    # shellcheck disable=SC2086
    fan sweep_fault $sw_list
    sbad=""; shits=0
    for sw_w in $sw_list; do
        if read -r sh_n sh_bad <"$T/fan/sweep_fault.$sw_w" && [ -n "$sh_n" ]; then
            shits=$((shits + sh_n)); sbad="$sbad${sh_bad:+ $sh_bad}"
        else sbad="$sbad worker-$sw_w-gave-no-result"; fi
        rm -rf "$T/${sw_w%%:*}"
    done
    [ -z "$sbad" ] && [ "$shits" -gt 0 ] && pass "sweep-$1-leaves-the-working-copy-whole ($shits failures)" || bad "sweep-$1" "hits $shits:$sbad"
}
sweep behind
sweep forked

behind() { # what a clone of $1 left in $SUIT_HOME
    ls "$SUIT_HOME/wardrobes" 2>/dev/null | grep -F -- "$1"
    [ -e "$SUIT_HOME/store/$1" ] && echo "store/$1"
    grep -s "^$1 " "$SUIT_HOME/remotes"
}
nothing_behind() { [ -z "$(behind "$1")" ] && pass "$2" || bad "$2" "left: $(behind "$1" | tr '\n' ' ')"; }
newmachine() { SUIT_HOME=$RT/$1; export SUIT_HOME; S=$SUIT_HOME/store/wd; rm -rf "$SUIT_HOME"; }

if command -v nc >/dev/null 2>&1; then
# http:// against a loopback fossil server with a login
newremote; mach A
cp "$RT/R.fossil" "$RT/S.fossil"
fossil user new alice contact "$SECRET" -R "$RT/S.fossil" >/dev/null 2>&1
fossil user capabilities alice oir -R "$RT/S.fossil" >/dev/null 2>&1
fossil settings backoffice-disable 1 -R "$RT/S.fossil" >/dev/null 2>&1
PORT=
for try in 1 2 3 4 5 6 7 8; do
    p=$(awk 'BEGIN { srand(); print 20000 + int(rand() * 30000) + '$try' * 7 }')
    nc -z 127.0.0.1 "$p" >/dev/null 2>&1 && continue
    fossil server "$RT/S.fossil" --port "$p" --localhost >"$RT/server.log" 2>&1 &
    SERVER=$!
    ( sleep 240; kill $SERVER 2>/dev/null ) >/dev/null 2>&1 &
    trap 'kill $SERVER 2>/dev/null; rm -rf "$T"' EXIT INT TERM
    i=0; while [ $i -lt 50 ] && ! nc -z 127.0.0.1 "$p" >/dev/null 2>&1; do i=$((i+1)); sleep 0.2; done
    kill -0 $SERVER 2>/dev/null && nc -z 127.0.0.1 "$p" >/dev/null 2>&1 && { PORT=$p; break; }
done
[ -n "$PORT" ] || bad http-server-did-not-start "$(cat "$RT/server.log")"
on A; echo web > "$S/web.txt"; "$SUIT" commit wd -m web >/dev/null 2>&1
"$SUIT" remote wd "http://127.0.0.1:$PORT/"
printf '%s\n' "wrong-secret-1" | "$SUIT" login wd alice
check http-wrong-password-is-refused 19 "sync wd: 127.0.0.1:$PORT failed" -- "$SUIT" sync wd
grep -q "wrong-secret-1" "$T/out" "$T/err" && bad wrong-secret-not-printed || pass wrong-secret-not-printed
"$SUIT" logout wd
check http-without-a-login-is-refused 19 "" -- "$SUIT" sync wd
printf '%s\n' "$SECRET" | "$SUIT" login wd alice
check http-sync-with-a-login 0 "" -- "$SUIT" sync wd
fossil cat web.txt -r tip -R "$RT/S.fossil" > "$T/got" 2>/dev/null; [ "$(cat "$T/got")" = web ] && pass http-push-reached-the-server || bad http-push-reached-the-server
for f in "$RT/A/remotes" "$RT/A/attention" "$RT/server.log"; do [ -e "$f" ] && grep -q "$SECRET" "$f" && bad "secret-not-in-$(basename "$f")"; done
grep -rl "$SECRET" "$RT/A" "$T/out" "$T/err" | grep -v '/credentials$' | grep -q . && bad secret-only-in-the-credentials-file || pass secret-only-in-the-credentials-file
# the server is made private: nobody may clone or pull without the login
fossil user capabilities alice oirg -R "$RT/S.fossil" >/dev/null 2>&1
fossil user capabilities nobody "" -R "$RT/S.fossil" >/dev/null 2>&1
fossil user capabilities anonymous "" -R "$RT/S.fossil" >/dev/null 2>&1
# clone of a wardrobe that needs a login, over http
newmachine H
check http-clone-without-a-login-is-refused 19 "clone wd: 127.0.0.1:$PORT failed" -- "$SUIT" clone wd "http://127.0.0.1:$PORT/"
nothing_behind wd http-refused-clone-leaves-nothing
printf '%s\n' "wrong-secret-1" | "$SUIT" login wd alice
check http-clone-with-the-wrong-password-is-refused 19 "" -- "$SUIT" clone wd "http://127.0.0.1:$PORT/"
grep -q "wrong-secret-1" "$T/out" "$T/err" && bad clone-wrong-secret-not-printed || pass clone-wrong-secret-not-printed
nothing_behind wd http-wrong-password-clone-leaves-nothing
printf '%s\n' "$SECRET" | "$SUIT" login wd alice
check http-clone-with-a-login 0 "" -- "$SUIT" clone wd "http://127.0.0.1:$PORT/"
[ "$(tree "$RT/H/store/wd")" = "$(tree "$RT/A/store/wd")" ] && [ -f "$RT/H/store/wd/web.txt" ] && pass http-clone-is-byte-identical || bad http-clone-is-byte-identical
[ "$(cat "$RT/H/remotes")" = "wd http://127.0.0.1:$PORT/" ] && pass http-clone-remote-has-no-login || bad http-clone-remote-has-no-login "$(cat "$RT/H/remotes")"
grep -rl "$SECRET" "$RT/H" "$T/out" "$T/err" | grep -v '/credentials$' | grep -q . && bad clone-secret-only-in-the-credentials-file || pass clone-secret-only-in-the-credentials-file
echo more > "$RT/H/store/wd/more.txt"
check http-tend-after-clone 0 "" -- "$SUIT" tend wd
fossil cat more.txt -r tip -R "$RT/S.fossil" > "$T/got" 2>/dev/null; [ "$(cat "$T/got")" = more ] && pass http-tend-after-clone-pushed || bad http-tend-after-clone-pushed
# a refused login counts as a failed sync
printf '%s\n' "wrong-secret-1" | "$SUIT" login wd alice
for i in 1 2 3; do "$SUIT" tend wd >"$T/out" 2>"$T/err"; r=$?; done
[ $r = 19 ] && [ "$(cat "$RT/H/wd.syncfail")" = 3 ] && grep -q "^sync wd: failing since 3 tries: 127.0.0.1:$PORT\$" "$RT/H/attention" && pass refused-login-counts-as-a-failed-sync || bad refused-login-counts-as-a-failed-sync "$r $(cat "$RT/H/attention")"
grep -q "wrong-secret-1" "$RT/H/attention" "$RT/H/wd.syncfail" && bad failing-line-has-no-secret || pass failing-line-has-no-secret
kill $SERVER 2>/dev/null
else
    skip http-cases "nc is not installed"
fi

# a login kept for a file:// remote is not used
newremote; mach A; mach B
printf '%s\n' "$SECRET" | "$SUIT" login wd alice
on A; echo a > "$S/a.txt"; "$SUIT" commit wd -m a >/dev/null 2>&1
SUIT_HOME=$RT/A; export SUIT_HOME; printf '%s\n' "$SECRET" | "$SUIT" login wd alice
check sync-file-remote-ignores-the-login 0 "" -- "$SUIT" sync wd
# a file deleted here and untouched there merges cleanly
base_pair c.txt d.txt
on A; printf 'one\nA\nthree\n' > "$S/d.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; rm "$S/c.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
check delete-here-and-edit-another-file-merges 0 "" -- "$SUIT" sync wd
[ ! -e "$RT/B/store/wd/c.txt" ] && [ "$(sed -n 2p "$RT/B/store/wd/d.txt")" = A ] && pass delete-here-merges-with-the-other-edit || bad delete-here-merges-with-the-other-edit

# both machines deleted the same file and edited different ones
base_pair c.txt
on A; rm "$S/c.txt"; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
on B; rm "$S/c.txt"; echo b > "$S/b.txt"; "$SUIT" commit wd -m b >/dev/null 2>&1
check both-delete-the-same-file-and-merge 0 "" -- "$SUIT" sync wd
[ ! -e "$RT/B/store/wd/c.txt" ] && [ -f "$RT/B/store/wd/a.txt" ] && pass both-deleted-file-stays-deleted || bad both-deleted-file-stays-deleted


# ---- clone -------------------------------------------------------------------------
# Machine A has the wardrobe and a remote; machine M gets it with suit clone.

newremote; mach A
on A; echo a > "$S/a.txt"; "$SUIT" tend wd >/dev/null 2>&1
newmachine M
check clone-over-file 0 "" -- "$SUIT" clone wd "file://$RT/R.fossil"
[ "$(cat "$T/out")" = "cloned wd" ] && pass clone-says-it-cloned || bad clone-says-it-cloned "$(cat "$T/out")"
[ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/M/store/wd")" ] && [ -f "$RT/M/store/wd/a.txt" ] && pass clone-working-copy-is-byte-identical || bad clone-working-copy-is-byte-identical
[ "$(cat "$RT/M/remotes")" = "wd file://$RT/R.fossil" ] && pass clone-records-the-remote || bad clone-records-the-remote "$(cat "$RT/M/remotes")"
[ "$(ls "$RT/M/wardrobes")" = wd.fossil ] && pass clone-leaves-only-the-repository || bad clone-leaves-only-the-repository "$(ls "$RT/M/wardrobes")"
check clone-store-is-clean 0 "" -- "$SUIT" store status wd
[ ! -s "$T/out" ] && pass clone-store-status-is-empty || bad clone-store-status-is-empty "$(cat "$T/out")"
check clone-sync-has-nothing-to-do 0 "" -- "$SUIT" sync wd
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass clone-sync-is-quiet || bad clone-sync-is-quiet "$(cat "$T/out" "$T/err")"

# an edit on the clone reaches A through two syncs
on M; echo b > "$S/b.txt"
check clone-edit-reaches-the-remote 0 "" -- "$SUIT" tend wd
on A
check clone-edit-reaches-the-other-machine 0 "" -- "$SUIT" sync wd
[ "$(cat "$RT/A/store/wd/b.txt")" = b ] && [ "$(tree "$RT/A/store/wd")" = "$(tree "$RT/M/store/wd")" ] && pass clone-edit-arrived-byte-identical || bad clone-edit-arrived-byte-identical

# refusals
on M; before=$(tree "$S"); sum=$(cksum < "$SUIT_HOME/wardrobes/wd.fossil")
check clone-refuses-an-existing-wardrobe 20 "there is already a wardrobe or a store of that name here" -- "$SUIT" clone wd "file://$RT/R.fossil"
[ "$(tree "$S")" = "$before" ] && [ "$(cksum < "$SUIT_HOME/wardrobes/wd.fossil")" = "$sum" ] && pass clone-never-overwrites || bad clone-never-overwrites
mkdir -p "$SUIT_HOME/store/onlystore"
check clone-refuses-an-existing-store 20 "already a wardrobe or a store" -- "$SUIT" clone onlystore "file://$RT/R.fossil"
[ -z "$(ls "$SUIT_HOME/wardrobes" | grep onlystore)" ] && pass clone-existing-store-gets-no-repository || bad clone-existing-store-gets-no-repository
rmdir "$SUIT_HOME/store/onlystore"
newmachine N
check clone-bad-name 2 "is not a wardrobe name" -- "$SUIT" clone 'bad/name' "file://$RT/R.fossil"
check clone-relative-file 2 "needs an absolute path" -- "$SUIT" clone x file://rel/x
check clone-bad-scheme 2 "starts with file://, http:// or https://" -- "$SUIT" clone x ftp://h/p
check clone-user-in-address 2 "credentials do not go in the address" -- "$SUIT" clone x http://alice@h/p
check clone-password-in-address 2 "credentials do not go in the address" -- "$SUIT" clone x http://alice:hunter2xyz@h/p
grep -q hunter2xyz "$T/err" && bad clone-does-not-repeat-the-password || pass clone-does-not-repeat-the-password
check clone-https-is-refused 18 "this build of suit cannot use https yet" -- "$SUIT" clone x https://example.invalid/r
check clone-remote-file-missing 17 "clone x: $RT/nope.fossil failed" -- "$SUIT" clone x "file://$RT/nope.fossil"
echo junk > "$RT/junk.fossil"
check clone-remote-not-a-repository 17 "clone x: $RT/junk.fossil failed" -- "$SUIT" clone x "file://$RT/junk.fossil"
check clone-remote-refuses-connection 17 "clone x: 127.0.0.1:1 failed" -- "$SUIT" clone x http://127.0.0.1:1/r
nothing_behind x clone-refusals-leave-nothing-behind
[ ! -e "$RT/N/remotes" ] && pass clone-refusals-write-no-remotes-file || bad clone-refusals-write-no-remotes-file
check clone-without-a-home 1 "" -- env -u SUIT_HOME HOME= "$SUIT" clone x "file://$RT/R.fossil"
check clone-with-no-url 2 "usage:" -- "$SUIT" clone x

# every failed system call during a clone leaves nothing behind; a call that
# does not matter leaves the whole clone
clone_fault() { # clone_fault FAULT: calls 1, 2, ... of FAULT fail in turn, on a machine of its own
    fname=$1; cm=F.$1
    n=1; quiet=0; failures=0; badstate=
    while [ $n -le 80 ] && [ $quiet -lt 3 ]; do
        newmachine "$cm"
        env SUIT_FAULT=$fname:$n "$SUIT" clone wd "file://$RT/R.fossil" >"$T/out.$cm" 2>"$T/err.$cm"; rc=$?
        if [ $rc = 0 ]; then
            quiet=$((quiet + 1))
            [ "$(tree "$SUIT_HOME/store/wd")" = "$(tree "$RT/A/store/wd")" ] && [ -n "$(grep '^wd ' "$SUIT_HOME/remotes")" ] || badstate="$badstate $fname:$n-incomplete"
        else
            quiet=0; failures=$((failures + 1))
            [ -z "$(behind wd)" ] || badstate="$badstate $fname:$n-left:$(behind wd | tr '\n' ,)"
        fi
        n=$((n + 1))
    done
    [ -z "$badstate" ] && pass "clone-fault-$fname-is-clean-$failures-failures" || bad "clone-fault-$fname" "$badstate"
}
clone_faults="open read write close fsync stat fstatat rename mkdir unlink lstat listdir rmdir spawn wait4 getenv getcwd"
fan clone_fault $clone_faults
fan_show clone_fault $clone_faults
newmachine F
check clone-store-fault-says-what 1 "" -- env SUIT_FAULT=mkdir:3 "$SUIT" clone wd "file://$RT/R.fossil"
nothing_behind wd clone-store-fault-leaves-nothing

# ---- tend with no name ---------------------------------------------------------------
mkw() { # mkw NAME: wardrobe NAME in the current home, its store open, no remote
    cp "$FIXTURE" "$SUIT_HOME/wardrobes/$1.fossil"; "$SUIT" store open "$1" >/dev/null 2>&1
}
SUIT_HOME=$RT/T0; export SUIT_HOME; rm -rf "$SUIT_HOME"
check tend-all-with-no-home-folder 0 "" -- "$SUIT" tend
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass tend-all-with-no-wardrobes-says-nothing || bad tend-all-with-no-wardrobes-says-nothing "$(cat "$T/out" "$T/err")"
mkdir -p "$SUIT_HOME/wardrobes"
check tend-all-with-an-empty-folder 0 "" -- "$SUIT" tend
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass tend-all-with-an-empty-folder-says-nothing || bad tend-all-with-an-empty-folder-says-nothing "$(cat "$T/out" "$T/err")"
check tend-all-without-a-home 1 "" -- env -u SUIT_HOME HOME= "$SUIT" tend
check tend-all-cannot-list 1 "cannot list $SUIT_HOME/wardrobes: $EIO" -- env SUIT_FAULT=listdir:1 "$SUIT" tend
check tend-with-two-names 2 "usage:" -- "$SUIT" tend a b
# files that are not wardrobes are left alone
: > "$SUIT_HOME/wardrobes/notes.txt"; : > "$SUIT_HOME/wardrobes/.fossil"; : > "$SUIT_HOME/wardrobes/bad name.fossil"
: > "$SUIT_HOME/wardrobes/$(printf 'n%.0s' $(seq 1 129)).fossil"; : > "$SUIT_HOME/wardrobes/x.fossil.clone"; : > "$SUIT_HOME/wardrobes/fossil"
check tend-all-skips-what-is-not-a-wardrobe 0 "" -- "$SUIT" tend
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass tend-all-skips-quietly || bad tend-all-skips-quietly "$(cat "$T/out" "$T/err")"
rm -f "$SUIT_HOME"/wardrobes/*

# one wardrobe
mkw one
check tend-all-with-one-clean-wardrobe 0 "" -- "$SUIT" tend
[ ! -s "$T/out" ] && [ ! -s "$T/err" ] && pass tend-all-one-clean-says-nothing || bad tend-all-one-clean-says-nothing "$(cat "$T/out" "$T/err")"
echo x > "$SUIT_HOME/store/one/new.txt"
check tend-all-checks-in 0 "" -- "$SUIT" tend
grep -q '^checked in' "$T/out" && pass tend-all-says-it-checked-in || bad tend-all-says-it-checked-in "$(cat "$T/out")"

# three wardrobes; the middle one fails its lint, the others are still tended
rm -rf "$SUIT_HOME"; mkdir -p "$SUIT_HOME/wardrobes"
mkw cc; mkw aa; mkw bb
for w in aa bb cc; do echo "$w" > "$SUIT_HOME/store/$w/edit.txt"; done
printf 'token = abcdefghijklmnopqrstuvwxyz0123456789\n' > "$SUIT_HOME/store/bb/bad.txt"
"$SUIT" tend > "$T/out" 2> "$T/err"; rc=$?
[ $rc = 3 ] && pass tend-all-exits-with-the-failure || bad tend-all-exits-with-the-failure "exit $rc"
[ "$(grep -c '^suit: tend .*: did not end clean' "$T/err")" = 1 ] && grep -q '^suit: tend bb: did not end clean, exit 3$' "$T/err" && pass tend-all-names-the-wardrobe-that-failed || bad tend-all-names-the-wardrobe-that-failed "$(cat "$T/err")"
[ "$(grep -c '^checked in' "$T/out")" = 2 ] && pass tend-all-checked-in-the-others || bad tend-all-checked-in-the-others "$(cat "$T/out")"
for w in aa cc; do "$SUIT" store status $w > "$T/st"; [ ! -s "$T/st" ] || bad "tend-all-$w-is-clean" "$(cat "$T/st")"; done
"$SUIT" store status bb | grep -q 'bad.txt' && grep -q '^lint bb' "$SUIT_HOME/attention" && pass tend-all-leaves-the-lint-for-bb || bad tend-all-leaves-the-lint-for-bb
# the highest code wins, and lines come in name order
rm "$SUIT_HOME/store/bb/bad.txt"; echo again > "$SUIT_HOME/store/aa/more.txt"
printf 'token = abcdefghijklmnopqrstuvwxyz0123456789\n' > "$SUIT_HOME/store/aa/bad.txt"
"$SUIT" remote bb http://127.0.0.1:1/r; "$SUIT" remote cc https://example.invalid/r
"$SUIT" tend > "$T/out" 2> "$T/err"; rc=$?
[ $rc = 18 ] && pass tend-all-exits-with-the-highest-code || bad tend-all-exits-with-the-highest-code "exit $rc"
grep '^suit: tend ' "$T/err" | tr '\n' '|' > "$T/lines"
[ "$(cat "$T/lines")" = "suit: tend aa: did not end clean, exit 3|suit: tend bb: did not end clean, exit 17|suit: tend cc: did not end clean, exit 18|" ] && pass tend-all-reports-in-name-order || bad tend-all-reports-in-name-order "$(cat "$T/lines")"

# too many wardrobes
rm -rf "$SUIT_HOME"; mkdir -p "$SUIT_HOME/wardrobes"
for i in $(seq 1 1025); do : > "$SUIT_HOME/wardrobes/w$i.fossil"; done
check tend-all-refuses-too-many 1 "more than 1024 wardrobes" -- "$SUIT" tend

# a clone that fails after the store is open takes it all away again, even when
# the rollback itself cannot look at a file
for n in 1 2 3 4 5 6 7 8 9 10; do
    newmachine F
    env SUIT_FAULT=rename:$n,lstat:1 "$SUIT" clone wd "file://$RT/R.fossil" >"$T/out" 2>"$T/err"; rc=$?
    [ $rc -lt 99 ] || bad "clone-fault-rename-$n-and-lstat" "exit $rc"
done
pass clone-rollback-survives-lstat-failures

# ---- repeated sync failures ---------------------------------------------------------
newremote; mach A
CNT=$RT/A/wd.syncfail; ATT=$RT/A/attention
"$SUIT" remote wd http://127.0.0.1:1/r
check failed-sync-1 17 "" -- "$SUIT" tend wd
[ "$(cat "$CNT")" = 1 ] && [ ! -e "$ATT" ] && pass first-failure-is-counted-not-reported || bad first-failure-is-counted-not-reported "$(cat "$CNT") $(cat "$ATT" 2>&1)"
check failed-sync-2 17 "" -- "$SUIT" tend wd
[ "$(cat "$CNT")" = 2 ] && [ ! -e "$ATT" ] && pass second-failure-is-counted-not-reported || bad second-failure-is-counted-not-reported
check failed-sync-3 17 "" -- "$SUIT" tend wd
[ "$(cat "$ATT")" = "sync wd: failing since 3 tries: 127.0.0.1:1" ] && pass third-failure-reaches-the-attention-file || bad third-failure-reaches-the-attention-file "$(cat "$ATT" 2>&1)"
check failed-sync-4 17 "" -- "$SUIT" tend wd
[ "$(cat "$ATT")" = "sync wd: failing since 4 tries: 127.0.0.1:1" ] && [ "$(cat "$CNT")" = 4 ] && pass later-failures-update-the-line || bad later-failures-update-the-line "$(cat "$ATT" 2>&1)"
# other kinds of item stay
printf 'lint other\n  x:1: y\n' >> "$ATT"
"$SUIT" tend wd >/dev/null 2>&1
grep -q '^lint other' "$ATT" && grep -q 'failing since 5 tries' "$ATT" && pass failing-line-keeps-other-items || bad failing-line-keeps-other-items "$(cat "$ATT")"
# a sync that reaches the remote clears the count and the line
"$SUIT" remote wd "file://$RT/R.fossil"
check success-after-failures 0 "" -- "$SUIT" tend wd
[ ! -e "$CNT" ] && ! grep -q '^sync wd' "$ATT" && grep -q '^lint other' "$ATT" && pass success-clears-the-count-and-the-line || bad success-clears-the-count-and-the-line "$(cat "$ATT" 2>&1)"
check success-again-is-quiet 0 "" -- "$SUIT" tend wd
[ ! -e "$CNT" ] && pass nothing-to-clear-writes-nothing || bad nothing-to-clear-writes-nothing
# an https remote counts too
"$SUIT" remote wd https://example.invalid/r
check https-failure-is-counted 18 "" -- "$SUIT" tend wd
[ "$(cat "$CNT")" = 1 ] && pass https-failure-counts || bad https-failure-counts "$(cat "$CNT")"
# a sync that stops at local changes reached the remote
"$SUIT" remote wd "file://$RT/R.fossil"
check count-cleared-by-a-reachable-remote 0 "" -- "$SUIT" tend wd
[ ! -e "$CNT" ] && pass reachable-remote-clears-the-count || bad reachable-remote-clears-the-count
# the count stops at its limit
printf '999999\n' > "$CNT"; "$SUIT" remote wd http://127.0.0.1:1/r
check count-stops-at-the-limit 17 "" -- "$SUIT" tend wd
[ "$(cat "$CNT")" = 999999 ] && grep -q 'failing since 999999 tries' "$ATT" && pass count-saturates || bad count-saturates "$(cat "$CNT")"
# a count file that is not a count
"$SUIT" remote wd "file://$RT/R.fossil"
for val in '0' '' '1234567' 'x' '3' '01
' '1x
' '12
3
'; do
    printf '%s' "$val" > "$CNT"
    "$SUIT" tend wd >"$T/out" 2>"$T/err"; rc=$?
    [ $rc = 1 ] && grep -q "$CNT: not a count of failed syncs" "$T/err" && pass "bad-count-file-$(printf '%s' "$val" | tr -c 'a-z0-9' _)" || bad "bad-count-file" "exit $rc $(cat "$T/err")"
done
rm -f "$CNT"

hunt() { # hunt NAME WANT_RC WANT_MSG FAULT SETUP COMMAND...: the first call of FAULT's kind that gives both
    hn=$1; hrc=$2; hmsg=$3; hf=$4; hsetup=$5; shift 5; k=1
    while [ $k -le 80 ]; do
        eval "$hsetup"
        env SUIT_FAULT=$hf:$k "$@" >"$T/out" 2>"$T/err"; r=$?
        if [ "$r" = "$hrc" ] && grep -qF -- "$hmsg" "$T/err"; then pass "$hn"; return; fi
        k=$((k + 1))
    done
    bad "$hn" "never saw exit $hrc with '$hmsg'"
}
hunt count-file-unreadable 1 "$CNT: cannot read: $EIO" read 'printf "2\n" > "$CNT"' "$SUIT" tend wd
"$SUIT" remote wd http://127.0.0.1:1/r
hunt count-file-unwritable 17 "cannot write $CNT: $EIO" rename 'rm -f "$CNT"' "$SUIT" tend wd
"$SUIT" remote wd http://127.0.0.1:1/r
hunt remotes-unreadable-after-the-failure 17 "remotes:0: cannot read: $EIO" open 'printf "2\n" > "$CNT"' "$SUIT" tend wd
"$SUIT" remote wd "file://$RT/R.fossil"
hunt count-file-unremovable 1 "cannot remove $CNT: $EIO" unlink 'printf "2\n" > "$CNT"' "$SUIT" tend wd
rm -f "$CNT"
fi # end sync

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