#!/bin/bash
# Prepares and submits the Overleaf archives for every workplace.
#
# Usage: ./install-overleaf.sh [OPTION...]
#
# Options:
#
#   --only-generate : only produces the dist/ and overleaf/ directories
#   --only-upload   : only uploads the overleaf/ directories to Overleaf over Git
#   --only-publish  : only publishes the Overleaf documents to Overleaf Gallery
set -e
shopt -s extglob
shopt -s nullglob

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

if [[ $# != 0 && $1 != --only-publish && $1 != --only-upload && $1 != --only-generate ]]; then
  printf 'Unexpected "%s" parameter.\n' "$1" 2>&1
  exit 1
fi

if [[ $1 != --only-publish && $1 != --only-upload ]]; then

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

  # Prepare the files
  xetex muletter.ins
  latexmk -pdf muletter.dtx
  latexmk -c muletter.dtx
  rm *.{bbl,bib,glo,gls,hd,run.xml}
  (cd example
   xetex example.ins)
  mkdir /tmp/overleaf
  
  for WORKPLACE in ${WORKPLACES[@]}; do
    TMPDIR=/tmp/overleaf/$WORKPLACE
    mkdir -p $TMPDIR/muletter
    # Copy top-level example files
    cp -v example/{$WORKPLACE{,-color}.tex,signature.pdf} muletter.cls $TMPDIR
    # Copy remaining files
    tar cv {label,logo}/muletter-$WORKPLACE-{english,czech}{,-color}.pdf locale/*.def \
      muletter.{dtx,pdf,ins} LICENSE.tex README.md | tar xC $TMPDIR/muletter
    (cd $TMPDIR
     # Typeset top-level example files
     for DOCUMENT in $WORKPLACE*.tex; do
        latexmk -pdf $DOCUMENT &
     done
     wait
     latexmk -c $WORKPLACE*.tex
     # Prepare a zip archive
     zip -r ../$WORKPLACE *)
  done
  
  mv -v /tmp/overleaf dist
  cp -v -r --reflink=always dist overleaf
  rm -v overleaf/{*.zip,*/muletter/*.*}
  for WORKPLACE in ${WORKPLACES[@]}; do
    rm -v overleaf/$WORKPLACE/$WORKPLACE*.pdf
  done

fi

if [[ $1 != --only-publish && $1 != --only-generate ]]; then

  # Upload to Git.
  parallel --halt=2 --bar --jobs 9 -- ./install-overleaf-git-upload.sh ::: ${WORKPLACES[@]}

fi

if [[ $1 != --only-upload && $1 != --only-publish && $1 != --only-generate ]]; then

  # Sleep for a while to make sure that Overleaf is aware that a new version
  # has been uploaded.
  sleep 5s

fi

if [[ $1 != --only-upload && $1 != --only-generate ]]; then

  # Publish to Overleaf gallery.
  parallel --halt=2 --bar --jobs 1 -- 'overleaf-upload {} && sleep 5s' ::: \
    `for WORKPLACE in ${WORKPLACES[@]}; do echo overleaf-meta/$WORKPLACE/overleaf-upload.def; done`

fi

if [[ $1 != --only-upload && $1 != --only-publish && $1 != --only-generate ]]; then

  rm -rf overleaf

fi
