#   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 -e
#set -x
#main

BLUEMIX_API_URL=$1
BLUEMIX_CCS_HOST=$2
BLUEMIX_USER=$3
BLUEMIX_PASSWORD=$4
BLUEMIX_ORG=$5
BLUEMIX_SPACE=$6
SERVER_CONTAINER_GROUP_NAME=$7

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 "SERVER_CONTAINER_GROUP_NAME : " $SERVER_CONTAINER_GROUP_NAME
echo

source $PLUGIN_HOME/MFPContainerFiles/initenv.sh
source $PLUGIN_HOME/MFPContainerFiles/ice_common_commands.sh


getCtrGrpState "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_GROUP_NAME
echo "Current state of the container group to be removed is -  $state"

if [[ "$state" == Error* ]]; then
	echo "Could not get the state of the container group.  Quitting!"
	exit 1;
fi
if [[ "$state" == 404* ]]; then
	echo "Container Group does not exist already. "
else
	echo "Container Group exist.  Check the status"
	stopResult=$(java com.ibm.mobilefirst.container.ManageMFPServerContainer 'stopDeleteCtrGrp' "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_GROUP_NAME)
	echo "stopResult response is $stopResult"
	if  [[ $stopResult == Error* ]]  ; then
		echo "Error Occured in container group stop  - Quitting!"
		exit 1
	fi
	echo "Container group stop issued.  Waiting for the container group to be stopped completely."
	
	checkContainerGrpStatusWithWait "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_GROUP_NAME "removeAction"
fi
echo "End of the script"