#! /bin/bash
# Last edited on 2026-02-10 09:30:04 by stolfi

usage="$0 TEXFILE"

# Runs bibtex ${TEXFILE:r} and pdflatex ${TEXFILE} repeatedly until 
# the ".aux" and ".bbl" files are stable.

if [[ $# -ne 1 ]]; then 
  echo "usage: ${usage}" 1>&2; exit 1
fi

name="$1"; shift;

source "${STOLFIHOME}/lib/latex-parse-name.sh"
echo "run-pdflatex: name = ${name} ext = ${ext}" 1>&2

auxiliaries=( aux bbl toc lof lot bcf )
shopt -s nullglob
bibs=( *.bib )
shopt -u nullglob

# Make sure that the auxiliary targets exist:
echo "run-pdflatex: making sure that auxiliary files exist" 1>&2
for ext in ${auxiliaries[@]} ; do
  target="${name}.${ext}"
  if [[ ! -r ${target} ]]; then touch ${target}; fi
done

# Loop until convergence:
while [[ 1 ]]; do
  # Save current version of files:
  for ext in ${auxiliaries[@]} ; do
    target="${name}.${ext}"
    /bin/cp -v ${target} ${target}~~
  done
  
  # Run bibtex and pdflatex
  
  echo "processing ${#bibs[@]} bibliography files ${bibs[@]} ..." 1>&2
  if [[ ${#bibs[@]} -gt 0 ]]; then
    ls -ld ${name}.bcf
    biber --output-format=bibtex --output-resolve ${name}.bcf ${name}
    bibtex ${name}
    bibfailed=$?
    echo "run-pdflatex: bibtex status = $bibfailed" 1>&2
  else
    bibfailed=0
  fi
  
  which pdflatex
  pdflatex -shell-escape -file-line-error ${name} > ${name}.errs
  texfailed=$?
  echo "run-pdflatex: pdflatex status = $texfailed" 1>&2
  if [[ ${texfailed} ]]; then break; fi
  
  # Check if any of the result files changed:
  changed=0
  for ext in ${auxiliaries[@]} ; do
    target="${name}.${ext}"
    if [[ -s ${target} ]]; then
      if ! { cmp -s ${target} ${target}~~; } ; then
        echo "run-pdflatex: ${target} changed" 1>&2
        changed=1
        ( ls -l ${target}~~ ${target} ; \
            diff ${target}~~ ${target} \
            | prettify-diff-output z \
            | head -10 z \
        ) \
        | sed -e 's/^/  | /'
      fi
    else
      echo "run-pdflatex: ${target} not generated" 1>&2
    fi
  done
  if [[ ! ${changed} ]]; then break; fi
done

# Either bibtex/pdflatex failed or the process converged.
# Print the error messages

# cat ${name}.errs | tex-error-filter
cat ${name}.errs
echo "run-pdflatex: done" 1>&2

exit ${texfailed}
