#!/usr/bin/env bash

# Safe bash settings
# -e            Exit on command fail
# -u            Exit on unset variable
# -o pipefail   Exit if piped command has error code
set -eu -o pipefail

cd "$(dirname "$0")/.."

if [ ! -f .lokalise_token ] ; then
    echo "Lokalise API token is required to download the latest set of" \
        "translations. Please create an account by using the following link:" \
        "https://lokalise.co/signup/3420425759f6d6d241f598.13594006/all/" \
        "Place your token in a new file \".lokalise_token\" in the repo" \
        "root directory."
    exit 1
fi

API_TOKEN="$(<.lokalise_token)"
PROJECT_ID="3420425759f6d6d241f598.13594006"
LOCAL_DIR="$(pwd)/translations"
DOWNLOAD_FILE="${LOCAL_DIR}/Home_Assistant_-_Polymer_frontend-locale.zip"
FILE_FORMAT=json

rm -f ${LOCAL_DIR}/*.json
mkdir -p ${LOCAL_DIR}

docker run \
     -v ${LOCAL_DIR}:/opt/dest \
     lokalise/lokalise-cli lokalise \
     --token ${API_TOKEN} \
     export ${PROJECT_ID} \
     --export_empty skip \
     --type json \
     --dest /opt/dest

# Extract and delete downloaded zip bundle
unzip -j "${DOWNLOAD_FILE}" locale/* -d "${LOCAL_DIR}"
rm -f "${DOWNLOAD_FILE}"
