#!/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_89_1'
\documentclass{article}
\begin{document}
Hello from a Make-built document.
\end{document}
INPUT_89_1
cat > Makefile <<'MAKEFILE'
LATEXMK ?= latexmk
FLAGS := -norc -pdf -no-shell-escape
FLAGS += -interaction=nonstopmode -halt-on-error
.DELETE_ON_ERROR:
.DEFAULT_GOAL := all
.PHONY: all clean distclean
all: build/main.pdf
build/main.pdf: main.tex | build
	@$(LATEXMK) $(FLAGS) -outdir=build main.tex > build/latexmk.log 2>&1 || \
	  { cat build/latexmk.log >&2; exit 1; }
build:
	@mkdir -p $@
clean:
	@$(LATEXMK) -norc -c -outdir=build main.tex > cleanup.log 2>&1 || \
	  { cat cleanup.log >&2; exit 1; }
distclean: clean
	@rm -rf -- build
MAKEFILE
m -s all
test -s build/main.aux
m -s clean
test -s build/main.pdf
test ! -e build/main.aux
test -s main.tex
printf "clean: PDF and source retained\n"
m -s distclean
test ! -e build
test -s main.tex
printf "distclean: generated directory removed, source retained\n"
m -s all
test -s build/main.pdf
printf "document rebuilt after cleanup\n"
