#!/bin/bash

# pull transifex resouces to generate a combined pot/po-files
#
# transifex resources to pull
TX_RESOURCES_FILE=./RESOURCES
[ ! -f $TX_RESOURCES_FILE ] && echo "Error: Transifex resouce file '$TX_RESOURCES_FILE' not found!" && exit 1

unset TX_RESOURCES
readarray -t TX_RESOURCES < <(
	   sed -rn '/^[[:space:]]*[[:alpha:]]+/{s/^[[:space:]]+//; s/[[:space:]]+$//; p}' \
	   $TX_RESOURCES_FILE \
	   )

#  set default msg filter
MSGGREP=( -X -E -e "desktop entry (name|comment)" )
MSGGREP=( -X -E -e "desktop entry name" )

# need 'latest' transifex client
: ${TXBIN:=$(which tx)}
[ ! -x "$TXBIN" ] && echo "Error: transifex client not found!" && exit 1

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

#  fehlix test project do not use
#: ${ORGANIZATION:=fehlix}
#: ${PROJECT:=testproject-do-not-use}

# set minium translations completion in percent to pull translation
: ${MINIMUM_PERC:=10}
export MINIMUM_PERC

# set transifex organization and project name - if not set in environment already
: ${ORGANIZATION:=anticapitalista}
: ${PROJECT:=antix-development}

PODIR=po
[ -d ${PODIR} ] && echodo cp -a ${PODIR} ${PODIR}_$(date '+%y.%m%d_%H%M%S').bak~
[ -d ${PODIR} ] || echodo mkdir ${PODIR}

# perpare mesonbuild
if [ ! -f ${PODIR}/meson.build ]; then
    cat <<'MESONBUILD' > ${PODIR}/meson.build
i18n = import('i18n')
i18n.gettext(meson.project_name(), preset: 'glib' )
MESONBUILD
fi

for PO in ${PODIR}/*.po; do
    [ -e "$PO" ] || continue
    CAT=${PO}.cat
    mv $PO $CAT
done

for RESOURCE in "${TX_RESOURCES[@]}"; do
    # adjust msg filter for msggrep
    case "$RESOURCE" in
		disk-manager) MSGGREP=( --msgid -E -e "Disk Manager" ) ;;
	esac

    POTFILE="$RESOURCE".pot
    # prepare transifex 
    [ -d .tx         ] || mkdir -p .tx
    [ -f  .tx/config ] && rm  .tx/config
    
    cat <<EOF > .tx/config
[main]
host = https://app.transifex.com

[o:${ORGANIZATION}:p:${PROJECT}:r:${RESOURCE}]

file_filter = ${PODIR}/<lang>.po
minimum_perc = ${MINIMUM_PERC:=10}
resource_name = ${RESOURCE}
source_file = ${POTFILE}
source_lang = en
type = PO
EOF
    
    # set transifex resource_id
    RESOUCE_ID="${PROJECT}.${RESOURCE}"
    
    TXOPTS=( pull --force  --all "$RESOUCE_ID" )
    # TXOPTS=( pull --force  --languages "de,el,fr_BE" "$RESOUCE_ID")
    echo ${TXBIN} "${TXOPTS[@]@Q}"
    ${TXBIN} "${TXOPTS[@]}"

    
    for PO in ${PODIR}/*.po; do
        [ -e "$PO" ] || continue
        CAT=$PO.cat
        GPO=$PO.gpo~
        PAT=$PO.tmp
        touch $CAT

        msggrep --force-po --no-location --no-wrap "${MSGGREP[@]}" -o $GPO $PO
        msgcat  --force-po --use-first --no-wrap  --no-location -o $PAT $CAT $GPO 
        mv $PAT $CAT
        rm $GPO
    done
done

for CAT in ${PODIR}/*.po.cat; do
    [ -e "$CAT" ] || continue
    PO=${CAT%.cat}
    mv $CAT $PO
done

# re-generate pot file based on po-files
[ -x ./make-pot ] &&  ./make-pot

# re-generate translation completion report
[ -x ./tx-complete-log ] &&  ./tx-complete-log 
