#!/usr/bin/env bash

set -e

PYBABEL=${1:-pybabel}
POEDITOR_BASE_URL="https://api.poeditor.com/v2"

if [ -z "$POEDITOR_API_TOKEN" ]; then
  echo "POEDITOR_API_TOKEN is not set"
  exit 1
fi

if [ -z "$POEDITOR_PROJECT_ID" ]; then
  echo "POEDITOR_PROJECT_ID is not set"
  exit 1
fi

check_response() {
  local response=${1}
  local status_code

  status_code=$(echo "${response}" | jq -r ".response.code")

  if [ "${status_code}" -ne 200 ]; then
    local error_message
    error_message=$(echo "${response}" | jq -r '.response.message')
    echo "POEditor API call fails with message '${error_message}'"
    exit 1
  fi
}

echo "Starting i18n"

echo "Getting available locales"
locales_response=$(curl -s --fail -X POST "${POEDITOR_BASE_URL}/languages/list" \
     -d api_token="${POEDITOR_API_TOKEN}" \
     -d id="${POEDITOR_PROJECT_ID}"
     )
check_response "${locales_response}"

locales=$(echo "${locales_response}" | jq -r ".result.languages[].code")

echo "Extracting messages and generate template file"
${PYBABEL} extract -F babel.cfg -o messages.pot .

echo "Uploading terms from the template to POEditor"
curl -s --fail -X POST "${POEDITOR_BASE_URL}/projects/upload" \
     -F api_token="${POEDITOR_API_TOKEN}" \
     -F id="${POEDITOR_PROJECT_ID}" \
     -F updating='terms' \
     -F file=@'messages.pot' \
     -F sync_terms=1


for locale in $locales; do
  echo "Processing '${locale}' locale"
  locale_underscore="${locale//-/_}"

  echo "Creating translation file based on the template"
  ${PYBABEL} init -i messages.pot -d i18n -l "${locale_underscore}"

  echo "Fetching link to download translation file from POEditor"
  export_response=$(curl -s --fail -X POST "${POEDITOR_BASE_URL}/projects/export" \
      -d api_token="${POEDITOR_API_TOKEN}" \
      -d id="${POEDITOR_PROJECT_ID}" \
      -d language="${locale}" \
      -d type='po'
      )
  check_response "${export_response}"
  download_link=$(echo "${export_response}" | jq -r ".result.url")

  echo "Downloading translation file ${download_link}"
  curl -s --fail "${download_link}" --output "i18n/${locale_underscore}/LC_MESSAGES/messages.po"
done

echo "Compiling translation files"
${PYBABEL} compile -d i18n

echo "Done i18n"
