#!/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_83_1'
\documentclass{article}
\usepackage[backend=biber,style=numeric]{biblatex}
\addbibresource{references.bib}
\begin{document}
This fictional example cites a notebook~\cite{bossert2026}.
\printbibliography
\end{document}
INPUT_83_1
cat > references.bib <<'INPUT_83_2'
@book{bossert2026,
  author = {Lukas C. Bossert},
  title = {A Small Build Notebook},
  year = {2026},
  publisher = {Tour Examples}
}
INPUT_83_2
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
all: build/main.pdf
build/main.pdf: main.tex references.bib | build
	@$(LATEXMK) $(FLAGS) -outdir=build main.tex > build/latexmk.log 2>&1 || \
	  { cat build/latexmk.log >&2; exit 1; }
build:
	@mkdir -p $@
MAKEFILE
m -s all
test -s build/main.bcf
test -s build/main.bbl
grep -q 'bossert2026' build/main.bbl
pdftotext build/main.pdf first.txt
grep -q 'Small Build Notebook' first.txt
printf "Biber citation resolved\n"
sed 's/Small Build Notebook/Revised Build Notebook/' references.bib > references.bib.tmp
mv references.bib.tmp references.bib
touch -t 202001010101 main.tex build/main.pdf
touch -t 202101010101 references.bib
m -s all
pdftotext build/main.pdf revised.txt
grep -q 'Revised Build Notebook' revised.txt
if grep -Eq 'undefined citations|Please .*run Biber' build/main.log; then exit 1; fi
printf "changed bibliography appears in the PDF\n"
