#!/bin/sh

### BEGIN INIT INFO
# Provides:          zope3
# Required-Start:    $syslog $local_fs
# Required-Stop:     $syslog $syslog
# Should-Start:      $local_fs
# Should-Stop:       $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start zope3 instances
# Description:       Start the instances defined in /etc/default/zope3
### END INIT INFO

ZVER=3
[ -d /var/lib/zope$ZVER/instance -a -d /var/lib/zope$ZVER/zeo -a -d /usr/lib/zope$ZVER ] || exit 0

. /lib/lsb/init-functions
. /etc/default/zope$ZVER

if [ "$ZEOSERVERS" = "NONE" -o "$ZEOSERVERS" = "" ]; then
    ZEOSERVERS=''
    log_warning_msg "Zope$ZVER: ZEO servers have been disabled, edit /etc/default/zope$ZVER to enable them."
elif [ "$ZEOSERVERS" = "ALL" ]; then
    ZEOSERVERS='*'
fi

if [ "$INSTANCES" = "NONE" -o "$INSTANCES" = "" ]; then
    INSTANCES=''
    log_warning_msg "Zope$ZVER: instances have been disabled, edit /etc/default/zope$ZVER to enable them."
elif [ "$INSTANCES" = "ALL" ]; then
    INSTANCES='*'
fi

case "$1" in
    start|stop|restart)
        p=''; [ "$1" = "stop" ] && p='p'

        if [ -n "$ZEOSERVERS" ]; then
            cd /var/lib/zope$ZVER/zeo
            for i in $ZEOSERVERS ; do
                    if [ "$i" = "*" ]; then
                        # log_success_msg "Zope$ZVER: no ZEO servers found."
                        break
                    elif [ ! -d "$i" ]; then
                        continue
                    fi
        
                    if [ -x $i/bin/zeoctl ] ; then
                        log_begin_msg "Zope$ZVER: ${1}${p}ing $i ZEO server"
                        $i/bin/zeoctl "$1" >/dev/null 2>&1
                        log_end_msg $?
                    else 
                        log_warning_msg "Zope$ZVER: skipping $i (old/purged)"
                    fi
            done
        fi

        if [ -n "$INSTANCES" ]; then
            cd /var/lib/zope$ZVER/instance
            for i in $INSTANCES ; do
                    if [ "$i" = "*" ]; then
                        log_success_msg "Zope$ZVER: no instances found."
                        break
                    elif [ ! -d "$i" ]; then
                        continue
                    fi

                    if [ -x $i/bin/zopectl ] ; then
                        log_begin_msg "Zope$ZVER: ${1}${p}ing $i instance"
                        dzhandle -z $ZVER zopectl "$i" $1 >/dev/null 2>&1
                        log_end_msg $?
                    else 
                        log_warning_msg "Zope$ZVER: skipping $i (old/purged)"
                    fi
            done
        fi
        ;;

    force-reload)
        echo "Zope$ZVER doesn't support force-reload, use restart instead."
        ;;
		
    *)
        echo "Usage: /etc/init.d/zope$ZVER {start|stop|restart|force-reload}"
        exit 1
        ;;
esac

exit 0
