#!/usr/bin/env bash
# End to end checks for CARD.md acceptance 2 to 10, on Linux with git, tmux and uv.
# Usage, from the project folder: bash e2e.sh REPO
# REPO is a real git repository of 100 or more files. It is only read.
# Scratch folders live under one mktemp folder and are removed at the end.
# The log is out/e2e.log; every line ends PASS or FAIL.
set -u
P=$(cd "$(dirname "$0")" && pwd)
REPO=${1:?usage: bash e2e.sh REPO}
TOOL="$P/emporium.py"
T=$(mktemp -d)
export GIT_CEILING_DIRECTORIES=$T
mkdir -p "$P/out"
LOG="$P/out/e2e.log"
: >"$LOG"
fails=0
say() { printf '%s\n' "$*" | tee -a "$LOG"; }
check() { if eval "$2"; then say "PASS $1"; else say "FAIL $1"; fails=$((fails + 1)); fi; }
em() { uv run --quiet "$TOOL" "$@"; }
footer() { awk -v k="$2" '$1 == k { gsub(",", "", $2); print $2; exit }' <<<"$1"; }
sumcounts() { grep -E '^\([a-n]\)  ' <<<"$1" | awk '{ for (i = 1; i <= NF; i++) if ($i ~ /^[0-9,]+$/) { gsub(",", "", $i); s += $i; break } } END { print s + 0 }'; }

# tmux: run one command in a fresh pane of the given size; leaves the pane for capture
TM=(tmux -L emporium-e2e -f /dev/null)
pane() { # cols rows cwd command [env...]
  local cols=$1 rows=$2 cwd=$3 cmd=$4 envs=() v; shift 4
  for v in "$@"; do envs+=(-e "$v"); done
  "${TM[@]}" kill-server 2>/dev/null
  "${TM[@]}" new-session -d -s e -x "$cols" -y "$rows" -c "$cwd" "${envs[@]}" "sleep 0.3; $cmd; sleep 30"
  "${TM[@]}" set -g history-limit 5000 >/dev/null
  for _ in $(seq 1 100); do
    sleep 0.2
    "${TM[@]}" capture-pane -p -t e | grep -q '^__END__' && return 0
  done
  return 1
}
cap() { "${TM[@]}" capture-pane -p -J -S - -t e "$@" | sed '/^__END__/,$d'; }

say "== run $(date -u +%Y-%m-%dT%H:%M:%SZ) on $(uname -sm), $(uv run --quiet python --version), $(git --version), tmux $(tmux -V | cut -d' ' -f2)"
say "== repo $(basename "$REPO"): $(git -C "$REPO" ls-files | wc -l) tracked files, $(git -C "$REPO" rev-list --count HEAD) commit(s)"

say ""
say "== 2. end to end on a real repository"
cd "$REPO" || exit 1
s=$(date +%s.%N)
REAL=$(em)
rc=$?
e=$(date +%s.%N)
secs=$(awk -v a="$s" -v b="$e" 'BEGIN { printf "%.2f", b - a }')
printf '%s\n' "$REAL" >"$P/out/real-report.txt"
sed 's/^/    /' "$P/out/real-report.txt" >>"$LOG"
say "exit $rc in $secs s"
check "2 exits 0" '[ $rc -eq 0 ]'
check "2 under 5 seconds ($secs s)" 'awk -v t="$secs" "BEGIN { exit !(t < 5) }"'
check "2 header names the basename" '[ "$(head -1 <<<"$REAL")" = "emporium index   $(basename "$REPO")" ]'
check "2 at least one class" 'grep -qE "^\([a-n]\)  " <<<"$REAL"'
check "2 four footer lines" '[ $(grep -cE "^(entries|classified|placements|surplus) " <<<"$REAL") -eq 4 ]'
check "2 no line starts with /Users/ or /home/" '! grep -qE "^(/Users/|/home/)" <<<"$REAL"'
check "2 no absolute path anywhere" '! grep -q "$REPO" <<<"$REAL"'

