#!/bin/bash
#
# ACStart.sh - Starts the Agent Controller server process.
# 

#
# If TPTP_AC_HOME is not set then set it to the parent directory of the directory containing this script
#
if [ -z "$TPTP_AC_HOME" ]; then
	TPTP_AC_HOME=`dirname "$0"`/..
	export TPTP_AC_HOME
fi
PATH="$TPTP_AC_HOME/bin":$PATH
export PATH

#
# Make sure TPTP_AC_HOME is valid
#
if [ -e "$TPTP_AC_HOME/config/serviceconfig.xml" ] ; then
	echo "Starting Agent Controller."
else
	echo "TPTP_AC_HOME not set properly. Could not locate config/serviceconfig.xml at that location."
	echo "TPTP_AC_HOME=" $TPTP_AC_HOME
	exit 67
fi

#
# Parse the configuration file for the location of the jvm library
#
JVM_LIB=`grep '<Jvm' "$TPTP_AC_HOME/config/serviceconfig.xml" | sed 's/<Jvm location="\(.*\)"\/>/\1/'`
export JVM_LIB

#
# Set the library path(s) based on the location of the jvm library (".." is the parent directory which
# also holds other dependent *.so)
#
DYLD_LIBRARY_PATH="$TPTP_AC_HOME/lib":`echo $JVM_LIB | sed 's/\(.*\)\/libjvm\.so/\1/'`:`echo $JVM_LIB | sed 's/\(.*\)\/libjvm\.so/\1/' | sed 's/\(.*\)\/.*/\1/'`:/usr/lib:$DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH

#
# Bug 175696, 201989
# Make sure TEMP dir is set
#
if [[ -n $TEMP ]]; then
	if [[ -d $TEMP ]]; then
		echo
	else
		export TEMP=/tmp
	fi
else
	export TEMP=/tmp
fi

#
# Start the ACServer
#
RUNNING=`ps -aux | grep "ACServer" | wc -l`
if [ $RUNNING -eq 1 ];then
	ps -aux | grep "ACServer" | awk '{
  	print "The server is already running on pid " $1
	}'      
	exit 66
else
    ACServer "$@" &
fi

#
# Wait for the process to come up in the system process list
#
sleep 2

#
# Check if ACServer is running by querying the system process list
#
RUNNING=`ps -ae | grep "ACServer" | wc -l`
if [ $RUNNING -ne 0 ];then
    echo "ACServer started successfully."
    exit 0
else
    echo "ACServer failed to start."
    exit 1
fi
