#!/bin/sh
#
# zope          Start/Stop the Zope web-application server.
#
# chkconfig: 2345 72 72
# description: zope is a web server specifically for handling \
#              HTTP requests to the Zope web-application service.
# 
# Source function library.
. /etc/rc.d/init.d/functions

INSTANCE_HOME=/var/zope
INSTANCE_NAME=`basename ${INSTANCE_HOME}`

# make sure starter script exists
[ -f ${INSTANCE_HOME}/zserver.sh ] || exit 0

RETVAL=0

# Source function library does not help us with the pid
# so we find get the pid from the file here *only*
pidfile=/var/zope/var/Z2.pid
pid=
if [ -f $pidfile ]; then
	pid=`cat $pidfile`
fi

# Modified version of killproc() from source function library

killproc() {
	RC=0
	# Test syntax.
	if [ "$#" -eq 0 ]; then
		echo $"Usage: killproc {program} [signal]"
		return 1
	fi

	notset=0
	# check for second arg to be kill level
	if [ -n "$2" ]; then
		killlevel=$2
	else
		notset=1
		killlevel="-9"
	fi

	# Save basename.
	base=${1##*/}

	# Kill it.
	if [ -n "${pid:-}" ] ; then
		[ "$BOOTUP" = "verbose" -a -z "$LSB" ] && echo -n "$base "
		if [ "$notset" -eq "1" ] ; then
			if checkpid $pid 2>&1; then
				# TERM first, then KILL if not dead
				kill -TERM $pid
				usleep 100000
				if checkpid $pid && sleep 1 &&
				checkpid $pid && sleep 3 &&
				checkpid $pid ; then
				kill -KILL $pid
				usleep 100000
			fi
		fi
		checkpid $pid
		RC=$?
		[ "$RC" -eq 0 ] && failure $"$base shutdown" || success $"$base shutdown"
		RC=$((! $RC))
		# use specified level only
		else
			if checkpid $pid; then
				kill $killlevel $pid
				RC=$?
				[ "$RC" -eq 0 ] && success $"$base $killlevel" || failure $"$base $killlevel"
			fi
		fi
	else
	    failure $"$base shutdown"
	    RC=1
	fi

        # Remove pid file if any.
	if [ "$notset" = "1" ]; then
	rm -f $pidfile
	fi
	return $RC
}

# Modified version of status() from source function library

status() {
	local base=${1##*/}

	# Test syntax.
	if [ "$#" = 0 ] ; then
		echo $"Usage: status {program}"
		return 1
	fi

	# First and only try "$pid"
	if [ -n "$pid" ]; then
	        echo $"${base} (pid $pid) is running..."
	        return 0
	fi

	# See if /var/lock/subsys/${base} exists
	if [ -f /var/lock/subsys/${base} ]; then
		echo $"${base} dead but subsys locked"
		return 2
	fi
	echo $"${base} is stopped"
	return 3
}

# See how we were called.
case "$1" in
  start)
	echo -n "Starting zope: "
  	cd ${INSTANCE_HOME}
	[ "$pid" != "" ] && ps h $pid >/dev/null 2>&1 && echo && exit $RETVAL
	rm -f ${INSTANCE_HOME}/var/Z2.pid
	daemon ${INSTANCE_HOME}/zserver.sh
	RETVAL=$?
  	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/${INSTANCE_NAME}
  	;;
  stop)
	echo -n "Shutting down zope: "
	killproc zope
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/${INSTANCE_NAME} ${INSTANCE_HOME}/var/Z2.pid
	;;
  restart|reload)
	$0 stop
	$0 start
	RETVAL=$?
	;;
  status)
	status zope
	[ $RETVAL -ne 0 ] && RETVAL=$?
	;;
  *)
	echo "Usage: zope {start|stop|restart|status}"
	exit 1
esac

exit $RETVAL
