#!/bin/bash

cd "$(dirname $0)"

# Get OneSky API Keys
#
hasKeys=1
publicApiKey=""
privateApiKey=""
if test -f "OneSky_PublicAPIKey";
then
	publicApiKey=$(cat OneSky_PublicAPIKey)
else
	hasKeys=0
	echo 'You need to create file OneSky_PublicAPIKey before running this. (OneSky > Site Settings > API Keys & Usage)'
fi

if test -f "OneSky_PrivateAPIKey";
then
	privateApiKey=$(cat OneSky_PrivateAPIKey)
else
	hasKeys=0
	echo 'You need to create file OneSky_PrivateAPIKey before running this. (OneSky > Site Settings > API Keys & Usage)'
fi

if (( $hasKeys == 0 ))
then
	exit 100
fi

# Define source path
#
sourcePath="$(dirname $0)/Temp"
mkdir -p $sourcePath

# Compile tool
#
javac "$(dirname $0)/tools/SortAndConvert.java"
javaCommand="java -cp $(dirname $0)/tools SortAndConvert"

destPath="$(dirname $0)"
file="Localizable.strings"

# Download and update translations
#
locales=("en" "de" "es-419" "fr" "it" "ja" "ko" "pt-BR" "ru" "zh-Hans" "zh-Hant")
summaryStrings=()
for locale in ${locales[@]};
do
	echo "----------------- Starting Locale '$locale' -----------------"
	curl -X GET https://platform.api.onesky.io/1/projects/26548/translations \
		-H 'Content-Type: application/json' \
		-d "{\"api_key\":\"${publicApiKey}\",\"timestamp\":\"$(date +%s)\",\"dev_hash\":\"$(md5 -q -s "$(date +%s)${privateApiKey}")\", \"locale\":\"$locale\", \"source_file_name\":\"Localizable.strings\"}" \
		> "$sourcePath/$locale.strings"
	outLocale=""
	case $locale in
		es-419)
			outLocale="es"
		;;
		pt-BR)
			outLocale="pt"
		;;
		*)
			outLocale=$locale
		;;
	esac
	summaryStrings[${#summaryStrings[@]}]="$(${javaCommand} "${sourcePath}/${locale}.strings"      "${destPath}/${outLocale}.lproj/${file}")"
	echo "${summaryStrings[${#summaryStrings[@]}-1]}"
	echo
done

echo
echo "-------------------------- Summary --------------------------"
for ((i = 0; i < ${#summaryStrings[@]}; i++))
do
	echo "${summaryStrings[i]}"
done

rm -r $sourcePath
