#!/bin/bash

set -e
shopt -s extglob
shopt -s nullglob

WORKPLACES=(arch c4e ceitec cerit ctt czs econ fi fsps fss iba ics is kariera \
  lang law med mu muzeu ped pharm phil press ptceitec rect rect-office sci skm teiresias ucb \
  uct)

# Clean up
rm -rf /tmp/overleaf overleaf dist

# Prepare the files
xetex mubeamer.ins
latexmk -pdf mubeamer.dtx
latexmk -c mubeamer.dtx
rm *.{bbl,bib,glo,gls,hd,run.xml}
pushd example
xetex example.ins
popd
mkdir /tmp/overleaf

for WORKPLACE in ${WORKPLACES[@]}; do
  TMPDIR=/tmp/overleaf/$WORKPLACE
  mkdir -p $TMPDIR/mubeamer
  # Copy top-level example files
  cp -v example/{$WORKPLACE{,-aspect-16_{9,10},-czech,-slovak,-fonts-lmodern,-gray,-xetex-luatex}.tex,example.bib} \
    beamerthemeMU.sty `kpsewhich cow-black.mps` $TMPDIR
  # Copy remaining files
  (
    shopt -s nullglob
    tar cv {logo,label}/mubeamer-{mu,$WORKPLACE}-*.pdf mubeamer.{dtx,pdf,ins} \
      LICENSE.tex README.md | tar xC $TMPDIR/mubeamer
  )
  if test -e patch/mubeamer-$WORKPLACE.sty; then
    tar cv patch/mubeamer-$WORKPLACE.sty | tar xC $TMPDIR/mubeamer
  fi
  pushd $TMPDIR
  # Typeset top-level example files
  for DOCUMENT in $WORKPLACE{,-!(xetex-luatex)}.tex; do
     latexmk -pdf $DOCUMENT &
  done
  latexmk -lualatex $WORKPLACE-xetex-luatex.tex &
  wait
  latexmk -c $WORKPLACE{,-*}.tex
  rm -rf par-*/
  rm *.{nav,snm,run.xml,bbl}
  # Prepare a zip archive
  zip -r ../$WORKPLACE *
  popd
done

mv -v /tmp/overleaf dist
mv dist/*.zip public/
