#!/usr/bin/env bash

# To test parse cloud build, we build and then deploy a basic parse application
# The parse function called will be the one in test/parse/cloud/main.js

set -e # exit when error

[ -z $TRAVIS_BUILD_NUMBER ] && CI='false' || CI='true'

if [ $CI == 'true' ]; then
  set -x # debug messages
fi

echo "Parse-cloud test"

# build (including the parse build)
# change the version number to 1.0.$TRAVIS_BUILD_NUMBER so that we can test that
# the build was really deployed to parse (see test/parse/cloud/main.js and test/parse/index.js)
cp src/version.js src/version.js.bak
printf "'use strict';\n\nmodule.exports = '1.0.$TRAVIS_BUILD_NUMBER';" > src/version.js
npm run build

cp dist/algoliasearch.parse.js test/parse/cloud

cd test/parse

# install parse cli
curl -s https://www.parse.com/downloads/cloud_code/installer.sh > installer.sh
# parse shell script tries to install in /usr/local/bin, not available in container based
# infra on travis
sed -i 's/\/usr\/local\/bin\/parse/parse/g' installer.sh
/bin/bash installer.sh

# decrypt parse cloud config file
# http://docs.travis-ci.com/user/encrypting-files/
openssl aes-256-cbc -K $encrypted_54792a874ee7_key -iv $encrypted_54792a874ee7_iv -in config/global.json.enc -out config/global.json -d

# deploy the new build
./parse deploy

# test
node index.js

# cleanup the mess
# get back to root of git project
cd ../../
cp src/version.js.bak src/version.js
git checkout dist/
git checkout test/
git clean test/ -f
