#!/bin/sh
# zope
#
# chkconfig: 345 90 10
# description: Starts and stops the Zope instances
# processname: z2.py
# config: /etc/sysconfig/zope
#
# probe: true
#


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

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network ]; then
		msg_network_down Zope
		exit 1
	fi
else
	exit 0
fi

# Zope settings.
INSTANCES="main"
[ -f /etc/sysconfig/zope ] && . /etc/sysconfig/zope


start_instances()
{
    RETVAL=1
    for INSTANCE_NAME in $INSTANCES
    do
	INSTANCE_HOME="/var/lib/zope/$INSTANCE_NAME"

	if [ -f /var/lock/subsys/"zope-$INSTANCE_NAME" ]; then
		msg_already_running "Zope instance $INSTANCE_NAME"
		continue
	fi

	run_cmd "Starting Zope instance $INSTANCE_NAME" "$INSTANCE_HOME"/bin/zopectl start
	RET=$?
	if [ $RET -eq 0 ]; then
		touch /var/lock/subsys/"zope-$INSTANCE_NAME"
		RETVAL=0
	fi
    done
    return $RETVAL
}

stop_instances()
{
    RETVAL=1
    for INSTANCE_NAME in $INSTANCES
    do
	INSTANCE_HOME="/var/lib/zope/$INSTANCE_NAME"

	if [ ! -f /var/lock/subsys/"zope-$INSTANCE_NAME" ]; then
		msg_not_running "Zope instance $INSTANCE_NAME"
		continue
	fi

	run_cmd "Stopping Zope instance $INSTANCE_NAME" "$INSTANCE_HOME"/bin/zopectl stop
	RET=$?
	if [ $RET -eq 0 ]; then
		RETVAL=0
	fi
	rm -f /var/lock/subsys/"zope-$INSTANCE_NAME"
    done
    return $RETVAL
}

stat_instances()
{
    for INSTANCE_NAME in $INSTANCES
    do
    	INSTANCE_HOME=/var/lib/zope/$INSTANCE_NAME
	PIDFILE=$INSTANCE_HOME/var/Z2.pid
	$INSTANCE_HOME/bin/zopectl status
    done
}

# See how we were called.
case "$1" in
  start)
  		msg_starting "Zope"
		started
		start_instances
		RETVAL=$?
		if [ "$RETVAL" = 0 ] ; then
			msg_starting "Zope"
			ok
			touch /var/lock/subsys/zope
		else
			msg_starting "Zope"
			fail
		fi
	;;
  stop)
	if [ -f /var/lock/subsys/zope ]; then
        	msg_stopping "Zope"
		started
		stop_instances
		RETVAL=$?
		if [ "$RETVAL" = 0 ] ; then
			msg_stopping "Zope"
			ok
		else
			msg_stopping "Zope"
			fail
		fi
        	rm -f /var/lock/subsys/zope >/dev/null 2>&1
        else
	        msg_not_running "Zope"
                exit 1
        fi
	;;
  status)
	stat_instances
	;;
  restart|force-reload)
	$0 stop
	$0 start
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|force-reload|status}"
	exit 3
	;;
esac

exit $RETVAL
