#   Licensed Materials - Property of IBM 
#   5725-I43 (C) Copyright IBM Corp. 2011, 2015. All Rights Reserved.
#   US Government Users Restricted Rights - Use, duplication or
#   disclosure restricted by GSA ADP Schedule Contract with IBM Corp.  

#!/usr/bin/bash

clean_up() {
	# Perform clean up before exiting
    if [ -d $WORKING_DIR/mfpf-analytics/dependencies ]
    then
        mv $WORKING_DIR/mfpf-analytics/dependencies $WORKING_DIR/dependencies
    fi
    if [ -d $WORKING_DIR/mfpf-analytics/mfpf-libs ]
    then
        mv $WORKING_DIR/mfpf-analytics/mfpf-libs $WORKING_DIR/mfpf-libs
    fi
}


#main

#set -e

BLUEMIX_API_URL=$1
BLUEMIX_CCS_HOST=$2
BLUEMIX_USER=$3
BLUEMIX_PASSWORD=$4
BLUEMIX_ORG=$5
BLUEMIX_SPACE=$6
ANALYTICS_IMAGE_TAG=$7
MFPF_WORKING_DIR=$8

echo "Arguments : "
echo "----------- "
echo 
echo "BLUEMIX_API_URL : " $BLUEMIX_API_URL
echo "BLUEMIX_CCS_HOST : " $BLUEMIX_CCS_HOST
echo "BLUEMIX_USER : " $BLUEMIX_USER
echo "BLUEMIX_PASSWORD : " XXXXXXXX
echo "BLUEMIX_ORG : " $BLUEMIX_ORG
echo "BLUEMIX_SPACE : " $BLUEMIX_SPACE
echo "ANALYTICS_IMAGE_TAG : " $ANALYTICS_IMAGE_TAG
echo "WORKING_DIR : " $MFPF_WORKING_DIR
echo 

if [[ "$MFPF_WORKING_DIR" == */ ]]; 
	then 
		temp=$MFPF_WORKING_DIR
  		WORKING_DIR="${temp%?}"
  	else
  		WORKING_DIR=$MFPF_WORKING_DIR
fi
  
echo "working dir is $WORKING_DIR"
source $PLUGIN_HOME/MFPContainerFiles/initenv.sh
source $PLUGIN_HOME/MFPContainerFiles/mfpf-analytics/scripts/common.sh

trap clean_up 0 1 2 3 15


mv $WORKING_DIR/dependencies $WORKING_DIR/mfpf-analytics/dependencies
mv $WORKING_DIR/mfpf-libs $WORKING_DIR/mfpf-analytics/mfpf-libs
cp -rf $WORKING_DIR/licenses $WORKING_DIR/mfpf-analytics/licenses

#addSshToDockerfile $WORKING_DIR/mfpf-analytics/usr $WORKING_DIR/mfpf-analytics/Dockerfile


if [ -f $WORKING_DIR/mfpf-analytics.tar.gz ]
then
	echo "Zip file already exists - deleting it and will recreate"
	rm -rf $WORKING_DIR/mfpf-analytics.tar.gz
fi

if [ ! -f $WORKING_DIR/mfpf-analytics.tar.gz ]
then
	echo "Delete was successful"
fi

cd $WORKING_DIR/mfpf-analytics
tar -zcvf  $WORKING_DIR/mfpf-analytics.tar.gz .

mv $WORKING_DIR/mfpf-analytics/dependencies $WORKING_DIR/dependencies
mv $WORKING_DIR/mfpf-analytics/mfpf-libs $WORKING_DIR/mfpf-libs
rm -rf $WORKING_DIR/mfpf-analytics/licenses

COUNTER=40
while [ $COUNTER -gt 0 ]
do
 if [ -f $WORKING_DIR/mfpf-analytics.tar.gz ]
    then
    		echo "File exist"
            break
    fi
    
    # Allow to sleep for 40s. 
    sleep 5s

    COUNTER=$(expr $COUNTER - 1)
done

if [  -f $WORKING_DIR/mfpf-analytics.tar.gz ]; then
	mfp_analytics_push=$(java com.ibm.mobilefirst.container.ManageMFPServerContainer "buildImage" "$BLUEMIX_CCS_HOST/build" $access_token $spaceGUID $ANALYTICS_IMAGE_TAG $WORKING_DIR/mfpf-analytics.tar.gz)
	echo "Result of the analytics image push is $mfp_analytics_push"
	if  [[ $mfp_analytics_push == Error* ]]  ; then
		echo "Error Occured in build of image - Quitting!"
		exit 1
	fi
	
fi
