#!/bin/bash

set -euo pipefail

readonly NO_ERROR=0
readonly ERROR_UNTRANSLATED_STRINGS=1 # this error could be ignorable
readonly ERROR_MSGMERGE=2

readonly PODIR="po"
readonly PROJECT_SOURCE_DIR="."
readonly POTFILETMP="$PODIR/tigervnc.pot.tmp"

readonly SOURCES=$(find vncviewer -type f \( -name '*.h' -o -name '*.cxx' -o -name '*.desktop.in.in' \))

cleanup() {
	rm -f "$POTFILETMP"
}
trap cleanup EXIT

# Update temporaty POT file
xgettext \
  --directory="${PROJECT_SOURCE_DIR}" \
  --output="$POTFILETMP" \
  --default-domain=tigervnc \
  --keyword=_ \
  --keyword=p_:1c,2 \
  --keyword=N_ \
  --copyright-holder="TigerVNC Team and many others (see README.rst)" \
  --msgid-bugs-address=tigervnc-devel@googlegroups.com \
  --sort-by-file \
  --add-comments=TRANSLATORS \
  --from-code=UTF-8 \
  $SOURCES

readonly POFILES=$(find "$PODIR" -type f -name 'de.po' -o -name 'es.po')

EXIT_CODE=$NO_ERROR

for POFILE in $POFILES; do
	cp -a "${POFILE}" "${POFILE}.bak"

	# Update PO file with new translations
	if ! msgmerge --quiet --update --no-location --no-wrap "${POFILE}" "$POTFILETMP" > /dev/null; then
		echo "Failed to run msgmerge. Aborting..."
		mv "${POFILE}.bak" "${POFILE}"
		EXIT_CODE=$ERROR_MSGMERGE
		break
	fi

	# Revert if only POT-Creation-Date line changed
	if diff --ignore-matching-lines='POT-Creation-Date' "${POFILE}" "${POFILE}.bak" >/dev/null; then
		mv "${POFILE}.bak" "${POFILE}"
	else
		rm "${POFILE}.bak"
	fi

	# Check for untranslated strings
	if grep -q "fuzzy" "${POFILE}" || perl -0777 -ne 'exit 0 if /msgstr ""\n\n/; exit 1' "${POFILE}"; then
		echo "At least one untranslated string in ${POFILE} (the word 'fuzzy' appears or there is an msgstr \"\"\n\n)"
		# Only exit with an error if it's German the language with untranslated strings
		POBASENAME=$(basename ${POFILE})
		[[ "$POBASENAME" != "de.po" ]] && EXIT_CODE=$ERROR_UNTRANSLATED_STRINGS
	fi
done

exit $EXIT_CODE
