#!/usr/bin/env bash
set -euo pipefail
unset MAKEFLAGS MFLAGS GNUMAKEFLAGS
make_bin=$(command -v gmake || command -v make)
m() { "$make_bin" --no-print-directory -rR "$@"; }
work_dir=$(mktemp -d)
if [ "${KEEP_WORK:-0}" = 1 ]; then
  trap 'printf "Artifacts: %s\n" "$work_dir"' EXIT
else
  trap 'rm -rf -- "$work_dir"' EXIT
fi
cd "$work_dir"
export TMPDIR="$work_dir"
cat > main.tex <<'INPUT_81_1'
\documentclass{article}
\begin{document}
\input{sections/intro}
\end{document}
INPUT_81_1
mkdir -p sections
cat > sections/intro.tex <<'INPUT_81_2'
First discovered chapter.
INPUT_81_2
cat > Makefile <<'MAKEFILE'
LATEXMK ?= latexmk
FLAGS := -norc -pdf -no-shell-escape
FLAGS += -interaction=nonstopmode -halt-on-error
.DELETE_ON_ERROR:
.DEFAULT_GOAL := pdf
.PHONY: pdf watch
pdf: | build
	@$(LATEXMK) $(FLAGS) -outdir=build main.tex > build/latexmk.log 2>&1 || \
	  { cat build/latexmk.log >&2; exit 1; }
watch: | build
	@$(LATEXMK) $(FLAGS) -outdir=build -pvc main.tex
build:
	@mkdir -p $@
MAKEFILE
m -s pdf
cp build/main.log first.log
m -s pdf
cmp first.log build/main.log
printf "unchanged input: TeX engine skipped\n"
printf "Changed discovered chapter.\n" > sections/intro.tex
m -s pdf
pdftotext build/main.pdf text.txt
grep -q 'Changed discovered chapter.' text.txt
printf "changed input: PDF updated\n"
m -n watch > watch-command.txt
grep -q -- '-pvc main.tex' watch-command.txt
printf "watch command checked without starting a watcher\n"
