#!/usr/bin/env bash
set -Eeuo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
cd ../

OUT="${1}"
HTMLIZE="${2}"
PROJECT_UC="__PROJECT_UC__"

sed -e '/^\* Tasks$/,/^\* Improvements$/!d' TODOs.org | \
  head -n -1                                          | \
  cat workflow/preamble.org - > tasks-and-bugs.org

emacs tasks-and-bugs.org                               \
      -l "${HTMLIZE}"                                  \
      --eval '(setq org-export-allow-bind-keywords t)' \
      -f org-html-export-to-html                       \
      --batch                                          \
      --kill

# Add anchor link to bug headers
perl -pe \
     's|^<h3 id="(.*?)">(.*)</h3>$|<h3 id="\1">\2<br /><a class="header-anchor" href="#\1">#\1</a></h3>|' \
    tasks-and-bugs.html > "$OUT/tasks-and-bugs.html"

pushd docs
make html
popd

cp docs/favicon.ico "$OUT"
mv docs/_build/html/_static/ "$OUT/_static/"

CURRENT_LANG="$(jq -r .current_lang < metadata.json)"
LANGS="$(jq -r .langs[] < metadata.json)"
TAGS="$(git tag | cat - <(echo master))"

for lang in ${LANGS}; do
  for tag in ${TAGS}; do
    mkdir -p "tmp/$lang/$tag/"
    git --work-tree="tmp/$lang/$tag/" checkout --recurse-submodules "$tag" -- .
    git reset .
    git checkout .

    pushd "tmp/$lang/$tag/docs/"
    jq ".version = \"$tag\"" ../metadata.json | sponge ../metadata.json

    RENAMES="$(jq ".$lang" < ../docs/i18n-pagenames.json      | \
                 jq -r 'to_entries[] | [.key, .value] | @csv' | \
                 tr -d '\"')"

    if [[ "$lang" != "$CURRENT_LANG" ]]; then
      for rename in $RENAMES; do
        from="$(echo "$rename" | cut -d, -f1)"
        to="$(echo "$rename"   | cut -d, -f2)"
        mv "${from}.rst" "${to}.rst"
        sed -i "s/^   $from$/   $to/" index.rst
      done
    fi

    make SPHINXOPTS="-D language=$lang" latexpdf epub singlehtml html
    popd

    mkdir "$OUT/$lang/"

    mv "tmp/$lang/$tag/docs/_build/html/" "$OUT/$lang/$tag/"
    pushd "$OUT/$lang/$tag/"
    rm -rf _static/
    ln -s ../../_static .
    popd

    mv "tmp/$lang/$tag/docs/_build/singlehtml/" "$OUT/$lang/$tag/single/"
    pushd "$OUT/$lang/$tag/single/"
    rm -rf _static/
    ln -s ../../../_static .
    rm -rf _images/
    ln -s ../_images .
    popd

    mv "tmp/$lang/$tag/docs/_build/latex/${PROJECT_UC,,}.pdf" "$OUT/$lang/$tag/${PROJECT_UC}.pdf"
  done
done
