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

#set -x


#main

BLUEMIX_API_URL=$1
BLUEMIX_CCS_HOST=$2
BLUEMIX_USER=$3
BLUEMIX_PASSWORD=$4
BLUEMIX_ORG=$5
BLUEMIX_SPACE=$6
SERVER_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 : " $BLUEMIX_PASSWORD
echo "BLUEMIX_ORG : " $BLUEMIX_ORG
echo "BLUEMIX_SPACE : " $BLUEMIX_SPACE
echo "SERVER_IMAGE_TAG : " $SERVER_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-server/scripts/common.sh
trap clean_up 0 1 2 3 15

chmod -R a+x $WORKING_DIR/mfpf-libs

#copyProjects
buildProjects
migrateProjects

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

if [ -f $WORKING_DIR/mfpf-server.tar.gz ]
then
	echo "Zip file already exists - Deleting it"
	rm -rf $WORKING_DIR/mfpf-server.tar.gz
fi

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

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

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


COUNTER=40
while [ $COUNTER -gt 0 ]
do
 if [ -f $WORKING_DIR/mfpf-server.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-server.tar.gz ]; then
	mfp_server_push=$(java com.ibm.mobilefirst.container.ManageMFPServerContainer "buildImage" "$BLUEMIX_CCS_HOST/build" $access_token $spaceGUID $SERVER_IMAGE_TAG $WORKING_DIR/mfpf-server.tar.gz)
	echo "Build image for the server result is $mfp_server_push"
	if  [[ $mfp_server_push == Error* ]]  ; then
		echo "Error Occured in build of image - Quitting!"
		exit 1
	fi
	
fi

