#   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
DB_TYPE=$7
DB_SRV_NAME=$8
DB_SRV_PLAN=$9
APP_NAME=${10}
ADMIN_SCHEMA_NAME=${11}
SERVER_IMAGE_TAG=${12}
SERVER_CONTAINER_NAME=${13}
SERVER_IP=${14}
SERVER_MEM=${15}
EXPOSE_HTTP=${16}
EXPOSE_HTTPS=${17}
SSH_ENABLE=${18}
ENABLE_VOLUME=${19}
TRACE_SPEC=${20}
MAX_LOG_FILES=${21}
MAX_LOG_FILE_SIZE=${22}
SSH_KEY=${23}
MFPF_PROPERTIES=${24}
WORKING_DIR=${25}



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 "DB_TYPE : " $DB_TYPE
echo "DB_SRV_NAME : " $DB_SRV_NAME
echo "DB_SRV_PLAN : " $DB_SRV_PLAN
echo "APP_NAME : " $APP_NAME
echo "ADMIN_SCHEMA_NAME : " $ADMIN_SCHEMA_NAME
echo "SERVER_IMAGE_TAG : " $SERVER_IMAGE_TAG
echo "SERVER_CONTAINER_NAME : " $SERVER_CONTAINER_NAME
echo "SERVER_IP : " $SERVER_IP
echo "SERVER_MEM : " $SERVER_MEM
echo "EXPOSE_HTTP : " $EXPOSE_HTTP
echo "EXPOSE_HTTPS : " $EXPOSE_HTTPS
echo "SSH_ENABLE : " $SSH_ENABLE
echo "ENABLE_VOLUME : " $ENABLE_VOLUME
echo "TRACE_SPEC : " $TRACE_SPEC
echo "MAX_LOG_FILES : " $MAX_LOG_FILES
echo "MAX_LOG_FILE_SIZE : " $MAX_LOG_FILE_SIZE
echo "SSH_KEY : " $SSH_KEY
echo "ENVIRONMENT PROPERTIES : " $MFPF_PROPERTIES
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"


source $PLUGIN_HOME/MFPContainerFiles/initDocker.sh
source $PLUGIN_HOME/MFPContainerFiles/initenv.sh
source $PLUGIN_HOME/MFPContainerFiles/mfpf-server/scripts/common.sh
source $PLUGIN_HOME/MFPContainerFiles/ice_common_commands.sh
source $WORKING_DIR/mfpf-server/usr/env/server.env


#=====================================Start of db preparation ======================================

set -e

mfp container login -a $BLUEMIX_API_URL -u $BLUEMIX_USER -p $BLUEMIX_PASSWORD -o $BLUEMIX_ORG -s $BLUEMIX_SPACE

if [ -z "$ADMIN_SCHEMA_NAME" ]
then
	ADMIN_SCHEMA_NAME=WLADMIN
fi

echo "admin shema name is $ADMIN_SCHEMA_NAME"

#create admin schema / runtime 
mfp container configdb -t $DB_TYPE -n $DB_SRV_NAME -p $DB_SRV_PLAN -a $APP_NAME -s $ADMIN_SCHEMA_NAME -f $WORKING_DIR/mfpf-server/usr/config


