#   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
SERVER_IP=$1
SERVER_PORT=$2
MFPF_ADMIN_USERNAME=$3
MFPF_ADMIN_PASSWORD=$4
if [ -z $5 ] 
then
	MFPF_ADMIN_ROOT="worklightadmin"
else
	MFPF_ADMIN_ROOT=$5
fi

CERT_PATH=$6
WORKING_DIR=$7

echo "Arguments : "
echo "----------- "
echo "SERVER_IP : " $SERVER_IP
echo "SERVER_HTTPS_PORT : " $SERVER_PORT
echo "MFPF_ADMIN_USERNAME : " $MFPF_ADMIN_USERNAME
echo "MFPF_ADMIN_PASSWORD : XXXXXX" 
echo "SERVER_ADMIN_ROOT : " $MFPF_ADMIN_ROOT
echo "CERT_PATH : " $CERT_PATH
echo "WORKING_DIR : " $WORKING_DIR
echo 

if [[ "$WORKING_DIR" == */ ]]; 
	then 
		temp=$WORKING_DIR
  		WORKING_DIR="${temp%?}"
  	else
  		WORKING_DIR=$WORKING_DIR
fi
  
echo "working dir is $WORKING_DIR"
echo $JAVA_HOME
serverURL="https://$SERVER_IP:$SERVER_PORT"
echo "serverURL is $serverURL"
if [ ! -z $WORKING_DIR ] 
then
	#projectsNumber=$(find . -mindepth 1 -maxdepth 1 -type d | wc -l)
	cd $WORKING_DIR/mfpf-server/usr/projects
	projects=$(find . -mindepth 1 -maxdepth 1 -type d)
	echo "projects are $projects"
	for DIR in $projects
	do
		cd $WORKING_DIR/mfpf-server/usr/projects
		cd $DIR
		runtimeName=${PWD##*/} 
		echo "runtimeName is $runtimeName"
		cd bin
		for file in *-all.wlapp
		do
 			# do something on "$file"
 			echo "cert path is $CERT_PATH"
 			if [ -z $CERT_PATH ]
 			then
 				
 				curl -k -s -u  $MFPF_ADMIN_USERNAME:$MFPF_ADMIN_PASSWORD -i -H "Accept: application/json" -F "data=@$file" -X POST $serverURL/$MFPF_ADMIN_ROOT/management-apis/1.0/runtimes/$runtimeName/applications?async=false 
 			else
 				curl --capath $CERT_PATH -s -u  $MFPF_ADMIN_USERNAME:$MFPF_ADMIN_PASSWORD -i -H "Accept: application/json" -F "data=@$file" -X POST $serverURL/$MFPF_ADMIN_ROOT/management-apis/1.0/runtimes/$runtimeName/applications?async=false
 			fi   
		done
		for file in *.adapter
		do
 			# do something on "$file"
 			if [ -z $CERT_PATH ]
 			then
 				curl -k -s -u  $MFPF_ADMIN_USERNAME:$MFPF_ADMIN_PASSWORD -i -H "Accept: application/json" -F "data=@$file" -X POST $serverURL/$MFPF_ADMIN_ROOT/management-apis/1.0/runtimes/$runtimeName/adapters?async=false
 			else
 				curl --capath $CERT_PATH -s -u  $MFPF_ADMIN_USERNAME:$MFPF_ADMIN_PASSWORD -i -H "Accept: application/json" -F "data=@$file" -X POST $serverURL/$MFPF_ADMIN_ROOT/management-apis/1.0/runtimes/$runtimeName/adapters?async=false
 			fi
		done
	done
else
	echo "No of projects to be deployed are empty"
		
fi
