#!/bin/sh
set -eu

export LANG=C.UTF-8

for DICT in dictionaries/*.txt; do
  sort "$DICT" | diff - "$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
  DICT="$(mktemp)"
  cat dictionaries/international.txt "dictionaries/$l.txt" > "$DICT"
  hunspell -u3 -H -d "$l" -p "$DICT" _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
