#!/bin/bash -e
### BEGIN INIT INFO
# Provides:          kerio-workspace-rendering
# Required-Start:    $remote_fs $local_fs $network
# Required-Stop:     $remote_fs $local_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start Kerio Workspace Rendering Server
# Description:       Start Kerio Workspace Rendering Server (OpenOffice.org headless server)
### END INIT INFO

DESC="Kerio Workspace Rendering Server"

OOO_BASE=/opt/kerio/workspace/rendering/openoffice.org3
[ -d $OOO_BASE ] || OOO_BASE=/opt/openoffice.org3
[ -d $OOO_BASE ] || OOO_BASE=/usr/lib/openoffice
EXEC="$OOO_BASE/program/soffice"
test -x $EXEC || exit 0

OOO_ARGS="-headless -nologo -norestore -nofirststartwizard -accept=socket,host=127.0.0.1,port=4063;urp"
PIDFILE=/opt/kerio/workspace/logs/kerio-workspace-rendering.pid

if which start-stop-daemon >/dev/null && start-stop-daemon --help | grep -q chuid; then
function start-ooo() { start-stop-daemon --start -c kworkspace -g kworkspace -b -m --pidfile $PIDFILE --exec $EXEC -- $OOO_ARGS; }
function stop-ooo() { start-stop-daemon --stop --oknodo --quiet --pidfile $PIDFILE; }
else
function start-ooo() {
	sudo -H -u kworkspace $EXEC $OOO_ARGS &
	echo $! > $PIDFILE

}
function stop-ooo() {
	kill `cat $PIDFILE`
	rm -f $PIDFILE
}
fi


function status-ooo()
{
    [ -f $PIDFILE ] || return 3
    ps -p `cat $PIDFILE` > /dev/null 2>/dev/null || return 1
    return 0
}

case "$1" in
    start)
	echo "Starting $DESC"
	status-ooo && exit 0
	start-ooo
	;;
    stop)
	echo "Stopping $DESC"
	stop-ooo
	rm -f $PIDFILE
	;;
    status)
	if status-ooo; then
	    echo "$DESC is running"
	    exit 0
	else
	    echo "$DESC is not running"
	    exit 1
	fi
	;;
    restart|force-reload)
	echo "Stopping $DESC"
	stop-ooo
	echo "Starting $DESC"
	start-ooo
	;;
    *)
	echo "Usage: $0 {start|stop|status}"
	exit 1
	;;
esac

