#!/bin/sh
#
# chkconfig: 2345 98 02
# description: Hinemos JBoss

#Copyright (C) 2006 - 2008 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

# Source config
. /opt/hinemos/hinemos.cfg

HINEMOS_JBOSS_LOCK_FILE=/var/lock/subsys/hinemos_jboss

RETVAL=0
PROG="hinemos_jboss"
USER=hinemos

start() {
	echo -n $"Starting $PROG: "
	sleep 3
	if [ ! -f ${HINEMOS_PG_PID} ];  then
		failure "hinemos_pg is not running, ${PROG} startup"
		echo ""
		echo "hinemos_pg is not running"
		return 1
	elif  [ ! -f ${HINEMOS_LDAP_PID} ];  then
		failure "hinemos_ldap is not running, ${PROG} startup"
		echo ""
		echo "hinemos_ldap is not running"
		return 1
	fi
	if  [ -f ${HINEMOS_JBOSS_PID} ];  then
		read JBOSS_PID < ${HINEMOS_JBOSS_PID}
		ps -p ${JBOSS_PID} e | grep "org.jboss.Main" > /dev/null && TMP=1
		if [ "$TMP" ] ; then
			failure "Hinemos JBoss (pid $JBOSS_PID) is running..., ${PROG} startup"
			echo ""
			echo "Hinemos JBoss (pid $JBOSS_PID) is running..."
		return 1
		fi
	fi
	if  ( ps -ef | grep "[o]rg.jboss.Main" > /dev/null ); then
		failure "another jboss is running, ${PROG} startup"
		echo ""                 
		echo "another jboss is running"
		return 1
	fi
	daemon --user=${USER} ${HINEMOS_HOME}/jboss-4.0.3SP1/bin/run_hinemos.sh
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch ${HINEMOS_JBOSS_LOCK_FILE}
        return $RETVAL
}

stop() {
        echo -n $"Stopping $PROG: "
	${HINEMOS_HOME}/jboss-4.0.3SP1/bin/shutdown_hinemos.sh -S
	RETVAL=$?
	TMP=0
	if [ $RETVAL -eq 0 ] ; then  
		for CNT in `seq 1 60`
		do        
			sleep 1
			ps -ef | grep ${JBOSS_HOME} | grep "org.jboss.Main" > /dev/null || TMP=1
			echo -n .
			if [ ${TMP} -ne 0 ] ; then
				echo ""
				success $"$PROG shutdown"
				rm -f ${HINEMOS_JBOSS_LOCK_FILE} ${HINEMOS_JBOSS_PID}
				return $RETVAL
			fi
		done
		failure $"$PROG shutdown"
	else 
		failure $"$PROG shutdown"
	fi
	return $RETVAL
}

# See how we were called.
case "$1" in        
	start)
		start
		;;
        stop)
		stop
		;;
	status)
		if [ -f $HINEMOS_JBOSS_PID ] ; then
			read JBOSS_PID < $HINEMOS_JBOSS_PID
			ps -p $JBOSS_PID e | grep $JBOSS_HOME > /dev/null && TMP=1
			if [ "$TMP" ] ; then
				echo "Hinemos JBoss (pid $JBOSS_PID) is running..."
				RETVAL=0
			else
				echo "Hinemos JBoss is stopped"
				RETVAL=3
			fi
		else
			echo "Hinemos JBoss is stopped"
			RETVAL=3
		fi
		;;
	restart)
		stop
		start
		;;
        *)
                echo $"Usage: $prog {start|stop|restart|status}"
                exit 1
esac

exit $RETVAL
