#!/bin/sh
#
# hinemos_log_agent
# This shell script control Hinemos Log Agent.
#
# chkconfig: 2345 99 01
# description: Hinemos Log Agent

# Copyright (C) since 2006 NTT DATA Corporation
#
# This program is free software; you can redistribute it and/or
# Modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details

# Source function library.
. /etc/rc.d/init.d/functions

ID=`echo "$(basename $0)" | sed -e "s/^.*hinemos_log_agent\(.*\)$/\1/"`

# Source config
. /opt/hinemos_agent${ID}/lib/hinemos_agent.cfg

RETVAL=0
PROG="hinemos_log_agent${ID}"

start() {
	is_running
	if [ $? -eq 0 ]
	then
		# do nothing if running
		return 0
	fi
	
	# startup if not running
	echo -n "Starting ${PROG} : "
	daemon "${HINEMOS_AGENT_HOME}/bin/log_agent_start.sh > /dev/null"
	RETVAL=$?
	echo
	[ ${RETVAL} -eq 0 ] && touch ${HINEMOS_LOG_AGENT_LOCK_FILE}
	return ${RETVAL}
}

stop() {
	is_running
	if [ $? -eq 0 ]
	then
		# shutdown if running
		echo -n "Stopping ${PROG} : "
		killproc ${PROG}
		RETVAL=$?
		echo
		[ ${RETVAL} -eq 0 ] && rm -f ${HINEMOS_LOG_AGENT_LOCK_FILE} ${HINEMOS_LOG_AGENT_PID}
		return ${RETVAL}
	fi
	
	# do nothing if not running
	return 0
}

is_running() {
	if [ -f ${HINEMOS_LOG_AGENT_PID} ]
	then
		read PID < ${HINEMOS_LOG_AGENT_PID}
		if [ `ps --no-headers --pid ${PID} e | grep "${JAVA_HOME}/bin/java.*com.clustercontrol.logagent.Agent" | wc -l` -gt 0 ]
		then
			return 0
		fi
	fi
	
	return 1
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		is_running
		if [ $? -eq 0 ]
		then
			read PID < ${HINEMOS_LOG_AGENT_PID}
			echo "Hinemos Log Agent (PID ${PID}) is running..."
		else
			echo "Hinemos Log Agent is stopped"
			RETVAL=3
		fi
		;;
	restart)
		stop
		start
		;;
	*)
		echo "Usage: $0 {start|stop|status|restart}"
		RETVAL=1
		;;
esac

exit ${RETVAL}
