#!/bin/bash

#
# Sync our translations.
#
# The sync process has 3 different steps:
#
# 1. Generates the message.pot file: it gets all the php files, parses them
#    and find all the strings that are tagged.
#
# 2. Send the pot file to POEditor.
#
# 3. Retrieve from POEditor all the po files for each language we're supporting,
#    allowing us to keep our codebase in sync.
#
# Author:
#    Michael Ortali <mortali@theorchard.com>
#

printf "Start sync process"
printf "Cloning orchard repo"
CURRENT=`pwd`
printf "Start extraction from: ${CURRENT}"

git clone git@github.com:theorchard/orchard.git orchard
cd orchard

find . -name "*.php" -or -name "*.phtml" -and -not -path "./vendor/*" \
    | xargs xgettext --language=php --from-code=UTF-8 -o ../messages.pot --keyword=plural:1,2 --keyword=translate

printf "Cleaning up workspace"
cd ../
rm -rf orchard/

printf "\nSending: message.pot"
curl --silent \
    -F "api_token=${API_KEY}" \
    -F "action=upload" \
    -F "id=${PROJECT_ID}" \
    -F "updating=terms" \
    -F "sync_terms=0" \
    -F "tags=[{\"new\": \"`date`\"}]" \
    -F "file=@messages.pot" \
    https://poeditor.com/api/ > /dev/null

git commit -a -m '[i18n] Update the message.pot'


printf "\n\nRetrieve translated files\n"
languages='en-US fr ru de es it ja pt tr zh-CN zh-TW ko'
for lang in $languages
do
    directory="${lang}/LC_MESSAGES/"
    mkdir -p $directory
    cd $directory

    API_RESPONSE=$(curl -silent \
        -F "api_token=${API_KEY}" \
        -F "action=export" \
        -F "id=${PROJECT_ID}" \
        -F "language=$lang" \
        -F "type=po" \
        https://poeditor.com/api/)

    FILE_URL=$(echo \
        $API_RESPONSE \
        | egrep -o 'http(.+)"' \
        | sed 's/\\//g' \
        | sed 's/"$//g')

    curl -silent $FILE_URL -o temp.po
    cat temp.po | sed '1,/^\r$/d' > messages.po
    printf "${lang} has been exported from poeditor (${FILE_URL})"
    msgfmt -cv -o messages.mo messages.po
    rm temp.po

    cd $CURRENT
done

git add .
git commit -a -m '[i18n] Export the languages from POEditor'

# Makes the Jenkins task succeed – otherwise if nothing needs to be merged,
# it returns exit 1, which shows the build as FAIL.
exit 0
