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

OUT='public'
PROJECT_UC="__PROJECT_UC__"

pushd doc
make html
popd

cp doc/favicon.ico "$OUT"
mv doc/_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/doc/"
    jq ".version = \"$tag\"" ../metadata.json | sponge ../metadata.json

    RENAMES="$(jq ".$lang" < ../doc/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 singlehtml html
    popd

    mkdir "$OUT/$lang/"

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

    mv "tmp/$lang/$tag/doc/_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/doc/_build/latex/${PROJECT_UC,,}.pdf" "$OUT/$lang/$tag/${PROJECT_UC}.pdf"
  done
done

gitstats . "$OUT/gitstats/"
