#! /bin/bash

### BEGIN INIT INFO
# Provides:          sogod
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: SOGo server
### END INIT INFO

# SOGo init script for SLES
#
# Copyright (C) 2009 Inverse inc.
#
# Author: Wolfgang Sourdeau <wsourdeau@inverse.ca>
#         Ludovic Marcotte <ludovic@inverse.ca>
#
# This file 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; either version 2, or (at your option)
# any later version.
#
# This file 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
PATH=/sbin:/bin:/usr/sbin:/usr/bin

NAME=sogo
DAEMON=/usr/sbin/sogod
DESC="SOGo"

USER=$NAME
PREFORK=3

PIDFILE=/var/run/$NAME/$NAME.pid
LOGFILE=/var/log/$NAME/$NAME.log

if [ -f /etc/sysconfig/$NAME ]; then
    . /etc/sysconfig/$NAME
fi

if [ ! -x $DAEMON ]; then
 echo "$DAEMON is not executable."
 exit 1
fi

checkDir() {
    directory="$1"
    if [ ! -d "$directory" ]
    then
	echo "$directory does not exist."
	exit 1
    fi

    if [ `/usr/bin/stat "$directory" -c %U` != "$USER" ]
    then
	echo "$directory is not owned by the '$USER' user."
	exit 1

    fi
}

checkDir /var/run/$NAME
checkDir /var/spool/$NAME
checkDir /var/log/$NAME

set -e

. /lib/lsb/init-functions
. /usr/share/GNUstep/Makefiles/GNUstep.sh

DAEMON_OPTS="-WOWorkersCount $PREFORK -WOPidFile $PIDFILE -WOLogFile $LOGFILE"

case "$1" in
  start)
	echo -n "Starting $DESC: "
	startproc -u $USER $DAEMON $DAEMON_OPTS || true
	echo "$NAME."
	;;
  stop)
	echo -n "Stopping $DESC: "
	killproc -p $PIDFILE $DAEMON || true
	echo "$NAME."
	;;
  restart)
	echo -n "Restarting $DESC: "
	killproc -p $PIDFILE $DAEMON || true
        sleep 1
	startproc -u $USER $DAEMON $DAEMON_OPTS || true
	echo "$NAME."
	;;
  condrestart|try-restart)
	if checkproc -p "$PIDFILE" $DAEMON >&/dev/null; then
	  restart
	fi
	;;
  status)
	checkproc -p $PIDFILE $DAEMON
        result="$?"
        if [ $result -eq 0 ]
        then
          echo "$DAEMON is running"
        else
        if [ $result -eq 1 ]
        then
          echo "$DAEMON is not running (stale pid file)"
        else
        if [ $result -eq 3 ]
        then
          echo "$DAEMON is not running"
        fi
	fi
	fi
	;;
  *)
	echo "Usage: $NAME {start|stop|restart|condrestart|status}" >&2
	exit 1
	;;
esac

exit 0
