#! /bin/bash
# Last edited on 2024-03-31 18:51:09 by stolfi

usage="$0 JOBNAME[.tex|.iso|]"

# Deletes any existing "JOBNAME.bbl" and "JOBNAME.aux" files, then
# runs LaTeX on JOBNAME. Assumes the TeX paths and environment
# variables are properly set.
#
# If LaTeX terminates correctly, deletes all results except the ".aux" file.
# If the new ".aux" file is identical to the previous one, leaves the previous one.
# If LaTeX terminates with error, deletes the ".aux" file and
# exits with error.

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

name="$1"; shift;

source "${STOLFIHOME}/lib/latex_parse_name.sh"

results=( bbl toc lof lot dvi ) 
resultx="echo ${results[@]} | /bin/tr ' ' ','" 1>&2
target=${name}.aux

if [[  -r ${target}  ]]; then
  /bin/mv ${target} ${target}~~
fi

latex "${name}" |& ${STOLFIHOME}/bin/${PLATFORM}/tex-error-filter
texstat=$status 

for rex in ${results[@]} ; do 
  if [[ -e ${name}.${rex} ]]; then
    /bin/mv -v ${name}.${rex} ${name}.${rex}~~
  fi
done

if [[ $texstat ]]; then
  /bin/rm -fv ${target}
  echo "** latex failed, ${target} not created" 1>&2
  exit 1
elif [[  { cmp -s ${target} ${target}~~ }  ]]; then
  /bin/mv -v ${target}~~ ${target}
  echo "${target} not changed" 1>&2
  exit 0
else
  echo "${target} changed" 1>&2
  exit 0
fi  
