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


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

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

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

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


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

	if [ -f /var/lock/subsys/"plone2-$INSTANCE_NAME" ]; then
                echo -n $"Plone2 instance $INSTANCE_NAME is already running. "
		continue	
	fi
         
        action $"Starting Plone2 instance $INSTANCE_NAME: " "$INSTANCE_HOME"/bin/zopectl start
        echo
	RET=$?
	if [ $RET -eq 0 ]; then
		touch /var/lock/subsys/"plone2-$INSTANCE_NAME"
		RETVAL=0
	fi
    done
    return $RETVAL
}

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

	if [ ! -f /var/lock/subsys/"plone2-$INSTANCE_NAME" ]; then
		echo -n "Plone2 instance $INSTANCE_NAME is not running. "
		continue	
	fi
	
	action $"Stopping Plone2 instance $INSTANCE_NAME: " "$INSTANCE_HOME"/bin/zopectl stop
	RET=$?
	if [ $RET -eq 0 ]; then
		RETVAL=0
	fi
	rm -f /var/lock/subsys/"plone2-$INSTANCE_NAME"
    done
    return $RETVAL
}

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

# See how we were called.
case "$1" in
  start)
		start_instances
		RETVAL=$?
		if [ "$RETVAL" = 0 ] ; then
			touch /var/lock/subsys/plone2
		fi
	;;
  stop)
	if [ -f /var/lock/subsys/plone2 ]; then
		stop_instances
        	rm -f /var/lock/subsys/plone2 >/dev/null 2>&1
        else
	        echo -n "Plone2 is not running. "
                exit 1
        fi
	;;
  status)
	stat_instances
	;;
  restart|force-reload)
	$0 stop
	$0 start
	exit $?
	;;
  *)
	echo $"Usage: $0 {start|stop|restart|force-reload|status}"
	exit 3
	;;
esac

exit $RETVAL
