#!/usr/bin/bash
shopt -s nullglob

if [ ! -d po ]; then
    echo "Run this script in the top source directory"
    exit 1
fi

git update-index -q --refresh >/dev/null 2>&1
if [ -n "$(git diff-index --name-only HEAD --)" ]; then
    echo "Run this script only without uncommited changes"
    exit 1
fi

if command -v zanata; then
    zanata pull || exit 1
else
    echo -e "'zanata' command not found." \
            "You can install it with:\n" \
            "dnf install /usr/bin/zanata"
    exit 1
fi

pushd po || exit 1

ERR=false
for pof in *.po
do
    msgfmt --check-format "$pof" || {
        ERR=true
    }
done

if $ERR; then
    exit 1
fi

for pof in *.po;
do
    echo "${pof%.*}"
    if ! git ls-files "$pof" --error-unmatch >/dev/null 2>&1; then
        git add "$pof" >/dev/null 2>&1 || {
            echo "Failed to 'git add $pof'"
            exit 1
        }
    fi
done | sort > LINGUAS

popd || exit 1

NEW_LINGUAS=$(git status -s --porcelain | grep "^A" | awk -F[/.] '{print $2}' | tr "\n" " " | sed 's/\(.*\) /\1/')
if [ -n "$NEW_LINGUAS" ]; then
    git add po/LINGUAS
    git commit -s -m "Add new translation languages - $NEW_LINGUAS"
fi

git commit -a -s -m "Translation updates"
git log --oneline -2
