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


MFPF_SERVER_IP=$1
MFPF_SERVER_HTTPS_PORT=$2
MFPF_ADMIN_USERNAME=$3
MFPF_ADMIN_PASSWORD=$4
if [ -z $5 ] 
then
	MFPF_ADMIN_ROOT="worklightadmin"
else
	MFPF_ADMIN_ROOT=$5
fi

MFPF_RUNTIME_NAME=$6
MFPF_ADAPTERS_NAME=$7
MFPF_APPS_NAME=$8
CERT_PATH=$9

echo "Arguments : "
echo "----------- "
echo "SERVER IP: " $MFPF_SERVER_IP
echo "SERVER Port (HTTPS) : " $MFPF_SERVER_HTTPS_PORT
echo "SERVER ADMIN USER NAME : " $MFPF_ADMIN_USERNAME
echo "SERVER ADMIN PASSWORD : " $MFPF_ADMIN_PASSWORD
echo "SERVER_ADMIN_ROOT : " $MFPF_ADMIN_ROOT
echo "SERVER RUNTIME NAME : " $MFPF_RUNTIME_NAME
echo "SERVER ADAPTERS : " $MFPF_ADAPTERS_NAME
echo "SERVER APPS : " $MFPF_APPS_NAME
echo "CERT PATH : " $CERT_PATH
echo 
 
serverURL="https://$MFPF_SERVER_IP:$MFPF_SERVER_HTTPS_PORT"
echo "serverURL is $serverURL"
set -e 
if [ ! -z $MFPF_RUNTIME_NAME ] 
then
	
	OIFS=$IFS;
	IFS=",";
	
	adapterArray=($MFPF_ADAPTERS_NAME);
	for ((i=0; i<${#adapterArray[@]}; ++i)); do 
		echo "will have to undeploy the adapter named - ${adapterArray[$i]}"
		if [ -z $CERT_PATH ]
		then
			curl -k -s -u  $MFPF_ADMIN_USERNAME:$MFPF_ADMIN_PASSWORD -i -H "Accept: application/json" -X DELETE $serverURL/$MFPF_ADMIN_ROOT/management-apis/1.0/runtimes/$MFPF_RUNTIME_NAME/adapters/${adapterArray[$i]}?async=false&locale=en
		else
			curl --capath $CERT_PATH -s -u  $MFPF_ADMIN_USERNAME:$MFPF_ADMIN_PASSWORD -i -H "Accept: application/json" -X DELETE $serverURL/$MFPF_ADMIN_ROOT/management-apis/1.0/runtimes/$MFPF_RUNTIME_NAME/adapters/${adapterArray[$i]}?async=false&locale=en
		fi
		
	done
	
	echo "Undeployed the adapters - Will continue with the apps"
	
	appArray=($MFPF_APPS_NAME);
	for ((i=0; i<${#appArray[@]}; ++i)); do 
	  	echo "will have to undeploy the app named - ${appArray[$i]}"
	  	if [ -z $CERT_PATH ]
		then
			curl -k -s -u  $MFPF_ADMIN_USERNAME:$MFPF_ADMIN_PASSWORD -i -H "Accept: application/json" -X DELETE $serverURL/$MFPF_ADMIN_ROOT/management-apis/1.0/runtimes/$MFPF_RUNTIME_NAME/applications/${appArray[$i]}?async=false&locale=en
		else
			curl --capath $CERT_PATH -s -u  $MFPF_ADMIN_USERNAME:$MFPF_ADMIN_PASSWORD -i -H "Accept: application/json" -X DELETE $serverURL/$MFPF_ADMIN_ROOT/management-apis/1.0/runtimes/$MFPF_RUNTIME_NAME/applications/${appArray[$i]}?async=false&locale=en
		fi
	done
	
	IFS=$OIFS;
	
else
	echo "No of app or adapters to be undeployed are empty"
fi 
set +e
