#!/usr/bin/env bash
set -euo pipefail
shopt -s nullglob

translations_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
project_dir=$(dirname -- "$translations_dir")
app=mx-datetime
sources=("$project_dir"/*.cpp "$project_dir"/*.h "$project_dir"/*.ui)
if (( ${#sources[@]} == 0 )); then
    echo "No C++, header, or UI sources found in $project_dir" >&2
    exit 1
fi
if ! command -v tx >/dev/null; then
    echo "The Transifex client (tx) is required to refresh translations." >&2
    exit 1
fi
lupdate=
for candidate in lupdate-qt6 /usr/lib/qt6/bin/lupdate lupdate; do
    if command -v "$candidate" >/dev/null; then
        lupdate=$candidate
        break
    fi
done
if [[ -z $lupdate ]]; then
    echo "Qt lupdate is required to extract source strings." >&2
    exit 1
fi

# Stage at the same depth as translations/ so lupdate records the same relative paths.
stage=$(mktemp -d "$project_dir/.translation-refresh.XXXXXXXX")
trap 'rm -rf -- "$stage"' EXIT
cd -- "$stage"
mkdir .tx
if [[ -s $translations_dir/.tx/config ]]; then
    # Keep project settings while directing all downloads into the staging directory.
    sed -E "s|^[[:space:]]*file_filter[[:space:]]*=.*|file_filter = ${app}_<lang>.ts|; s|^[[:space:]]*source_file[[:space:]]*=.*|source_file = ${app}_en.ts|" \
        "$translations_dir/.tx/config" > .tx/config
else
    cat > .tx/config <<CONFIG
[main]
host = https://www.transifex.com

[o:anticapitalista:p:antix-development:r:$app]
file_filter = ${app}_<lang>.ts
source_file = ${app}_en.ts
source_lang = en
type = ts
CONFIG
fi
if ! grep -Eq '^[[:space:]]*minimum_perc[[:space:]]*=' .tx/config; then
    echo 'minimum_perc = 25' >> .tx/config
fi

tx pull -r "antix-development.$app" --all
# English is regenerated below. US English duplicates the source catalog.
rm -f -- "${app}_en.ts" "${app}_en_US.ts"
downloads=("${app}_"*.ts)
if (( ${#downloads[@]} == 0 )); then
    echo "Transifex returned no translation catalogs." >&2
    exit 1
fi
for catalog in "${downloads[@]}"; do
    if [[ ! -s $catalog ]]; then
        echo "Transifex returned an empty catalog: $catalog" >&2
        exit 1
    fi
done

english=${app}_en.ts
if [[ -f $translations_dir/$english ]]; then
    cp -- "$translations_dir/$english" "$english"
fi
"$lupdate" "${sources[@]}" -ts "$english"

# Publish complete refreshes one at a time. Prune obsolete locales last.
exec {lock_fd}<"$translations_dir"
flock -x "$lock_fd"
obsolete=()
for catalog in "$translations_dir/${app}_"*.ts; do
    if [[ ! -f ${catalog##*/} ]]; then
        obsolete+=("$catalog")
    fi
done
mv -f -- "${app}_"*.ts "$translations_dir/"
if (( ${#obsolete[@]} )); then
    rm -- "${obsolete[@]}"
fi
