#!/bin/sh

### BEGIN INIT INFO
# Provides: csm_agent
# Required-Start:
# Required-Stop:
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description: Start the CSM agent daemon
### END INIT INFO

# All paths are relative to here
#
INSTALL_DIR=/opt/NetApp/csm_agent
cd ${INSTALL_DIR}

if [ -z "${JAVA_HOME}" ] ; then
    echo "JAVA_HOME must be defined"
    exit 1;
fi

WEB_INF_PATH=${INSTALL_DIR}/webapp/WEB-INF
LIB_PATH=$WEB_INF_PATH/lib

CP=$WEB_INF_PATH:$WEB_INF_PATH/classes

# Define just the classpath required to boot jetty
files="$LIB_PATH/jetty-6.1.3.jar"
files="$files $LIB_PATH/jetty-util-6.1.3.jar"
files="$files $LIB_PATH/log4j-1.2.12.jar"
files="$files $LIB_PATH/slf4j-api-1.3.1.jar"
files="$files $LIB_PATH/slf4j-log4j12-1.3.1.jar"
files="$files $LIB_PATH/netapp-common-1.0-SNAPSHOT.jar"
files="$files $LIB_PATH/commons-cli-2.20061128.jar"
files="$files $LIB_PATH/spring-2.0.4.jar"
files="$files $LIB_PATH/commons-logging-1.1.jar"
files="$files $LIB_PATH/servlet-api-2.4.jar"

SAPLIB=`dbmcli dbm_getpath IndepProgPath | grep "^/"`
if [ $? -eq 0 ] ; then
    SAPLIB="${SAPLIB}/runtime/jar/sapdbc.jar"
    echo "Using SAP JDBC driver from ${SAPLIB}"
    files="$files ${SAPLIB}"
else
    echo "No SAP JDBC driver found; MaxDB interactions will be disabled on this agent."
fi

for file in $files
do
  CP=$CP:$file
done

CP=${INSTALL_DIR}/etc:$CP

# If shell is killed the java process will keep running as zombie and user will see no message.
# To kill java process, send it a TERM instead of this shell.
trap /bin/true TERM

umask 0000

LOG_DIR=$INSTALL_DIR/log
LOG=$LOG_DIR/agent_server_console.log
mkdir -p $LOG_DIR

if [ -n "$DEBUG_PORT" ] ; then
    JVM_ARGS="$JVM_ARGS -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=$DEBUG_PORT,timeout=20000"
fi

java $JVM_ARGS -cp $CP -Dcom.sun.management.jmxremote -Dcommon.dir=$INSTALL_DIR com.netapp.common.server.ServerMain $@ > $LOG 2>&1 &

pid="$!"
while ps -p $pid | grep $pid >/dev/null 2>&1
do
    sleep 1
    # grep for the log entry that indicates the server has started.
    if [ "$1" = "start" ] ; then
    	msg=`grep "SERVER-01102" $LOG`
    # grep for the log entry tthat indicates the server has stopped
   	elif [ "$1" = "stop" ] ; then 
   		msg=`grep "SERVER-01111" $LOG`
   	fi
   	
    if [ -n "$msg" ] ; then
        echo "$msg"
        exit 0
    fi
done
echo "${1}ing agent server failed."
cat $LOG
exit 1
