#!/bin/sh

set -eu

# gettext installed via homebrew is "keg-only", add it to the PATH
if [ -d "/usr/local/opt/gettext/bin" ]; then
  export PATH="/usr/local/opt/gettext/bin:$PATH"
fi

POT_NAME="locales/metabase.pot"
LOCALES=$(find locales -type f -name "*.po" -exec basename {} .po \;)

if [ -z "$LOCALES" ]; then
  LOCALES_QUOTED=""
else
  LOCALES_QUOTED=" $(echo "$LOCALES" | awk '{ printf "\"%s\" ", $0 }')"
fi

FRONTEND_LANG_DIR="resources/frontend_client/app/locales"

# backend
# NOTE: include "en" even though we don't have a .po file for it because it's the default?
cat << EOF > "resources/locales.clj"
{
  :locales  #{"en"$LOCALES_QUOTED}
  :packages ["metabase"]
  :bundle   "metabase.Messages"
}
EOF

mkdir -p "$FRONTEND_LANG_DIR"

for LOCALE in $LOCALES; do
  LOCALE_FILE="locales/$LOCALE.po"
  LOCALE_WITH_UNDERSCORE=$(echo "$LOCALE" | tr '-' '_')
  # frontend
  # NOTE: just copy these for now, but eventially precompile from .po to .json
  ./bin/i18n/build-translation-frontend-resource \
    "$LOCALE_FILE" \
    "$FRONTEND_LANG_DIR/$LOCALE_WITH_UNDERSCORE.json"

  # backend
  msgfmt                            \
    --java2                         \
    -d "resources"                  \
    -r "metabase.Messages" \
    -l "$LOCALE_WITH_UNDERSCORE"    \
    "$LOCALE_FILE"
done
