#!/bin/bash

cd $(dirname -- "${BASH_SOURCE[0]}")
FASCS=("8a" "8b" "9b" "9c" "12a" "14a" "16a" "20a")
mkdir -p tmp/

echo "$(date)"

for FASC in "${FASCS[@]}"; do
  FILE="fasc${FASC}"
  echo "Downloading $FILE"
  wget "https://www-cs-faculty.stanford.edu/~knuth/${FILE}.ps.gz" -O tmp/${FILE}.ps.gz

  if [ $? -eq 0 ]; then
    gunzip tmp/${FILE}.ps.gz
    perl ./pkfix.pl tmp/${FILE}.ps tmp/${FILE}-fixed.ps
    ps2pdf tmp/${FILE}-fixed.ps tmp/${FILE}.pdf
    if [ -f "./${FILE}.pdf" ]; then
      if ! cmp -s ./${FILE}.pdf tmp/${FILE}.pdf; then
        echo "- Found new version"
	mv tmp/${FILE}.pdf ./${FILE}.pdf
        touch --reference=tmp/${FILE}.ps ./${FILE}.pdf
      else
        echo "- No changes found"
        rm tmp/${FILE}.pdf
      fi
    else
      echo "- Found new version"
      mv tmp/${FILE}.pdf ./${FILE}.pdf
      touch --reference=tmp/${FILE}.ps ./${FILE}.pdf
    fi
  else
    echo "- Error"
  fi
done

echo "Done"
rm tmp/*