if [ ! -z $WORKING_DIR ] 
then
	echo "No of projects to be deployed are not empty"	
	
	#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
		mfp container configdb -t $DB_TYPE -n $DB_SRV_NAME -p $DB_SRV_PLAN -a $APP_NAME -s ${DIR##*/} -r ${DIR##*/} -f $WORKING_DIR/mfpf-server/usr/config
	done
	
else
	echo "No of projects to be deployed are empty"
		
fi ##end of the param WORKING_DIR check for empty

set +e
#=====================================End of db preparation ======================================

#=====================================Start of server preparation ======================================

trap clean_up 0 1 2 3 15

copyProjects

echo "build projects"
buildProjects
migrateProjects

set -e

echo "working directory beofre moving is $WORKING_DIR"
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 "File exist - so 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
 echo "Coutner is $COUNTER"
 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

cd $PLUGIN_HOME/MFPContainerFiles/mfpf-server/scripts
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
set +e
#=====================================End of server preparation ======================================


#=====================================Start of Container Creation ======================================

getCtrState "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_NAME
echo "Current state of the container to be removed is -  $state"

if [[ "$state" == "NotAvailable" ]]; then
	echo "Container does not exist already."
else
	echo "Container exist. Trying to delete it."
	ctrId=$(java com.ibm.mobilefirst.container.ManageMFPServerContainer 'getCtrIdWithName' "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_NAME)
	echo "container id is $ctrId"
	if  [[ $ctrId == Error* ]]  ; then
		echo "Error Occured in container id retrieval  - Quitting!"
		exit 1
	fi
	
	removalResponse=$(java com.ibm.mobilefirst.container.ManageMFPServerContainer 'removeContainer' "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $ctrId)
	echo "Removal response is $removalResponse"
	if  [[ $removalResponse == Error* ]]  ; then
			echo "Error Occured in removal of container - Quitting!"
			 exit 1
	elif [[ "$removalResponse" == "204" ]] ; then
		echo "Request for removal of container succeeded"
	fi
	echo "Removal issued.  Will wait for the container to be completely removed."
	checkContainerStatusWithWait "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_NAME "removeAction"
fi

echo "Creating a new container"

#arg 1 - bluemix url
#arg 2 - accesstoken
#arg 3 - space guid
#arg 4 - SERVER_IMAGE_TAG
#arg 5 - SERVER_CONTAINER_NAME
#arg 6 - memroy
#arg 7 - environment properties
#arg 8 - command - which is null for mfp
#arg 9 - ssh key name 
#arg 10 - ports
#arg 11 - host config - empty for mfp
#arg 12 - app Name
#arg 13 - volumes
#arg 14 - number of cpus
#arg 15 - cpu set
ports=null

args[0]="createContainer"
args[1]=$BLUEMIX_CCS_HOST
args[2]=$access_token
args[3]=$spaceGUID
args[4]=$SERVER_IMAGE_TAG
args[5]=$SERVER_CONTAINER_NAME
args[6]=$SERVER_MEM

if [ -z "$TRACE_SPEC" ]
then
TRACE_SPEC="*~info"
else
TRACE_SPEC="$TRACE_SPEC"
fi

if [ -z "$MAX_LOG_FILES" ]
then
MAX_LOG_FILES="5"
else
MAX_LOG_FILES="$MAX_LOG_FILES"
fi

if [ -z "$MAX_LOG_FILE_SIZE" ]
then
MAX_LOG_FILE_SIZE="20"
else
MAX_LOG_FILE_SIZE="$MAX_LOG_FILE_SIZE"
fi

environmentProps="TRACE_LEVEL=$TRACE_SPEC&MAX_LOG_FILES=$MAX_LOG_FILES&MAX_LOG_FILE_SIZE=$MAX_LOG_FILE_SIZE"

if [ ! -z "$MFPF_PROPERTIES" ]
then
	environmentProps="$environmentProps&mfpfproperties=$MFPF_PROPERTIES"
fi
if [ "$ENABLE_VOLUME" = "TRUE" ] || [ "$ENABLE_VOLUME" = "true" ]
then
	createVolumes "$BLUEMIX_CCS_HOST" $access_token $spaceGUID
	volumes="$SYSVOL_NAME:$SYSVOL_PATH&$LIBERTYVOL_NAME:$LIBERTYVOL_PATH"
	environmentProps="$environmentProps&LOG_LOCATIONS=$SYSVOL_PATH/syslog,$LIBERTYVOL_PATH/messages.log,$LIBERTYVOL_PATH/console.log,$LIBERTYVOL_PATH/trace.log"
else
	volumes="null"
fi
echo "volumes is $volumes"


echo "environmentprops is $environmentProps"
args[7]="$environmentProps"
args[8]="null"

if [ ! -z "$SSH_KEY" ] && ([ "$SSH_ENABLE" = "TRUE" ] || [ "$SSH_ENABLE" = "true" ])
then
	KeyName="$SSH_KEY"
else
	KeyName="null"
fi
args[9]="$KeyName"


if [ "$SSH_ENABLE" = "TRUE" ] || [ "$SSH_ENABLE" = "true" ]
then
   ports="22"
fi

if [ "$EXPOSE_HTTP" = "TRUE" ] || [ "$EXPOSE_HTTP" = "true" ]
then
	if [ -z "$ports" ]; then
	    ports="$MFPF_SERVER_HTTPPORT"
	else
		ports="$ports , $MFPF_SERVER_HTTPPORT"
	fi
fi

if [ "$EXPOSE_HTTPS" = "TRUE" ] || [ "$EXPOSE_HTTPS" = "true" ]
then
	if [ -z "$ports" ]; then
		ports="$MFPF_SERVER_HTTPSPORT"
	else
	    ports="$ports, $MFPF_SERVER_HTTPSPORT"
	fi
fi
echo "ports is $ports"
args[10]="$ports"
args[11]="null"


if [ ! -z "$APP_NAME" ] 
then 
	appName="$APP_NAME"
else
	appName="null"
fi
args[12]="$appName"


args[13]="$volumes"

args[14]=0
args[15]="null"


printf '%s\n' "${args[@]}"


createCtrResponse=$(java com.ibm.mobilefirst.container.ManageMFPServerContainer "createContainer" ${args[1]} ${args[2]} ${args[3]} ${args[4]} ${args[5]} ${args[6]} "$environmentProps" ${args[8]} "$KeyName" "$ports" ${args[11]} ${args[12]} "$volumes" ${args[14]} ${args[15]})
echo "Create container response for server is $createCtrResponse"
if  [[ $createCtrResponse == Error* ]]  ; then
	echo "Error Occured in creation of container - Quitting!"
	exit 1
fi
echo "Create Server Successful"

checkContainerStatusWithWait "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_NAME "ipAction"
ctrId=$(java com.ibm.mobilefirst.container.ManageMFPServerContainer 'getCtrIdWithName' "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_NAME)

ipAssignResponse=$(java com.ibm.mobilefirst.container.ManageMFPServerContainer "assignIP" "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $ctrId $SERVER_IP)
echo "Server ip assignment response is $ipAssignResponse"
if  [[ $ipAssignResponse == Error* ]]  ; then
	echo "Error Occured in ip assignment to container - Quitting!"
	exit 1
fi
echo "Container successfully created with an IP - $SERVER_IP"