#!/bin/bash

# Script to deploy the built jars to Google Cloud Storage
# Ravi - 2017-06-11
set -ev

# Set the required variables
LOCAL_SRC_DIR=deploy
GCS_BUCKET="gs://ice-console/ice-console2"

#Uploading to a different bucket for Jenkins pilot run
#Remove this 'if' block when Jenkins is ready for production
# if [ "$BUILD_AGENT" = "Jenkins" ]; then
#     echo "Build agent is Jenkins!"
#     GCS_BUCKET="gs://jenkins-front-end-builds"
# fi

KEYFILE="tools/deploy/gcs/key.json"
ENC_KEYFILE="tools/deploy/gcs/key.json.enc"


# function setup_gcs () {
#    # Set the GCE project to the 'vpsincprod'
#     /home/travis/build/vpsinc/ice-frontend-react-mobx/google-cloud-sdk/bin/gcloud config set project vpsincprod

#    # Unencrypt the key file retrieved from repo on GitHubxs (Is this better to do directly in .travis.yml?) 
#    #Have to make sure that the directories are right
#     # openssl aes-256-cbc -K $encrypted_b5da0929b907_key -iv $encrypted_b5da0929b907_iv -in key.json.enc -out key.json -d
#     # openssl aes-256-cbc -K $encrypted_b5da0929b907_key -iv $encrypted_b5da0929b907_iv -in ${ENC_KEYFILE} -out ${KEYFILE} -d
#     openssl aes-256-cbc -K $encrypted_fc0ada65fa46_key -iv $encrypted_fc0ada65fa46_iv -in ${ENC_KEYFILE} -out ${KEYFILE} -d
#     if [[ ! -f ${KEYFILE} ]]; then
# 	echo "Unencrypted file ( ${KEYFILE} ) not found" 
# 	exit 1
#     fi

#    # Authenticate to GCS using the key file
#     /home/travis/build/vpsinc/ice-frontend-react-mobx/google-cloud-sdk/bin/gcloud auth activate-service-account --key-file=${KEYFILE}

# #    gcloud auth list

#    # Delete the key file
#     rm ${KEYFILE}

# }

echo "Setting up GCS keys and environment"

# Sync the local and remote directories (recursively) - this is preferred to 'cp' because 'cp' can lead to unexpected
# semantics based on if the remote directory previously exists or is new. 
# REMEMBER not to use the -d option to rsync - this will cause GCS_BUCKET to be *exactly* sync'd with LOCAL_SRC_DIR, 
# meaning that files in GCS_BUCKET that are not in LOCAL_SRC_DIR will get deleted. We want to keep the old files 
# in GCS_BUCKET so using -r (without -d) is the way to get only new/changed files into GCS_BUCKET. 
# NOTE: order of directory matters - the first is the reference

# if [ "$BUILD_AGENT" = "Jenkins" ]; then
gcloud config set project vpsincprod
echo "Transferring jars"
gsutil cp ${DEPLOY_TAR_WITH_TAG} ${GCS_BUCKET}/${DEPLOY_TAR_WITH_TAG}
# else
#     setup_gcs
#     echo "Transferring jars"
#     /home/travis/build/vpsinc/ice-frontend-react-mobx/google-cloud-sdk/bin/gsutil cp bundle.tgz ${GCS_BUCKET}/react/ice-console2_${TRAVIS_TAG}.tgz
# fi

echo "done"

#/home/travis/build/vpsinc/ice-frontend-react-mobx/google-cloud-sdk/bin/gsutil -m rsync -r ${LOCAL_SRC_DIR} ${GCS_BUCKET}
#Using cp as rsync needs a dir by itself
#/home/travis/build/vpsinc/ice-frontend-react-mobx/google-cloud-sdk/bin/gsutil cp bundle.tgz gs://ice-frontend/react/ice-frontend_${TRAVIS_TAG}.tgz
