#!/bin/sh
set -eux

PACKAGE="$1"
shift

dictname() {
  case "$1" in
    en)
      echo en_US-large
      ;;
    *)
      echo "Unsupported dictionary type $1"
      exit 1
      ;;
  esac
}

OUT="$(mktemp)"
CLONE="$(mktemp -d)"
rsync -a . "$CLONE"
cd "$CLONE"

for tag in master $(git tag); do
  git checkout "$tag"
  for lang in "$@"; do
    mkdir -p "public/$lang/$tag/"

    make html
    mv "doc/$PACKAGE.html/" "public/$lang/$tag/doc/"

    make MAKEINFOFLAGS=--no-split html ps dvi pdf
    mv -t "public/$lang/$tag/" "doc/$PACKAGE.dvi" "doc/$PACKAGE.ps" "doc/$PACKAGE.pdf" "doc/$PACKAGE.html"

    makeinfo --docbook "doc/$PACKAGE.texi" -o "$PACKAGE.docbook"
    xsltproc build-aux/docbook-xsl/epub/docbook.xsl "$PACKAGE.docbook"
    echo "application/epub+zip" > mimetype
    zip -0Xq "$PACKAGE.epub" mimetype
    zip -Xr9D "$PACKAGE.epub" META-INF OEBPS
    mv "$PACKAGE.epub" "public/$lang/$tag/"

    cat doc/dictionaries/international.txt "doc/dictionaries/$lang.txt" > doc/dictionaries/curr.txt
    hunspell -u -H -d "$(dictname "$lang")" -p doc/dictionaries/curr.txt "public/$lang/$tag/$PACKAGE.html" | tee -a "$OUT"
  done
done

cd -
rm -rf public/
mv "$CLONE/public/" public/

if [ -s "$OUT" ]; then
  echo "Misspelled words detected:"
  cat "$OUT"
  exit 1
fi
