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

export LANG=C.UTF-8

for DICT in dictionaries/*.txt; do
  diff <(sort "$DICT") "$DICT" || {
    echo "The $DICT dictionary is unsorted. To fix it, run:" >&2
    echo "  LANG=C.UTF-8 sort doc/$DICT | sponge docs/$DICT" >&2
    exit 1
  }
done

OUT="$(mktemp)"
LANGS="$(jq -r .langs[] < ../metadata.json)"

for l in ${LANGS}; do
  make SPHINXOPTS="-D language=$l" html
  hunspell -u3 -H -d "$l" -p <(cat dictionaries/international.txt "dictionaries/$l.txt") _build/html/*.html | tee -a "$OUT"
done

if [[ -s "$OUT" ]]; then
  printf "\nvvv Mispelled words detected by hunspell.\n\n"
  sort < "$OUT" | uniq
  printf "\n^^^\n" >&2
  exit 1
else
  echo "No spelling errors detected"
  exit 0
fi
