#! /usr/bin/env bash

# Add (after removing old) \examdate LaTeX macro to file $2 (usually coursedefs.tex)
# based on information in file $1 (usually sylsup/schedule.tex).

if [[ $# -lt 2 ]]; then
  echo "Usage: addexemdates schedulefile macrofile"
  exit 1
fi

tempfile=/tmp/addexemdates.$USER.$$

# Follow each occurrence of \exam{1}, \exam{2}, etc. in schedule with
# space and parenthesized date or precede with parenthesized date and
# space; do same way for all.
grep -v '\\examdate' $2 > $tempfile
echo -n '\newcommand{\examdate}[1]{\ifcase#1' >> $tempfile
sed -n 's+.*\\exam{[0-9]*} (\([0-9/]*\)[ )].*+\\or\1+p' $1 | tr -d '\012' >> $tempfile
sed -n 's+.*(\([0-9/]*\)) \\exam{[0-9]*}.*+\\or\1+p' $1 | tr -d '\012' >> $tempfile
echo '\else??\fi} % auto-generated by addexamdates' >> $tempfile

if [[ `comm --nocheck-order -13 $tempfile $2 | wc -l` -le 1 ]]; then
  mv $tempfile $2
else
  echo "addexamdates: $2 not updated since removes more than one line of $tempfile"
fi
