#! /bin/sh
### BEGIN INIT INFO
# Provides:       webmail
# Required-Start: $remote_fs tomcat apache2 sessiond groupware
# Required-Stop:
# Default-Start:  3 5
# Default-Stop:
# Description:    start the Open-Xchange Webmail application
### END INIT INFO
. /etc/rc.status

# First reset status of this service
rc_reset

enablessl=

OX_BIN=/usr/bin/openexchange-webmail
test -x $OX_BIN || exit 5
UPLOADTEMP=/var/lib/open-xchange/webmailupload
LOGFILE=/var/lib/open-xchange/log/webmail.log
USER=tomcat
PROG_NAME="OXWebmail"

create_temp() {
    rm -rf $UPLOADTEMP
    mkdir $UPLOADTEMP
    chmod 700 $UPLOADTEMP
    chown $USER $UPLOADTEMP
    test -d $UPLOADTEMP || {
	echo -n "  unable to create $UPLOADTEMP "
	exit 1
    }
}

java_pslist() {
    unset COLUMNS
    # ORG, works with linux great
    # ps xao "%p %a" | grep -E '.*java.*-DappName=webmailApp' | grep -v grep | awk '{print $1}'
    
    # for solaris, bug ID: 37
    # ps eafo "pid,args" | grep -E '.*java.*-DappName=webmailApp' | grep -v grep | awk '{print $1}'
    
    # next try to make all happy
    ps axwww | grep -E '.*java.*-DappName=webmailApp' | grep -v grep | awk '{print$1}'

}

java_killproc() {
    is_running=0
    for i in $(java_pslist); do
	is_running=1
	kill -KILL $i > /dev/null 2>&1
    done
    if [ $is_running -eq 0 ]; then
	return 7
    fi
    return 0
}

java_startproc() {
    if [ -n "$(java_pslist)" ]; then
	return 0
    fi
    #sudo -u $USER $OX_BIN >> $LOGFILE 2>&1 &
    su $USER -s /bin/bash $OX_BIN >> $LOGFILE 2>&1 &
    return 0
}

java_checkproc() {
    if [ -n "$(java_pslist)" ]; then
	return 0
    else
	return 3
    fi
}


start() {
    echo -n "Starting $PROG_NAME"
    
    create_temp
    java_startproc
    rc_status -v
}

stop() {
    echo -n "Shutting down $PROG_NAME"
    java_killproc
    rc_status -v
}


case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    restart)
	stop
        sleep 2
        start
	;;
    status)
	echo -n "Checking for $PROG_NAME: "
	java_checkproc
        rc_status -v
	;;
    *)
	echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}"
	exit 1
	;;
esac