say ""
say "== 3. cross-check against find and git log"
ENT=$(footer "$REAL" entries)
FIND=$(find . -mindepth 1 -type d -name .git -prune -o -print | wc -l)
say "entries $ENT, find $FIND"
check "3 entries minus 1 equals find" '[ $((ENT - 1)) -eq $FIND ]'
N1=$(em n | wc -l)
N2=$(find . -type d -name .git -prune -o -type f -size -64c -print | wc -l)
say "flies $N1, find -size -64c $N2"
check "3 flies equals find" '[ $N1 -eq $N2 ]'
diff <(em g | LC_ALL=C sort) <(find . -type d -name .git -prune -o -type f ! -name "*.*" ! -name ".*" -print | sed "s|^\./||" | LC_ALL=C sort) >/dev/null
G=$?
say "stray dogs $(em g | wc -l), find $(find . -type d -name .git -prune -o -type f ! -name '*.*' ! -name '.*' -print | wc -l)"
check "3 stray dogs equals find as a set" '[ $G -eq 0 ]'
TOP=$(git log --name-only --no-renames --relative --pretty=format: | grep -v '^$' | LC_ALL=C sort | uniq -c | LC_ALL=C sort -k1,1nr -k2 | head -1)
say "git top: $TOP"
FR=$(em frenzied 2>&1)
frc=$?
say "frenzied on this repository: exit $frc, $FR"
check "3 frenzied agrees: top count under 5 means no entries" '[ "$(awk "{print \$1}" <<<"$TOP")" -lt 5 ] && [ $frc -eq 1 ] || [ "$(head -1 <<<"$FR")" = "$(awk "{print \$2}" <<<"$TOP")" ]'

# The repository above has one commit. A history is needed to rank anything, so
# a copy of its files is given one here: an initial commit, then 60 commits that
# each touch the files a fixed rule picks, in pairs. Constructed, and labelled so.
H="$T/history/$(basename "$REPO")"
mkdir -p "$H"
(cd "$REPO" && git ls-files -z | xargs -0 cp --parents -t "$H")
cd "$H" || exit 1
gc() { git -c user.name=fixture -c user.email=fixture@localhost "$@"; }
git init -q && git add -A && gc commit -qm initial
mapfile -t files < <(git ls-files | head -40)
for i in $(seq 1 60); do
  for j in $(seq 0 39); do
    k=$((j / 2)) # files 2k and 2k+1 get the same commits, so every count is a tie
    if [ $(((i * (k + 3)) % (k + 2))) -eq 0 ] || [ $k -lt $((7 - i / 9)) ]; then printf '%s\n' "$i" >>"${files[$j]}"; fi
  done
  git add -A && gc commit -qm "change $i"
done
git rm -q "${files[0]}" && gc commit -qm "remove one"
TOPS=$(git log --name-only --no-renames --relative --pretty=format: | grep -v '^$' | LC_ALL=C sort | uniq -c | LC_ALL=C sort -k1,1nr -k2)
FIRST=$(while read -r n f; do [ -e "$f" ] && { echo "$f"; break; }; done <<<"$TOPS")
WANT=$(while read -r n f; do [ "$n" -ge 5 ] && [ -f "$f" ] && echo "$f"; done <<<"$TOPS" | head -10)
GOT=$(em frenzied)
say "constructed history: $(git rev-list --count HEAD) commits; git top lines:"
head -12 <<<"$TOPS" | sed 's/^/    /' >>"$LOG"
say "emporium frenzied:"
sed 's/^/    /' <<<"$GOT" >>"$LOG"
check "3 frenzied first line equals the first git top path on disk ($FIRST)" '[ "$(head -1 <<<"$GOT")" = "$FIRST" ]'
check "3 frenzied top ten equals git log, ties by path" '[ "$GOT" = "$WANT" ]'
HR=$(em)
check "3 frenzied appears in the report of the history copy" 'grep -q "^(i)  Frenzied" <<<"$HR"'

say ""
say "== 4. arithmetic"
for name in REAL HR; do
  r=${!name}
  pl=$(footer "$r" placements); cl=$(footer "$r" classified); su=$(footer "$r" surplus); sc=$(sumcounts "$r")
  say "$name: class counts add to $sc, placements $pl, classified $cl, surplus $su"
  check "4 $name counts add up to placements" '[ $sc -eq $pl ]'
  check "4 $name surplus equals placements minus classified" '[ $su -eq $((pl - cl)) ]'
