#! /bin/bash
### BEGIN INIT INFO
# Provides:          open-xchange
# Required-Start:    $local_fs $remote_fs $network $syslog
# Should-Start:      mysql
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Should-Stop:       mysql
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/stop open-xchange
### END INIT INFO

# Open-Xchange Initscript

STARTSCRIPT=/opt/open-xchange/sbin/open-xchange
NAME=open-xchange
DESC="Open-Xchange"
DEFAULTS=/etc/default/open-xchange
OXFUNCTIONS=/opt/open-xchange/lib/oxfunctions.sh
OXCONFIG=/opt/open-xchange/etc/ox-scriptconf.sh

# Defaults - don't touch, edit /etc/default/open-xchange
ENABLED=0

test -f $DEFAULTS && . $DEFAULTS
if [ ! -f $OXFUNCTIONS ]; then
    echo "$DESC: $OXFUNCTIONS missing, exiting"
    exit 0
fi
if [ ! -f $OXCONFIG ]; then
    echo "$DESC: $OXCONFIG missing, exiting"
    exit 0
fi

. /lib/lsb/init-functions
. $OXFUNCTIONS
. $OXCONFIG

if [ "$ENABLED" = "0" ]; then
    echo "$DESC: disabled, see $DEFAULTS"
    exit 0
fi

ulimit -n $NRFILES

if ox_is_running open-xchange-admin "/opt/open-xchange/etc/admindaemon"; then
   echo -n "old 6.20 admin daemon still running, shutting down..."
   ox_stop_daemon open-xchange-admin
   while ox_is_running open-xchange-admin "/opt/open-xchange/etc/admindaemon"; do
        sleep 1
   done
   echo " done"
fi
if ox_is_running open-xchange-groupware "/opt/open-xchange/etc/groupware"; then
   echo -n "old 6.20 groupware still running, shutting down..."
   ox_stop_daemon open-xchange-groupware
   while ox_is_running open-xchange-groupware "/opt/open-xchange/etc/groupware"; do
        sleep 1
   done
   echo " done"
fi

case "$1" in
  start)
    echo -n "Starting $DESC: "
    ox_start_daemon $STARTSCRIPT $NAME open-xchange open-xchange
    echo "$NAME."
    ;;

  stop)
    echo -n "Stopping $DESC: "

    pidfile=/var/run/open-xchange.pid
    test -e $pidfile && read pid < $pidfile
    ox_stop_daemon $NAME
    while ox_is_running open-xchange "/opt/open-xchange/etc" $pid; do
          sleep 1
    done
    echo "$NAME."
    ;;

  restart|force-reload)
    echo -n "Restarting $DESC: "
        $0 stop
        $0 start
    echo "$NAME."
    ;;

  status)
    status_of_proc -p /var/run/open-xchange.pid $STARTSCRIPT "$NAME"
    exit $?
    ;;

  *)
    N=/etc/init.d/$SNAME
    echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
    exit 1
    ;;
esac

exit 0
