#! /usr/bin/env bash

set -euo pipefail

# 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

# check xgettext is installed
if ! command -v xgettext > /dev/null; then
  echo 'Please install the "xgettext" command (e.x. `brew install gettext`)'
  exit 1
fi

# switch to project root directory if we're not already there
script_directory=`dirname "${BASH_SOURCE[0]}"`
cd "$script_directory/../.."

source "./bin/check-clojure-cli.sh"
check_clojure_cli

POT_NAME="locales/metabase.po"
POT_BACKEND_NAME="locales/metabase-backend.pot"
# NOTE: hardcoded in .babelrc
POT_FRONTEND_NAME="locales/metabase-frontend.pot"
# NOTE: hardcoded in src/metabase/automagic_dashboards/dashboard_templates.clj
POT_AUTODASH_NAME="locales/metabase-automatic-dashboards.pot"

mkdir -p "locales"

#######################
# update frontend pot #
#######################

# NOTE: about twice as fast to call babel directly rather than a full webpack build
BABEL_ENV=extract ./node_modules/.bin/babel --quiet -x .js,.jsx,.ts,.tsx -o /dev/null {enterprise/,}frontend/src
# BABEL_ENV=extract BABEL_DISABLE_CACHE=1 yarn run build

# NOTE: replace ttag's "${ 0 }" style references with xgettext "{0}" style references for consistency
sed -i".bak" -E 's/\$\{ *([0-9]+) *\}/{\1}/g' "$POT_FRONTEND_NAME"
rm "$POT_FRONTEND_NAME.bak"

######################
# update backend pot #
######################

clojure -X:build i18n.enumerate/enumerate :filename "\"$POT_BACKEND_NAME\""

########################
# update auto dash pot #
########################

clojure -M:generate-automagic-dashboards-pot

##################
# merge all pots #
##################

msgcat "$POT_FRONTEND_NAME" "$POT_BACKEND_NAME" "$POT_AUTODASH_NAME" > "$POT_NAME"
