#!/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_87_1'
\documentclass{article}
\begin{document}
\section{Introduction}\label{sec:intro}
See section~\ref{sec:intro}.
\end{document}
INPUT_87_1
cat > latexmkrc <<'INPUT_87_2'
$pdflatex = 'pdflatex -no-shell-escape -interaction=nonstopmode -halt-on-error %O %S';
$max_repeat = 5;
INPUT_87_2
cat > Makefile <<'MAKEFILE'
LATEXMK ?= latexmk
.DELETE_ON_ERROR:
.DEFAULT_GOAL := all
.PHONY: all
all: build/main.pdf
build/main.pdf: main.tex latexmkrc | build
	@$(LATEXMK) -norc -r latexmkrc -pdf -outdir=build main.tex > build/latexmk.log 2>&1 || \
	  { cat build/latexmk.log >&2; exit 1; }
build:
	@mkdir -p $@
MAKEFILE
m -s all
pdftotext build/main.pdf text.txt
grep -q 'See section 1.' text.txt
if grep -Eq 'undefined references|Reference .* undefined' build/main.log; then exit 1; fi
m -q all
printf "project settings loaded; section reference resolved\n"