done
A="$T/arith"
mkdir -p "$A"
printf 'some notes that are longer than sixty four bytes, so not a fly at all.\n' >"$A/notes.txt"
printf 'all:\n\techo a makefile longer than sixty four bytes, a stray dog only\n' >"$A/Makefile"
touch -d '3 days ago' "$A/notes.txt" "$A/Makefile"
B1=$(em "$A")
: >"$A/zero.png"
touch -d '3 days ago' "$A/zero.png"
B2=$(em "$A")
dp=$(($(footer "$B2" placements) - $(footer "$B1" placements)))
dc=$(($(footer "$B2" classified) - $(footer "$B1" classified)))
say "zero-byte png: placements +$dp, classified +$dc; $(em k "$A") in k, $(em n "$A") in n"
check "4 zero-byte png raises placements by 2 and classified by 1" '[ $dp -eq 2 ] && [ $dc -eq 1 ]'
check "4 no overlap gives surplus 0" '[ "$(footer "$B1" surplus)" -eq 0 ]'
sed 's/^/    /' <<<"$B2" >>"$LOG"

say ""
say "== 5. the report counts itself"
EM="$T/empty"
mkdir "$EM"
E0=$(em "$EM")
sed 's/^/    /' <<<"$E0" >>"$LOG"
check "5 empty folder: (h) count 1" 'grep -qE "^\(h\)  Included in this classification +1  written by this tool$" <<<"$E0"'
check "5 empty folder: (this report)" 'grep -qx "     (this report)" <<<"$E0"'
check "5 empty folder: entries 1, 0 on disk" 'grep -qE "^entries +1   0 on disk, and this report$" <<<"$E0"'
check "5 empty folder: surplus 0" 'grep -qE "^surplus +0$" <<<"$E0"'
W="$T/write"
mkdir "$W"
while [ "$(date +%S)" -gt 50 ]; do sleep 1; done
W1=$(em "$W" --write 2>&1)
w1=$?
f1=$(ls "$W")
say "first --write: exit $w1, files: $f1, $(tail -1 <<<"$W1")"
check "5 first run leaves one file named for the minute in its header" '[ $w1 -eq 0 ] && [ "$(ls "$W" | wc -l)" -eq 1 ] && [ "$f1" = "emporium-index-$(sed -n "2s/.*counted \([0-9-]*\) \([0-9]*\):\([0-9]*\).*/\1-\2\3/p" "$W/$f1").txt" ]'
check "5 the filed report has no colour and starts with the header" '[ "$(head -c 14 "$W/$f1")" = "emporium index" ] && ! grep -q $'"'"'\x1b'"'"' "$W/$f1"'
m=$(date +%M)
while [ "$(date +%M)" = "$m" ]; do sleep 1; done
sleep 1
W2=$(em "$W" --write 2>/dev/null)
w2=$?
f2=$(ls "$W" | grep -vx "$f1")
W3=$(em "$W" --write 2>&1)
w3=$?
sed 's/^/    /' <<<"$W2" >>"$LOG"
say "second --write: exit $w2, new file $f2; third, same minute: exit $w3, $W3"
check "5 second run: (h) count 2" 'grep -qE "^\(h\)  Included in this classification +2  written by this tool$" <<<"$W2"'
check "5 second run: entries 2, 1 on disk" 'grep -qE "^entries +2   1 on disk, and this report$" <<<"$W2"'
check "5 second run: surplus 1 or 2" '[ "$(footer "$W2" surplus)" -ge 1 ] && [ "$(footer "$W2" surplus)" -le 2 ]'
check "5 both files on disk, emporium h lists the first" '[ "$(ls "$W" | wc -l)" -eq 2 ] && em h "$W" | grep -qx "$f1"'
before=$(md5sum "$W/$f2")
check "5 third run in the same minute exits 1 and writes nothing" '[ $w3 -eq 1 ] && [ "$W3" = "A report for this minute is already filed." ] && [ "$(ls "$W" | wc -l)" -eq 2 ] && [ "$(md5sum "$W/$f2")" = "$before" ]'

