#!/usr/bin/env bash
# Acceptance checks 2 to 7 and 9 of CARD.md, run on a real git repository (a
# copy of this source) in a throwaway HOME, never on anyone's own directories.
# Linux, as a normal user. From the project folder: bash test/e2e.sh
set -u
export LC_ALL=C
umask 022
cd "$(dirname "$0")/.."
SRC=$PWD
BIN=$(mktemp -d)
CGO_ENABLED=0 go build -o "$BIN/fallow" . || exit 1
export PATH="$BIN:$PATH"
[ "$(id -u)" != 0 ] || { echo "run as a normal user: root ignores permission bits" >&2; exit 1; }

W=$(mktemp -d) # saved copies and command output
export HOME=$(mktemp -d)
OUT=$(mktemp -d); echo hi > $OUT/outside.txt
F=$(mktemp -d)/field; mkdir -p $F/docs
cp -R $SRC/go.mod $SRC/*.go $SRC/README.md $SRC/CARD.md $SRC/test $F/
printf '#!/bin/sh\necho ok\n' > $F/run.sh; chmod 755 $F/run.sh
echo notes > $F/docs/notes.md; ln -s $OUT/outside.txt $F/link
git -C $F init -q && git -C $F add -A && git -C $F -c user.name=t -c user.email=t@t commit -qm fixture
find $F ! -type l -printf '%m %P\n' | sort > $W/before.modes
find $F ! -type l -printf '%T@ %P\n' | sort > $W/before.mtimes
(cd $F && find . -type f ! -path './.git/*' | sort | xargs sha256sum) > $W/before.sums
BOOK=$HOME/.fallow-book
RF=$(realpath $F)
echo "fixture: $(find $F | wc -l) entries in $RF, $(git -C $F log --oneline | wc -l) commit, book at $BOOK"

pass=0; fails=0
t() { # description, then a test command
  local d=$1; shift
  if "$@"; then pass=$((pass + 1)); echo "  ok  $d"; else fails=$((fails + 1)); echo "  FAIL  $d"; fi
}
x() { # run a command, keep stdout in $W/o, stderr in $W/e and the status in $rc, and show all three
  echo; echo "\$ $*"
  "$@" > $W/o 2> $W/e; rc=$?
  sed 's/^/  | /' $W/o; sed 's/^/  ! /' $W/e; echo "  exit $rc"
}
writable() { find $F ! -type l -perm /222 | wc -l; }
modes() { find $F ! -type l -printf '%m %P\n' | sort; }
booksum() { sha256sum < $BOOK; }
last_entry() { awk '/^entry /{b=""} {b=b $0 "\n"} END{printf "%s", b}' $BOOK; }

echo; echo "== 2. Rest, end to end, on the real repository"
A=$(find $F | wc -l); B=$(writable)
x env FALLOW_TODAY=2026-10-13 fallow rest $F --seasons 1
t "exit 0" [ $rc = 0 ]
t "stderr first line names FALLOW_TODAY" [ "$(head -n 1 $W/e)" = "Today is taken to be 2026-10-13 (FALLOW_TODAY)." ]
t "Ploughing from 25 Mar 2027." grep -qF "Ploughing from 25 Mar 2027." $W/o
t "'$A entries, $B locked.' (find before the rest)" grep -qxF "  $A entries, $B locked." $W/o
t "no write bit left: $(writable)" [ "$(writable)" = 0 ]
t "echo x >> run.sh fails" eval "! (echo x >> $F/run.sh) 2>/dev/null"
t "rm docs/notes.md fails" eval "! rm -f $F/docs/notes.md 2>/dev/null"
t "cat run.sh works" eval "cat $F/run.sh > /dev/null"
t "git log works, one commit" [ "$(git -C $F log --oneline | wc -l)" = 1 ]
t "ls -l run.sh: $(ls -l $F/run.sh | cut -c1-10)" [ "$(ls -l $F/run.sh | cut -c1-10)" = "-r-xr-xr-x" ]
t "outside.txt still 644" [ "$(stat -c %a $OUT/outside.txt)" = 644 ]
t "symlink still points at it" [ "$(readlink $F/link)" = "$OUT/outside.txt" ]
t "objects still 444" eval '[ -z "$(find $F/.git/objects -type f ! -perm 444)" ] && [ -n "$(find $F/.git/objects -type f)" ]'
head -n 9 $BOOK > $W/head9
printf '%s\n' "# Field book. Entries are added at the end and never altered. Each entry names the one before it." \
  "entry 1" "after -" "did rested" "date 2026-10-13" > $W/want5
t "book lines 1 to 5" eval "head -n 5 $W/head9 | cmp -s - $W/want5"
t "book line 6 is an at instant" eval "sed -n 6p $W/head9 | grep -qE '^at [0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}\.[0-9]{9}(Z|[+-][0-9]{2}:[0-9]{2})$'"
t "book lines 7 to 9" [ "$(sed -n 7,9p $W/head9)" = "$(printf 'field %s\nseasons 1\nfrom 2027-03-25' "$RF")" ]
t "manifest row '  0755 run.sh'" grep -qx '  0755 run.sh' $BOOK
t "manifest row for ." grep -qxE '  [0-7]{4} \.' $BOOK
t "no row for a file under .git/objects" eval "! grep -qE '^  [0-7]{4} \.git/objects/[0-9a-f]{2}/' $BOOK"
echo "  book, first nine lines:"; sed 's/^/  > /' $W/head9

echo; echo "== 3. The quarter day boundary and exact restoration"
SZ=$(stat -c %s $BOOK)
x env FALLOW_TODAY=2027-03-24 fallow plough $F
t "exit 1" [ $rc = 1 ]
t "refusal begins 'Not before 25 Mar 2027. 1 day to go.'" eval "sed -n 2p $W/e | grep -q '^Not before 25 Mar 2027\. 1 day to go\.'"
t "still no write bit" [ "$(writable)" = 0 ]
t "book size unchanged ($SZ)" [ "$(stat -c %s $BOOK)" = "$SZ" ]
x env FALLOW_TODAY=2027-03-25 fallow plough $F
t "exit 0" [ $rc = 0 ]
t "starts 'Ploughed', not 'Ploughed early'" eval "head -n 1 $W/o | grep -q '^Ploughed /'"
t "'$B entries restored to the modes they had.'" grep -qxF "  $B entries restored to the modes they had." $W/o
t "modes identical" eval "modes | diff - $W/before.modes"
t "modification times identical" eval "find $F ! -type l -printf '%T@ %P\n' | sort | diff - $W/before.mtimes"
t "contents identical" eval "(cd $F && find . -type f ! -path './.git/*' | sort | xargs sha256sum) | diff - $W/before.sums"
t "echo x >> docs/notes.md works" eval "echo x >> $F/docs/notes.md"
t "run.sh still executable" [ -x $F/run.sh ]

echo; echo "== 4. The trespass is written in plain words and the book only grows"
cp $BOOK $W/book.saved
x env FALLOW_TODAY=2026-10-13 fallow rest $F --seasons 2
t "rest exit 0, ploughing from 24 Jun 2027" eval "[ $rc = 0 ] && grep -qF 'Ploughing from 24 Jun 2027.' $W/o"
x env FALLOW_TODAY=2027-01-05 fallow plough $F --trespass
t "exit 0" [ $rc = 0 ]
t "the posted line" grep -qxF "  Ploughed early, 170 days before 24 Jun 2027. The field was posted, not fenced." $W/o
t "writes work again" eval "echo x >> $F/docs/notes.md"
t "grep -c 'posted, not fenced' book is 1" [ "$(grep -c 'posted, not fenced' $BOOK)" = 1 ]
t "the entry says did trespassed" eval "last_entry | grep -qx 'did trespassed'"
t "earlier bytes untouched (cmp -n)" cmp -n $(wc -c < $W/book.saved) $W/book.saved $BOOK
x env FALLOW_TODAY=2026-10-13 fallow rest $F --seasons 1
x env FALLOW_TODAY=2027-03-25 fallow plough $F --trespass
t "the flag alone: exit 0, 'Ploughed' not early, did ploughed" eval "[ $rc = 0 ] && head -n 1 $W/o | grep -q '^Ploughed /' && last_entry | grep -qx 'did ploughed'"
x fallow status
t "STATE shows 'ploughed early 5 Jan 2027'" grep -qE '  ploughed early 5 Jan 2027  ' $W/o
t "the trespass block" grep -qxF "  Ploughed early 5 Jan 2027, 170 days before 24 Jun 2027. The field was posted, not fenced." $W/o

echo; echo "== 5. The ledger holds without the permission bit"
x env FALLOW_TODAY=2026-10-13 fallow rest $F --seasons 1
B2=$(sed -n 's/^  [0-9]* entries, \([0-9]*\) locked\.$/\1/p' $W/o)
sleep 1
chmod u+w $F/run.sh && echo x >> $F/run.sh
S=$(booksum)
TODAY=$(date '+%-d %b %Y')
x fallow status
t "exit 0" [ $rc = 0 ]
t "one line 'Changed since rest: 1 entry. Newest: $TODAY, run.sh.'" [ "$(grep -cxF "  Changed since rest: 1 entry. Newest: $TODAY, run.sh." $W/o)" = 1 ]
t "one line 'Write permission: back on 1 of $B2 locked entries.'" [ "$(grep -cxF "  Write permission: back on 1 of $B2 locked entries." $W/o)" = 1 ]
t "no evidence line says trespass" eval "! grep -E '^ +(Changed since rest|Write permission)' $W/o | grep -qiE 'trespass|violation|broken|guilty'"
t "last line is the caution" [ "$(tail -n 1 $W/o)" = "A modification time can be moved by a backup, a sync or an indexer. This is evidence, not a finding." ]
t "status wrote nothing" [ "$(booksum)" = "$S" ]
x env FALLOW_TODAY=2027-03-25 fallow plough $F
t "plough exit 0" [ $rc = 0 ]
t "'changed 1 ' once, in the newest entry" eval "[ \$(grep -cE '^changed 1 ' $BOOK) = 1 ] && last_entry | grep -qE '^changed 1 '"
t "'writable 1 ' once, in the newest entry" eval "[ \$(grep -cE '^writable 1 ' $BOOK) = 1 ] && last_entry | grep -qE '^writable 1 '"
echo "  newest entry:"; last_entry | sed 's/^/  > /'
x fallow status
t "the Found at ploughing block" eval "grep -A3 -xF '  Rested 13 Oct 2026 for 1 season. Ploughed 25 Mar 2027.' $W/o | grep -qxF '    Changed since rest: 1 entry. Newest: $TODAY, run.sh.'"

echo; echo "== 6. Edited books are visible"
cp $BOOK $W/book.good
sed -i 's/^seasons 1$/seasons 4/' $BOOK
x fallow status
t "exit 1" [ $rc = 1 ]
t "the break in place of 'each follows'" eval "sed -n 2p $W/o | grep -qF ', Entry 2 names a different entry 1 than the one in the book.  Seal '"
t "table header still printed once" [ "$(grep -c '^FIELD  *RESTED' $W/o)" = 1 ]
cp $W/book.good $BOOK
x fallow status
t "restored: exit 0" [ $rc = 0 ]
awk '/^entry /{n++} n!=2' $W/book.good > $BOOK
x fallow status
t "deleted entry: exit 1, 'Entry numbering jumps from 1 to 3.'" eval "[ $rc = 1 ] && sed -n 2p $W/o | grep -qF 'Entry numbering jumps from 1 to 3.'"
t "table header still printed once" [ "$(grep -c '^FIELD  *RESTED' $W/o)" = 1 ]
cp $W/book.good $BOOK
S1=$(fallow status | sed -n 's/.*  Seal \([0-9a-f]*\)$/\1/p')
echo "note x" >> $BOOK
S2=$(fallow status | sed -n 's/.*  Seal \([0-9a-f]*\)$/\1/p')
t "a line added to the last entry changes the seal ($S1 to $S2)" eval '[ -n "$S1" ] && [ -n "$S2" ] && [ "$S1" != "$S2" ]'
cp $W/book.good $BOOK
t "the book is the good one again" cmp $W/book.good $BOOK

echo; echo "== 7. Refusals each name the cause and change nothing"
x env FALLOW_TODAY=2026-10-13 fallow rest $F --seasons 1
t "rest again: exit 0" [ $rc = 0 ]
refused() { # want_rc, exact stderr line, command...
  local want=$1 line=$2; shift 2
  local m0 b0; m0=$(modes | sha256sum); b0=$(booksum)
  x "$@"
  t "exit $want: $line" eval '[ $rc = $want ] && [ "$(cat $W/e)" = "$line" ]'
  t "  nothing changed" eval '[ "$(modes | sha256sum)" = "$m0" ] && [ "$(booksum)" = "$b0" ]'
}
N=" Nothing was changed."
refused 1 "$RF is already resting. Ploughing from 25 Mar 2027.$N" fallow rest $F --seasons 1
refused 1 "$RF/docs lies inside the resting field $RF.$N" fallow rest $F/docs --seasons 1
refused 1 "$(dirname $RF) holds the resting field $RF.$N" fallow rest $(dirname $F) --seasons 1
refused 1 "~ holds the field book. Fallow will not rest it.$N" fallow rest $HOME --seasons 1
refused 1 "$RF/run.sh is not a directory.$N" fallow rest $F/run.sh --seasons 1
refused 1 "$OUT is not resting.$N" fallow plough $OUT
refused 2 "Seasons are counted in whole numbers from 1 to 40." fallow rest $OUT --seasons 0
refused 2 "Seasons are counted in whole numbers from 1 to 40." fallow rest $OUT --seasons 41
refused 2 "Seasons are counted in whole numbers from 1 to 40." fallow rest $OUT --seasons x
refused 2 "Say how long: fallow rest DIR --seasons N." fallow rest $OUT
refused 2 "FALLOW_TODAY must be YYYY-MM-DD." env FALLOW_TODAY=banana fallow status
NL=$(mktemp -d); touch "$NL/a
b"
b0=$(booksum)
x fallow rest $NL --seasons 1
t "a name with a line break: exit 1, the sentence" eval '[ $rc = 1 ] && [ "$(cat $W/e)" = "A name in this field contains a line break. Fallow cannot write it down.$N" ]'
t "  not locked, book unchanged" eval '[ -w "$NL" ] && [ -w "$NL/a
b" ] && [ "$(booksum)" = "$b0" ]'

echo; echo "== 9. A copy carries its rest"
x env FALLOW_TODAY=2027-03-25 fallow plough $F
t "close the open rest: exit 0" [ $rc = 0 ]
x env FALLOW_TODAY=2026-10-13 fallow rest $F --seasons 1
B3=$(sed -n 's/^  [0-9]* entries, \([0-9]*\) locked\.$/\1/p' $W/o)
EN=$(sed -n 's/^  Entered as no\. \([0-9]*\)\..*/\1/p' $W/o)
S=$(booksum)
C=$(mktemp -d)/copy; cp -a $F $C; RC=$(realpath $C)
x fallow status $C
t "exit 0, carries $B3 of $B3" eval '[ $rc = 0 ] && [ "$(cat $W/o)" = "$RC is not in the book. It carries the locks of entry $EN ($RF): $B3 of $B3 locked entries." ]'
chmod u+w $C/run.sh
x fallow status $C
t "after chmod u+w: $((B3 - 1)) of $B3" [ "$(cat $W/o)" = "$RC is not in the book. It carries the locks of entry $EN ($RF): $((B3 - 1)) of $B3 locked entries." ]
x fallow status $F
t "status F: only its block, no heading, no table" eval '[ $rc = 0 ] && [ "$(head -n 1 $W/o)" = "$RF" ] && ! grep -qE "^(FIELD BOOK|FIELD  )" $W/o'
x fallow status $OUT
t "status OUT: exactly '$OUT is not in the book.'" [ "$(cat $W/o)" = "$OUT is not in the book." ]
x fallow plough $C
t "plough the copy: exit 1, not resting" eval '[ $rc = 1 ] && [ "$(cat $W/e)" = "$RC is not resting.$N" ]'
t "book unchanged, field still locked" eval '[ "$(booksum)" = "$S" ] && [ "$(writable)" = 0 ]'

echo; echo "== the book as it stands"
x fallow status
cp $BOOK $W/final.book

# leave nothing locked behind
FALLOW_TODAY=2027-03-25 fallow plough $F > /dev/null 2>&1
chmod -R u+w $C $NL 2>/dev/null
rm -rf "$(dirname $F)" "$(dirname $C)" $OUT $NL $HOME $BIN
echo
if [ $fails = 0 ]; then echo "all $pass assertions passed"; else echo "$fails of $((pass + fails)) assertions FAILED"; fi
rm -rf $W
[ $fails = 0 ]
