#!/bin/bash

# Everything below is relative to this directory, wherever the script is run from.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR" || exit 1
APPNAME="$(basename "$(dirname "$SCRIPT_DIR")")-desktop"

echodo() {
  echo "${@}"
  ${@}
}

# prepare transifex 
if [ ! -s  .tx/config ]; then
   mkdir -p .tx
   cat <<EOF > .tx/config
[main]
host = https://www.transifex.com

[o:anticapitalista:p:antix-development:r:$APPNAME]
file_filter = po/${APPNAME}_<lang>.po
source_file = ${APPNAME}.pot
source_lang = en
type = po
EOF
fi    


if ! command -v tx >/dev/null; then
   echo "Error: tx (Transifex client) not found; existing translations were left untouched."
   exit 1
fi

# Set the existing catalogs aside so languages dropped on Transifex are pruned,
# and put them back if the pull fails or is interrupted so local edits are not
# lost. The backup lives next to po/, so moving there is a rename.
mkdir -p po
BACKUP_DIR="$(mktemp -d "$SCRIPT_DIR/.po-backup.XXXXXX")" || exit 1
shopt -s nullglob dotglob

# Move the backed-up catalogs back (without deleting anything).
undo_backup() {
   restored=("$BACKUP_DIR"/*)
   if [ "${#restored[@]}" -gt 0 ]; then
      mv "${restored[@]}" po/
   fi
   rmdir "$BACKUP_DIR"
}

# Drop whatever the pull wrote, then put the previous catalogs back.
restore_catalogs() {
   trap '' INT TERM # a second restore would delete the catalogs just put back
   rm -rf po/*
   undo_backup
}

backup=(po/*)
if [ "${#backup[@]}" -gt 0 ] && ! mv "${backup[@]}" "$BACKUP_DIR/"; then
   echo "Error: could not back up po/; restoring the previous translations."
   undo_backup
   exit 1
fi
trap 'echo "Interrupted; restoring the previous translations."; restore_catalogs; exit 130' INT TERM

# get all translations
if ! echodo tx pull -r antix-development.$APPNAME --all; then
   echo "Error: tx pull failed; restoring the previous translations."
   restore_catalogs
   exit 1
fi
pulled=(po/*.po)
if [ "${#pulled[@]}" -eq 0 ]; then
   echo "Error: tx pull returned no translations; restoring the previous translations."
   restore_catalogs
   exit 1
fi
trap - INT TERM
rm -rf "$BACKUP_DIR"
shopt -u nullglob dotglob