say ""
say "== 6. filters"
cd "$REPO" || exit 1
SD=$(em stray-dogs)
check "6 stray-dogs prints only paths, no header" '! grep -q "emporium index" <<<"$SD" && [ "$(wc -l <<<"$SD")" -eq "$(em g | wc -l)" ]'
check "6 g and stray-dogs are byte-identical" 'cmp -s <(em g) <(em stray-dogs)'
NR="$T/nonrepo"
mkdir "$NR" && printf 'x\n' >"$NR/a.txt"
o=$(em frenzied "$NR" 2>"$T/err"); r=$?
check "6 frenzied in a non-repo: No entries. on stderr, exit 1" '[ $r -eq 1 ] && [ -z "$o" ] && [ "$(cat "$T/err")" = "No entries." ]'
em dogs 2>"$T/err"; r=$?
say "$(cat "$T/err")"
check "6 dogs exits 2 with the unknown-class line" '[ $r -eq 2 ] && grep -q "^Unknown class \"dogs\". Classes: a owner is not you; b not writable by you; c not modified in 2 years; d created in the last 24 hours; e audio file, by extension; f symlink to nothing; g no extension; h written by this tool; i top 10 by git commits; j over 1,000 entries; k image, by extension; m modified in the last minute; n smaller than 64 bytes. See emporium --classes.$" "$T/err"'
em stray-dogs --write 2>"$T/err"; r=$?
check "6 stray-dogs --write exits 2" '[ $r -eq 2 ] && [ "$(cat "$T/err")" = "--write takes the whole report." ]'
check "6 included never prints (this report)" '! em included "$W" | grep -q "this report" && ! em included "$EM" | grep -q "this report"'

say ""
say "== 7. honest dates"
C="$T/copy/$(basename "$REPO")"
mkdir -p "$T/copy" && cp -R "$REPO" "$C"
CR=$(em "$C")
say "$(grep -A1 "share one modification time" <<<"$CR")"
check "7 cp -R copy: date-cluster note" 'grep -q "^Note: [0-9,]* of [0-9,]* files share one modification time" <<<"$CR"'
D="$T/spread"
mkdir "$D"
for i in $(seq 1 12); do printf 'file %s of a spread\n' "$i" >"$D/f$i.txt"; touch -d "$i days ago" "$D/f$i.txt"; done
check "7 spread dates: no cluster note" '! em "$D" | grep -q "share one modification time"'
check "7 non-repo: Frenzied note" 'em "$NR" | grep -qx "Note: Frenzied was not counted. This folder is not inside a git repository."'
check "7 repository with history: no Frenzied note" '! grep -q "Frenzied was not counted" <<<"$HR"'
check "7 Linux: sucking pigs note" 'grep -qx "Note: Sucking pigs uses modification time. This system reports no creation time." <<<"$REAL"'

say ""
say "== 8. hostile names"
X="$T/hostile"
mkdir "$X"
printf 'a file with an escape in its name, long enough not to be a fly\n' >"$X/$(printf 'x\033[31my')"
XR=$(em "$X")
check "8 report shows x?[31my" 'grep -qF "x?[31my" <<<"$XR" && ! grep -q $'"'"'\x1b'"'"' <<<"$XR"'
em "$X" --write >/dev/null 2>&1
check "8 the --write file shows x?[31my" 'grep -qF "x?[31my" "$X"/emporium-index-*.txt && ! grep -q $'"'"'\x1b'"'"' "$X"/emporium-index-*.txt'
say "$(em stray-dogs "$X" | od -c | head -2)"
check "8 piped filter keeps the escape byte (033)" 'em stray-dogs "$X" | od -c | grep -q "x 033   \[   3   1   m   y"'
pane 80 24 "$X" "uv run --quiet '$TOOL' stray-dogs; echo __END__" || say "tmux did not finish"
check "8 filter on a TTY shows ?" '[ "$(cap | head -1)" = "x?[31my" ]'

