#   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
source $PLUGIN_HOME/MFPContainerFiles/initDocker.sh

#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_GROUP_NAME=${13}
SERVER_CONTAINER_GROUP_HOST=${14}
SERVER_CONTAINER_GROUP_DOMAIN=${15}
SERVER_CONTAINER_GROUP_MIN=${16}
SERVER_CONTAINER_GROUP_MAX=${17}
SERVER_CONTAINER_GROUP_DESIRED=${18}
SERVER_MEM=${19}
TRACE_SPEC=${20}
MAX_LOG_FILES=${21}
MAX_LOG_FILE_SIZE=${22}
ENABLE_VOLUME=${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_GROUP_NAME : " $SERVER_CONTAINER_GROUP_NAME
echo "SERVER_CONTAINER_GROUP_HOST : " $SERVER_CONTAINER_GROUP_HOST
echo "SERVER_CONTAINER_GROUP_DOMAIN : " $SERVER_CONTAINER_GROUP_DOMAIN
echo "SERVER_CONTAINER_GROUP_MIN : " $SERVER_CONTAINER_GROUP_MIN
echo "SERVER_CONTAINER_GROUP_MAX : " $SERVER_CONTAINER_GROUP_MAX
echo "SERVER_CONTAINER_GROUP_DESIRED : " $SERVER_CONTAINER_GROUP_DESIRED
echo "SERVER_MEM : " $SERVER_MEM
echo "TRACE_SPEC : " $TRACE_SPEC
echo "MAX_LOG_FILES : " $MAX_LOG_FILES
echo "MAX_LOG_FILE_SIZE : " $MAX_LOG_FILE_SIZE
echo "ENABLE_VOLUME : " $ENABLE_VOLUME
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/initenv.sh
source $PLUGIN_HOME/MFPContainerFiles/ice_common_commands.sh
source $WORKING_DIR/mfpf-server/usr/env/server.env
source $PLUGIN_HOME/MFPContainerFiles/mfpf-server/scripts/common.sh

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

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 paramWORKING_DIR check for empty

#=====================================End of db preparation ======================================

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

trap clean_up 0 1 2 3 15

copyProjects

echo "build projects"
buildProjects
migrateProjects

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


#=====================================End of server preparation ======================================

#=====================================Start of container group creation ======================================

getCtrGrpState "$3" $access_token $spaceGUID ${15}
echo "----------------------------------- state in initial 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' "$3" $access_token $spaceGUID ${15})
	echo "stopResult in script is $stopResult"
	if  [[ $stopResult == Error* ]]  ; then
		echo "Error Occured in container group stop  - Quitting!"
		exit 1
	fi
	echo "----------------------------------- Container group stopped"
	
	checkContainerGrpStatusWithWait "$3" $access_token $spaceGUID ${15} "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_GROUP_NAME
#arg 6 - memory
#arg 7 - SERVER_CONTAINER_GROUP_MIN
#arg 8 - SERVER_CONTAINER_GROUP_MAX
#arg 9 - SERVER_CONTAINER_GROUP_DESIRED
#arg 10 - volumes
#arg 11 - ports
#arg 12 - app Name
#arg 13 - environment properties
#arg 14 - command - which is null for mfp
#arg 15 - SERVER_CONTAINER_GROUP_HOST
#arg 16 - SERVER_CONTAINER_GROUP_DOMAIN

args[0]="createContainerGrp"
args[1]=$BLUEMIX_CCS_HOST
args[2]=$access_token
args[3]=$spaceGUID
args[4]=$SERVER_IMAGE_TAG
args[5]=$SERVER_CONTAINER_GROUP_NAME
args[6]=$SERVER_MEM
args[7]=$SERVER_CONTAINER_GROUP_MIN
args[8]=$SERVER_CONTAINER_GROUP_MAX
args[9]=$SERVER_CONTAINER_GROUP_DESIRED


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

TRACE_SPEC=${TRACE_SPEC//"="/"~"}

environmentProps="MFPF_CLUSTER_MODE=Farm&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

args[10]="$volumes"

ports="$MFPF_SERVER_HTTPPORT"
args[11]="$ports"

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

echo "environmentprops is $environmentProps"
args[13]="$environmentProps"
args[14]="null"
args[15]=$SERVER_CONTAINER_GROUP_HOST
args[16]="$SERVER_CONTAINER_GROUP_DOMAIN"

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


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

checkContainerGrpStatusWithWait "$BLUEMIX_CCS_HOST" $access_token $spaceGUID $SERVER_CONTAINER_GROUP_NAME "createAction"

echo "End of the script"

#=====================================End of container group creation ======================================