#!/usr/bin/env bash
# Called from the Qt or desktop translations directory by get_translations.
set -eu
shopt -s nullglob

if ! command -v tx >/dev/null; then
    echo "Cannot download translations: the Transifex client (tx) is missing." >&2
    exit 1
fi

resource="file-rewind"
case $1 in
    qt)
        catalogDir=.
        extension=ts
        sourceFile=${resource}_en.ts
        ;;
    desktop)
        resource+=-desktop
        catalogDir=po
        extension=po
        sourceFile=${resource}.pot
        ;;
    *) exit 2 ;;
esac

if [[ ! -s .tx/config ]]; then
    mkdir -p .tx
    cat > .tx/config <<EOF
[main]
host = https://www.transifex.com

[o:anticapitalista:p:antix-development:r:$resource]
file_filter = $catalogDir/${resource}_<lang>.$extension
source_file = $sourceFile
source_lang = en
type = $extension
EOF
fi
if [[ $1 == qt ]] && ! grep -q minimum_perc .tx/config; then
    echo "minimum_perc = 25" >> .tx/config
fi

# A sibling of the catalog directory keeps ../src locations in the English TS correct.
stage=$(mktemp -d ../.translation-refresh.XXXXXXXX)
trap 'rm -rf -- "$stage"' EXIT
mkdir -p "$stage/.tx" "$stage/$catalogDir"
# Keep settings such as the language map and completion threshold, but bind
# download paths to the staging directory even if the local config uses absolute paths.
awk -v filter="$catalogDir/${resource}_<lang>.$extension" -v src="$sourceFile" '
    /^[[:space:]]*file_filter[[:space:]]*=/ { print "file_filter = " filter; next }
    /^[[:space:]]*source_file[[:space:]]*=/ { print "source_file = " src; next }
    /^[[:space:]]*trans\.[^=]+=/ { next }
    { print }
' .tx/config > "$stage/.tx/config"
if [[ -f $sourceFile ]]; then
    cp -- "$sourceFile" "$stage/$sourceFile"
elif [[ $1 == desktop && -f pot/$sourceFile ]]; then
    cp -- "pot/$sourceFile" "$stage/$sourceFile"
fi
(cd -- "$stage" && tx pull -r "antix-development.$resource" --all)

catalogs=()
for file in "$stage/$catalogDir/${resource}_"*."$extension"; do
    if [[ ${file##*/} == "$sourceFile" ]]; then
        continue
    fi
    if [[ ! -f $file || -L $file || ! -s $file ]]; then
        echo "No usable translation in ${file##*/}." >&2
        exit 1
    fi
    catalogs+=("$file")
done
if (( ${#catalogs[@]} == 0 )); then
    echo "The download contained no translation catalogs for $resource." >&2
    exit 1
fi

if [[ $1 == qt ]]; then
    lupdate=
    for cmd in lupdate lupdate-qt6 /usr/lib/qt6/bin/lupdate; do
        if command -v "$cmd" >/dev/null; then
            lupdate=$cmd
            break
        fi
    done
    if [[ -z $lupdate ]]; then
        echo "Cannot update the English catalog: install the Qt development tools (lupdate)." >&2
        exit 1
    fi
    cp -- "$sourceFile" "$stage/$sourceFile"
    "$lupdate" ../src -extensions cpp,h,ui -pluralonly -ts "$stage/$sourceFile"
    [[ -s $stage/$sourceFile ]]
    catalogs+=("$stage/$sourceFile")
fi

# Keep one publisher per catalog directory while the old set is being replaced.
mkdir -p "$catalogDir"
exec 9< "$catalogDir"
flock -x 9
backup=$stage/previous
mkdir -- "$backup"
declare -A received
changed=()
stale=()
for file in "${catalogs[@]}"; do
    name=${file##*/}
    received[$name]=1
    dest=$catalogDir/$name
    if [[ -e $dest || -L $dest ]]; then
        if [[ ! -f $dest ]]; then
            echo "Cannot replace $dest: it is not a catalog file." >&2
            exit 1
        fi
        cp -a -- "$dest" "$backup/$name"
    fi
done
for dest in "$catalogDir"/*."$extension"; do
    name=${dest##*/}
    if [[ -f $dest && $name != "$sourceFile" && -z ${received[$name]+present} ]]; then
        stale+=("$dest")
    fi
done

finishPublish() {
    local result=$? dest saved rollbackFailed=false
    if (( result != 0 )); then
        for dest in "${changed[@]}"; do
            saved=$backup/${dest##*/}
            if [[ -e $saved || -L $saved ]]; then
                mv -fT -- "$saved" "$dest" || rollbackFailed=true
            else
                rm -f -- "$dest" || rollbackFailed=true
            fi
        done
        if [[ $rollbackFailed == true ]]; then
            echo "Could not restore every catalog. Remaining backups are in $backup." >&2
            exit 1
        fi
    fi
    rm -rf -- "$stage"
}
trap finishPublish EXIT
for file in "${catalogs[@]}"; do
    dest=$catalogDir/${file##*/}
    mv -fT -- "$file" "$dest"
    changed+=("$dest")
done
for dest in "${stale[@]}"; do
    mv -T -- "$dest" "$backup/${dest##*/}"
    changed+=("$dest")
done
