#!/bin/bash
#
### BEGIN INIT INFO
# Provides:        hinemos_agent
# Required-Start:  
# Required-Stop:   
# Default-Start:   2 3 4 5
# Default-Stop:        0 1 6
# Short-Description:   Hinemos Agent
### END INIT INFO

# 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.
. /lib/lsb/init-functions

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

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

# exist /var/log/subsys
test -e /var/lock/subsys || mkdir /var/lock/subsys

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} : "
	bash ${HINEMOS_AGENT_HOME}/bin/agent_start.sh -q
	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} : "
	bash ${HINEMOS_AGENT_HOME}/bin/agent_stop.sh -q
	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}
