#!/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_85_1'
\documentclass{article}
\begin{document}
\section*{Stock counts}
\begin{tabular}{lr}
Item & Count \\
\hline
\input{tables/rows}
\end{tabular}
\end{document}
INPUT_85_1
cat > data.tsv <<'INPUT_85_2'
books 4
pens 2
INPUT_85_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
tables/rows.tex: data.tsv | tables
	@printf "generate table rows\n"
	@awk '{printf "%s & %d \\\\\n", $$1, $$2}' $< > $@.tmp && mv $@.tmp $@
build/main.pdf: main.tex tables/rows.tex | build
	@printf "compile document with table\n"
	@$(LATEXMK) $(FLAGS) -outdir=build main.tex > build/latexmk.log 2>&1 || \
	  { cat build/latexmk.log >&2; exit 1; }
build tables:
	@mkdir -p $@
MAKEFILE
m -s all
m -q all
printf "books 7\npens 2\n" > data.tsv
touch -t 202001010101 main.tex tables/rows.tex build/main.pdf
touch -t 202101010101 data.tsv
m -s all
grep -Fq 'books & 7 \\' tables/rows.tex
pdftotext -layout build/main.pdf text.txt
grep -Eq 'books[[:space:]]+7' text.txt
printf "edited data appears in the table and PDF\n"
