#!/usr/bin/env bash

# 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 "$PROJECT_DIR" || exit 1

echodo() {
  printf '%q ' "$@"
  printf '\n'
  "$@"
}

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

# Migrate configurations created before catalogs moved under translations/.
sed -i \
    -e "s|^file_filter = \./${APPNAME}_<lang>\.ts$|file_filter = translations/${APPNAME}_<lang>.ts|" \
    -e "s|^source_file = ${APPNAME}_en\.ts$|source_file = translations/${APPNAME}_en.ts|" \
    .tx/config

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

# Get all translations
if command -v tx >/dev/null; then
   echodo tx pull -r "antix-development.$APPNAME" --all
fi

# en_US duplicates the English source catalog and should not be shipped.
rm -f "translations/${APPNAME}_en_US.ts"

# 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"

# Update all catalogs from C++ and QML sources.
mapfile -d '' SOURCE_FILES < <(find src qml -type f \( -name '*.cpp' -o -name '*.h' -o -name '*.qml' \) -print0)
mapfile -d '' TRANSLATION_FILES < <(find translations -maxdepth 1 -type f -name '*.ts' -print0)
if [ "${#SOURCE_FILES[@]}" -gt 0 ] && [ "${#TRANSLATION_FILES[@]}" -gt 0 ]; then
    "$LUPDATE" "${SOURCE_FILES[@]}" -ts "${TRANSLATION_FILES[@]}"
fi
