#!/bin/bash
#
# hinemos_agent
# This shell script control Hinemos Job Agent.
#
# chkconfig: 2345 99 01
# description: Hinemos Agent

# Copyright (C) 2011 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_agent\(.*\)$/\1/"`

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

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

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

stop() {
	is_running
	if [ $? -ne 0 ]
	then
		# do nothing if not running
		return 0
	fi
	
	# shutdown if running
	echo -n "Stopping ${PROG} : "
	${HINEMOS_AGENT_HOME}/bin/agent_stop.sh
	RETVAL=$?
	echo
	return ${RETVAL}
}

is_running() {
	if ! [ -f ${HINEMOS_AGENT_PID} ]
	then
		return 1
	fi
	
	read PID < ${HINEMOS_AGENT_PID}
	if [ `ps --no-headers --pid ${PID} e | grep "java.*com.clustercontrol.agent.Agent" | wc -l` -eq 0 ]
	then
		return 1
	fi

	return 0
}

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

exit ${RETVAL}
