#!/bin/sh
# tenkana, a spider that jumps from the checkpoints of your TeX document.
# Copyright © 2026 निरंजन (Niranjan)
#
# tenkana is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# tenkana is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with tenkana.  If not, see <https://www.gnu.org/licenses/>.
#
# tenkana was written by Claude, a large language model (LLM) made by
# Anthropic.  Its maintainer designs tenkana and tests what it does, but does
# not understand its code; as far as he knows, no human has reviewed it.
# Courts are divided on whether material generated by an LLM can be protected
# by copyright.  Should it be found that the copyright claimant cannot hold
# copyright in any part of tenkana, that part is in the public domain.
# Wherever copyright does hold, tenkana is distributed under the terms of the
# GNU General Public License, version 3 or (at your option) any later version,
# as stated above.

# What tenkana does, checked from the outside: options and messages, builds,
# references, snapshots, plain runs, the TeX runs of other programs, the
# files it leaves and its exit codes.  Every check runs tenkana as a user
# would, so the same tests hold whatever tenkana is written in.
#
#   tests/run.sh [tenkana]      (default: build ./tenkana with ./build.sh)
#
# Needs pdflatex, lualatex, xelatex, latexmk and pdftotext.  Each check runs
# in a folder of its own, with a cache of its own; nothing outside them is
# touched.  Snapshots exist only on x86-64; elsewhere the checks expect
# builds without them, and those of snapshots alone are left out.  Prints one line per failed check and a summary; exits 1 if any
# check failed.
set -u
here=$(cd "$(dirname "$0")/.." && pwd)
top=$(mktemp -d)
trap 'rm -rf "$top" 2>/dev/null || { sleep 1; rm -rf "$top"; }' EXIT
# (snapshots end when their cache folder goes)
export XDG_CACHE_HOME="$top/cache"
export SOURCE_DATE_EPOCH=1700000000 FORCE_SOURCE_DATE=1
unset TENKANA_ENGINE TENKANA_SILENT TENKANA_DEBUG TENKANA_WATCH
if [ $# -ge 1 ]; then
  T=$(cd "$(dirname "$1")" && pwd)/$(basename "$1")
else
  "$here/build.sh" "$top/tenkana" >/dev/null || exit 1
  T="$top/tenkana"
fi

snapshots=no
[ "$(uname -m)" = x86_64 ] && snapshots=yes
snap() { [ $snapshots = yes ]; }  # snap && check ...: with snapshots only

passed=0 failed=0
ok() { passed=$((passed + 1)); }
bad() { failed=$((failed + 1)); echo "FAIL: $*"; }
check() {  # check NAME COMMAND...: the command must succeed
  name=$1; shift
  if "$@" >/dev/null 2>&1; then ok; else bad "$name"; fi
}
has() { grep -F -e "$2" "$1" >/dev/null; }  # has FILE TEXT
text() { pdftotext "$1" - 2>/dev/null; }

n=0
fresh() {  # a new folder for a check; the rest runs inside it
  n=$((n + 1)); d="$top/t$n"; mkdir -p "$d"; cd "$d" || exit 1
}
doc() {  # doc NAME BODY: a small LaTeX document
  printf '\\documentclass{article}\n\\begin{document}\n%b\n\\end{document}\n' \
    "$2" > "$1.tex"
}
edit() {  # edit NAME TEXT: add TEXT just before \end{document}
  sed -i "s/^\\\\end{document}/$2\\n\\\\end{document}/" "$1.tex"
}
run() {  # run tenkana, its output in out.txt, its exit code in $code
  "$T" "$@" > out.txt 2>&1 < /dev/null; code=$?
}

# ---- options and messages ---------------------------------------------------
fresh
run --version
check "--version: exit 0" [ $code = 0 ]
check "--version: names tenkana" grep -Eq '^tenkana [0-9]+\.[0-9]+\.[0-9]+$' out.txt
check "--version: license" has out.txt "GPLv3+"
run -V; check "-V is --version" grep -q '^tenkana [0-9]' out.txt
run --help
check "--help: exit 0" [ $code = 0 ]
check "--help: usage" has out.txt "usage: tenkana [tenkana options] TeX-command"
check "--help: spider" has out.txt "|o(O)(O)o|"
run -h; check "-h is --help" has out.txt "usage: tenkana"
run
check "no command: exit 2" [ $code = 2 ]
check "no command: says so" has out.txt "tenkana: no TeX command given"

for c in \
  "-b|unknown option -b; did you mean tenkana -v?" \
  "-sb|unknown option -sb; did you mean tenkana -sv?" \
  "-S|unknown option -S; did you mean tenkana -s?" \
  "-hv|-hv can't be combined; did you mean tenkana -h -v?" \
  "-qf|-qf can't be combined; did you mean tenkana -q -f?" \
  "--verbos|unknown option --verbos; did you mean tenkana --verbose?" \
  "-verbose|unknown option -verbose; did you mean tenkana --verbose?" \
  "--quiet|unknown option --quiet; did you mean tenkana --silent?" \
  "--bogus|unknown option --bogus; tenkana's options come before the TeX command." \
  "-interaction=nonstopmode|unknown option -interaction=nonstopmode; tenkana's options come before" \
  "-k|unknown option -k; tenkana's options come before"; do
  opt=${c%%|*}; msg=${c#*|}
  run "$opt" pdflatex x
  check "option $opt: exit 2" [ $code = 2 ]
  check "option $opt: message" has out.txt "tenkana: $msg"
done
run nosuchprogram x
check "unknown program: exit 2" [ $code = 2 ]
check "unknown program: message" has out.txt "tenkana: nosuchprogram was not found on your PATH."
run -f sh -c true
check "--force with a program: exit 2" [ $code = 2 ]
check "--force with a program: message" has out.txt "--force works only with a TeX command, not with sh"
doc a "A."
run pdflatex -output-directory=o a
check "unsupported TeX option: exit 2" [ $code = 2 ]
check "unsupported TeX option: message" has out.txt "the TeX option -output-directory is not supported yet."
run -q a b
check "-q with two files: exit 2" [ $code = 2 ]
check "-q with two files: message" has out.txt "-q takes one file (b is a second one)."

# ---- builds -----------------------------------------------------------------
fresh
doc d "First text."
run pdflatex d
check "first build: exit 0" [ $code = 0 ]
snap && check "first build: message" grep -Eq '^tenkana: (first build \(|jumped from)' out.txt
check "first build: PDF" sh -c 'pdftotext d.pdf - | grep -q "First text"'
check "first build: TeX's output shown" has out.txt "Output written on d.pdf"
check "first build: no pause file in the .fls" sh -c '! grep -q tenkanapause d.fls'
check "first build: cache private" sh -c "[ \$(stat -c %a '$XDG_CACHE_HOME/tenkana') = 700 ]"
before=$(stat -c %Y d.pdf); sleep 1.1
run pdflatex d
check "unchanged: message" has out.txt "tenkana: nothing changed; the output is up to date."
check "unchanged: TeX not run" [ "$(stat -c %Y d.pdf)" = "$before" ]
edit d "Second text."
run pdflatex d
check "edit: exit 0" [ $code = 0 ]
snap && check "edit: jumped" grep -Eq '^tenkana: jumped from ~[0-9.]+s for (a plain run|[0-9]+ plain runs) to [0-9.]+s \([0-9]+% less time\)\.$' out.txt
check "edit: PDF updated" sh -c 'pdftotext d.pdf - | grep -q "Second text"'
edit d "Third text."
run -v pdflatex d
if snap; then
  check "-v: pass line" grep -Eq '^tenkana: pass 1 \(resumed from the preamble snapshot, [0-9.]+s\)\.$' out.txt
else
  check "-v: pass line" grep -Eq '^tenkana: pass 1 \(plain run with cached preamble, [0-9.]+s\)\.$' out.txt
fi
snap && check "-v: memory line" grep -Eq '^tenkana: [0-9]+ snapshots? in memory, [0-9]+MB\.$' out.txt
edit d "Fourth text."
run --silent pdflatex d
check "--silent: no tenkana lines" sh -c '! grep -q "^tenkana" out.txt'
check "--silent: built" sh -c 'pdftotext d.pdf - | grep -q "Fourth text"'
edit d "Fifth text."
run -f pdflatex d
snap && check "--force: from scratch" grep -Eq '^tenkana: (first build \(|jumped from)' out.txt
run --clean d
check "--clean: message" grep -Eq '^tenkana: removed the cache for d( and stopped [0-9]+ snapshots?)?\.$' out.txt
check "--clean: cache gone" sh -c "[ -z \"\$(ls '$XDG_CACHE_HOME/tenkana/docs')\" ]"
run --clean d
check "--clean again: nothing" has out.txt "no cache for d in this folder"

# references settle; -s makes one run
fresh
doc r 'See section~\\ref{b}.\n\\section{A}\\label{a}\n\\section{B}\\label{b}'
run -v pdflatex r
check "references: two passes" has out.txt "pass 2"
check "references: resolved" sh -c 'pdftotext r.pdf - | grep -q "See section 2"'
fresh
doc r 'See section~\\ref{b}.\n\\section{B}\\label{b}'
run -s pdflatex r
check "-s: one pass, ?? left" sh -c 'pdftotext r.pdf - | grep -q "See section ??"'
run -s pdflatex r
check "-s twice: resolved" sh -c 'pdftotext r.pdf - | grep -q "See section 1"'
run --final -d pdflatex r
check "--final, -d: accepted" [ $code = 0 ]

# engines, -q, no snapshots
for e in lualatex xelatex; do
  fresh; doc e "Engine $e."
  run $e e
  check "$e: exit 0" [ $code = 0 ]
  check "$e: PDF" sh -c "pdftotext e.pdf - | grep -q 'Engine $e'"
  edit e "Edited $e."
  run $e e
  check "$e: edit" sh -c "pdftotext e.pdf - | grep -q 'Edited $e'"
done
fresh; doc q "Quick."
TENKANA_ENGINE=pdflatex run -q q
check "-q: builds with TENKANA_ENGINE" has out.txt "Output written on q.pdf"
fresh; doc p "Plain."
run --no-snapshots pdflatex p
check "--no-snapshots: exit 0" [ $code = 0 ]
check "--no-snapshots: PDF" sh -c 'pdftotext p.pdf - | grep -q Plain'
edit p "Plainer."
run --no-snapshots pdflatex p
check "--no-snapshots: edit" sh -c 'pdftotext p.pdf - | grep -q Plainer'

# a TeX error: TeX's exit code; TeX code without \input runs as it is
fresh; doc x '\\undefinedcommand'
pdflatex -interaction=nonstopmode x >/dev/null 2>&1; want=$?
rm -f x.aux x.log x.pdf
run pdflatex -interaction=nonstopmode x
check "TeX error: TeX's exit code" [ $code = "$want" ]
run pdflatex '\relax\stop'
check "no main file: runs as is" [ $code = 0 ]

# the preamble snapshot on disk, when the snapshots in memory have ended
if snap; then
  fresh; doc disk "On disk."
  run pdflatex disk
  i=0  # the snapshot is written to disk in the background
  while [ $i -lt 100 ] && ! ls "$XDG_CACHE_HOME"/tenkana/docs/disk-*/disk-snap/ck000.img.status >/dev/null 2>&1; do
    sleep 0.1; i=$((i + 1))
  done
  pkill -f 'disk$' 2>/dev/null; sleep 0.5
  edit disk "After a restart."
  run -v pdflatex disk
  check "disk: restored" has out.txt "restored the preamble snapshot from disk"
  check "disk: PDF" sh -c 'pdftotext disk.pdf - | grep -q "After a restart"'
fi

# ---- the TeX runs of other programs -----------------------------------------
fresh
cat > m.tex <<'EOF'
\documentclass{article}
\begin{document}
See section~\ref{b} and \cite{k}.
\section{A}\label{a} Text.
\section{B}\label{b} Text.
\bibliographystyle{plain}\bibliography{m}
\end{document}
EOF
printf '@book{k, author={A. Author}, title={T}, year={2000}, publisher={P}}\n' > m.bib
mkdir plain; cp m.tex m.bib plain/
(cd plain && latexmk -pdf -interaction=nonstopmode m > ../plain.txt 2>&1)
run latexmk -pdf -interaction=nonstopmode m
check "latexmk: exit 0" [ $code = 0 ]
check "latexmk: summary" grep -Eq '^tenkana: latexmk took [0-9.]+s and ran TeX [0-9]+ times?: ' out.txt
check "latexmk: same number of runs" [ "$(grep -c 'Run number' out.txt)" = "$(grep -c 'Run number' plain.txt)" ]
# (without snapshots the cached preamble numbers the fonts differently)
pdf=m.pdf; snap || pdf=
for f in m.aux m.bbl $pdf; do
  check "latexmk: $f as without tenkana" cmp -s $f plain/$f
done
check "latexmk: no pause file in the .fls" sh -c '! grep -q tenkanapause m.fls'
check "latexmk afterwards: nothing to do" sh -c 'latexmk -pdf -interaction=nonstopmode m 2>&1 | grep -q "Nothing to do"'

fresh; doc s "Sh."
run sh -c 'pdflatex -interaction=nonstopmode s; pdflatex -interaction=nonstopmode s'
check "sh: ran TeX 2 times" has out.txt "and ran TeX 2 times"
run sh -c 'pdflatex -interaction=nonstopmode s; pdflatex -interaction=nonstopmode s'
check "sh again: both skipped" has out.txt "2 skipped (nothing changed)"
run -v sh -c 'pdflatex -interaction=nonstopmode s'
check "-v: each run's lines" grep -q '^tenkana: pdflatex s: ' out.txt
run sh -c 'exit 3'
check "program's exit code" [ $code = 3 ]
check "no TeX run" has out.txt "ran no TeX compilation."
run sh -c 'pdflatex -fmt=pdflatex -interaction=nonstopmode s'
check "unsupported option: as is" has out.txt "1 as is (the TeX option -fmt is not supported yet)"
check "unsupported option: built" [ $code = 0 ]
fresh; doc e '\\undefinedcommand'
run latexmk -pdf -interaction=nonstopmode e
check "latexmk error: exit 12" [ $code = 12 ]
fresh; printf 'os.execute("pdflatex -interaction=nonstopmode l")\n' > l.lua; doc l "Lua."
run texlua l.lua
check "texlua is a program, its TeX run counted" has out.txt "ran TeX 1 time"

echo "tests/run.sh: $passed passed, $failed failed."
[ $failed = 0 ]
