#!/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

WORKPLACES=(econ fi fsps fss law med ped pharm phil sci)

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/{fithesis,overleaf} ./overleaf

  # Prepare the files
  mkdir /tmp/{fithesis,overleaf}
  unzip -d /tmp/fithesis fithesis.tds.zip
  TDS=/tmp/fithesis/tex/latex/fithesis
  for fac in ${WORKPLACES[@]}; do
    OVERLEAF=/tmp/overleaf/$fac
    mkdir -p "$OVERLEAF"/fithesis &&
    cp example/mu/{$fac-*.tex,example.bib,example-terms-abbrs.tex} "$OVERLEAF"
    cp overleaf-meta/latexmkrc "$OVERLEAF"
    tar c "$TDS"/fithesis4.cls \
          "$TDS"/locale/{*.def,mu/{*.def,$fac/*.def}} \
          "$TDS"/style/{fithesis-base.sty,mu/fithesis-mu-{*.clo,{base,$fac}.sty}} \
          "$TDS"/logo/mu/fithesis-{base,$fac}{,-czech,-english,-slovak}{,-color}.pdf | tar xvC "$OVERLEAF"
    mv "$OVERLEAF$TDS"/* "$OVERLEAF"/fithesis
    mv "$OVERLEAF"/fithesis/fithesis4.cls "$OVERLEAF"/fithesis4.cls
    rm -rf "$OVERLEAF"/tmp
  done
  rm -rf /tmp/fithesis
  mv /tmp/overleaf .

fi

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


  # Upload to Git.
  parallel --halt=2 --bar --jobs 1 -- ./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 --ungroup -- '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