say ""
say "== 9. the terminal, 80x24 in tmux"
F="$T/fixture"
mkdir -p "$F/src" "$F/assets" "$F/notes"
for i in $(seq 1 14); do printf 'chapter %s, kept for the record and long enough to weigh more than a fly\n' "$i" >"$F/notes/ch$i.md"; done
touch -d '3 years ago' "$F"/notes/*.md
printf 'all:\n\techo build, and a line long enough to make this more than a fly\n' >"$F/Makefile"
printf 'Permission is granted, provided that this notice is kept in every copy.\n' >"$F/LICENSE"
touch -d '2 days ago' "$F/Makefile" "$F/LICENSE"
chmod 444 "$F/LICENSE"
: >"$F/assets/blank.png"; : >"$F/notes/.gitkeep"
touch -d '2 days ago' "$F/assets/blank.png" "$F/notes/.gitkeep"
ln -s missing.wav "$F/assets/theme"
printf 'print("hello")\n' >"$F/src/main.py"
pane 80 24 "$F" "uv run --quiet '$TOOL'; echo __END__" COLORTERM=truecolor || say "tmux did not finish"
PANE=$(cap)
printf '%s\n' "$PANE" >"$P/out/pane-80x24.txt"
sed 's/^/    /' <<<"$PANE" >>"$LOG"
check "9 no line wider than 80 columns" '[ "$(awk "{ if (length > m) m = length } END { print m + 0 }" <<<"$PANE")" -le 80 ]'
check "9 each class two lines, then a name line" 'awk "/^\([a-n]\)  /{ getline n; if (n !~ /^     [^ ]/) bad = 1 } END { exit bad }" <<<"$PANE"'
MARKS=$(grep -oE '^\([a-n]\)' <<<"$PANE" | tr -d '()' | tr -d '\n')
say "marks shown: $MARKS"
check "9 classes in Borges order, empty ones absent" '[ "$MARKS" = "$(grep -o . <<<"$MARKS" | LC_ALL=C sort | tr -d "\n")" ] && ! grep -q "^(a)" <<<"$PANE" && ! grep -q "^(j)" <<<"$PANE"'
"${TM[@]}" capture-pane -p -e -S - -t e >"$P/out/pane-80x24.ans"
check "9 brick rule 38;2;236;94;82 on a truecolor TTY" 'grep -qF $'"'"'\x1b[38;2;236;94;82m=============='"'"' "$P/out/pane-80x24.ans"'
pane 80 24 "$F" "uv run --quiet '$TOOL'; echo __END__" COLORTERM=truecolor NO_COLOR=1 || say "tmux did not finish"
check "9 NO_COLOR=1: no colour codes" '! "${TM[@]}" capture-pane -p -e -S - -t e | grep -qE $'"'"'\x1b\[[0-9;]*(3[0-7]|38;[25])'"'"
check "9 piped: no escape codes at all" '! em "$F" | grep -q $'"'"'\x1b'"'"
pane 80 24 "$F" "uv run --quiet '$TOOL' --classes; echo __END__" || say "tmux did not finish"
CL=$(cap)
printf '%s\n' "$CL" >"$P/out/pane-classes-80x24.txt"
CM=$(grep -oE '^[a-n]  [a-z]' <<<"$CL" | cut -c1 | tr -d '\n')
say "--classes marks: $CM"
check "9 --classes lists a to n with the l line between k and m" '[ "$CM" = "abcdefghijklmn" ] && grep -qx "l  et cetera     no property to check, not implemented." <<<"$CL"'
check "9 --classes no line wider than 80" '[ "$(awk "{ if (length > m) m = length } END { print m + 0 }" <<<"$CL")" -le 80 ]'
"${TM[@]}" kill-server 2>/dev/null

say ""
say "== 10. dependencies and text"
IMPORTS=$(uv run --quiet python - "$TOOL" <<'PY'
import ast, sys
tree = ast.parse(open(sys.argv[1]).read())
mods = {a.name.split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.Import) for a in n.names}
mods |= {n.module.split(".")[0] for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)}
print(" ".join(sorted(mods)), "|", " ".join(sorted(m for m in mods if m not in sys.stdlib_module_names)) or "none outside the standard library")
PY
)
say "imports: $IMPORTS"
check "10 standard library only" 'grep -q "| none outside the standard library" <<<"$IMPORTS"'
cd "$P" || exit 1
TEXT=(emporium.py test_emporium.py README.md BUILD.md e2e.sh shots.py)
check "10 the text files exist" 'ls "${TEXT[@]}" >/dev/null'
check "10 no em or en dash" '! grep -nP "[\x{2013}\x{2014}]" "${TEXT[@]}"'
check "10 no emoji" '! grep -nP "[\x{1F000}-\x{1FAFF}\x{2600}-\x{27BF}]" "${TEXT[@]}"'
# code: a spaced hyphen between operands is subtraction; prose: any spaced hyphen counts
DASH=$(grep -nE '(^|[^-])[-][-]([^-a-zA-Z]|$)|[ ][-][ ]' emporium.py test_emporium.py e2e.sh shots.py | grep -vE '[]A-Za-z0-9_)}"] [-] [A-Za-z0-9_($"]|[-]S [-] ' || true)
DASH+=$(grep -nE '(^|[^-])[-][-]([^-a-zA-Z]|$)|[^ ] [-] ' README.md BUILD.md || true)
[ -n "$DASH" ] && say "$DASH"
check "10 no double or spaced hyphen used as a dash" '[ -z "$DASH" ]'

"${TM[@]}" kill-server 2>/dev/null
chmod -R u+w "$T" && rm -rf "$T"
say ""
say "== $fails failed"
exit $((fails > 0))
