#!/usr/bin/env bash
# Called from the catalog's Transifex project directory.
set -e
shopt -s nullglob
resource=$1
catalog_dir=$2
extension=$3
source_file=$4

command -v tx >/dev/null || { echo "Transifex client (tx) is required" >&2; exit 1; }
stage=$(mktemp -d .tx-pull.XXXXXXXX)
trap 'rm -rf -- "$stage"' EXIT
mkdir -p "$stage/$catalog_dir"
cp -R .tx "$stage/"
cp -- "$source_file" "$stage/"
(cd "$stage" && tx pull -r "antix-development.$resource" --all)

if [[ "$extension" == ts ]]; then
    # Keep the local English source. en_US duplicates it.
    rm -f -- "$stage/${resource}_en.ts" "$stage/${resource}_en_US.ts"
fi
downloaded=("$stage/$catalog_dir/${resource}_"*."$extension")
if (( ${#downloaded[@]} == 0 )); then
    echo "No translations downloaded for $resource" >&2
    exit 1
fi

# Publish by same-filesystem rename. Remove obsolete catalogs only after all
# downloaded files have been installed successfully.
obsolete=()
for existing in "$catalog_dir/${resource}_"*."$extension"; do
    [[ "$existing" -ef "$source_file" ]] && continue
    [[ -f "$stage/$existing" ]] || obsolete+=("$existing")
done
mkdir -p "$catalog_dir"
for catalog in "${downloaded[@]}"; do
    mv -f -- "$catalog" "$catalog_dir/"
done
if (( ${#obsolete[@]} )); then
    rm -- "${obsolete[@]}"
fi
