#!/usr/bin/env bash

set -e

# Get script directory and determine app name
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
APPNAME="$(basename "$PROJECT_DIR")"

cd "$SCRIPT_DIR"
command -v tx >/dev/null || { echo "Transifex client (tx) is required" >&2; exit 1; }

# 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 = ./${APPNAME}_<lang>.ts
source_file = ${APPNAME}_en.ts
source_lang = en
type        = ts
minimum_perc = 25
EOF
fi

# Migrate percent checking
if ! grep -q minimum_perc .tx/config; then
        echo "minimum_perc = 25" >> .tx/config
fi

# Find lupdate command in common locations
LUPDATE=""
for cmd in lupdate lupdate-qt6 /usr/lib/qt6/bin/lupdate /usr/bin/lupdate /usr/local/bin/lupdate; do
    if command -v "$cmd" >/dev/null 2>&1; then
        LUPDATE="$cmd"
        break
    fi
done

if [ -z "$LUPDATE" ]; then
    echo "Error: lupdate command not found. Please install Qt development tools."
    exit 1
fi

echo "Using lupdate: $LUPDATE"

# Download and update the English catalog before replacing any local files.
# A sibling of translations keeps lupdate source locations relative to ../src.
stage=$(mktemp -d "$PROJECT_DIR/.tx-pull.XXXXXXXX")
trap 'rm -rf -- "$stage"' EXIT
mkdir "$stage/.tx"
cp .tx/config "$stage/.tx/config"
cp "${APPNAME}_en.ts" "$stage/"
(cd "$stage" && tx pull -r "antix-development.$APPNAME" --all)
rm -f -- "$stage/${APPNAME}_en_US.ts"

shopt -s nullglob
catalogs=("$stage/${APPNAME}_"*.ts)
if (( ${#catalogs[@]} < 2 )); then
    echo "Transifex returned no translated catalogs" >&2
    exit 1
fi
for catalog in "${catalogs[@]}"; do
    if [[ ! -s "$catalog" ]]; then
        echo "Empty catalog: ${catalog##*/}" >&2
        exit 1
    fi
done
"$LUPDATE" "$PROJECT_DIR/src" -ts "$stage/${APPNAME}_en.ts"

for catalog in "${APPNAME}_"*.ts; do
    if [[ ! -f "$stage/$catalog" ]]; then
        rm -- "$catalog"
    fi
done
mv -- "${catalogs[@]}" "$SCRIPT_DIR/"
