#!/bin/bash
#
# benno-rest    Archiving daemon for Benno MailArchiv
#
# chkconfig:    2345 99 01
# description:  The Benno MailArchiv archiving daemon reads mails from inspool
#               and indexes and archives them.
# processname:  benno-rest
# config: /etc/default/benno-rest
# config: /etc/benno/benno.xml
#

### BEGIN INIT INFO
# Provides: benno-rest
# Required-Start: $local_fs $network
# Required-Stop: $local_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: SMTP gateway for Benno Mailarchive
# Description: This is a daemon which provides an SMTP interface
#              to the Benno Mailarchiv mail archive system.
### END INIT INFO

# Source function library.
. /etc/init.d/functions

PIDFILE="/var/run/benno-rest.pid"
NAME="benno-rest"
DAEMON=/usr/bin/java
JAR_FILE=bennorest.jar
START_JAR="-jar $JAR_FILE"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
BENNOCOREDIR=/opt/benno
LOG_CONFIG=/etc/benno/bennorest-log4j.xml

LANG=C; export LANG
DAEMON_PORT='8080'

# Read configuration file if present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

if [ "$START_ARCHIVE"x != "yes"x ]; then
	echo "$NAME disabled: not starting. To enable it edit /etc/default/$NAME"
	exit 0
fi

start() {
    getstatus
    if [ $RETVAL -eq 0 ];then
        echo -n "$NAME already running."
        return
    fi
    echo -n "Starting $NAME."
    umask 027
    cd $BENNOCOREDIR
    daemon --check $NAME \
           --user $USER "/usr/bin/java \
           -Dlog4j.configuration=$LOG_CONFIG \
           $START_JAR \
           $DAEMON_ARGS &" 2> /dev/null
    RETVAL=$?
    if [ $RETVAL != "0" ];then
        echo "... failed."
        exit $RETVAL
    fi
}

stop() {
    echo -n "Shutting down $NAME."
    /sbin/fuser -s -k -n tcp $DAEMON_PORT
    RETVAL=$?
    if [ $RETVAL -ne 0 ];then
        echo "...failed."
        exit $RETVAL
    fi
}


getstatus() {
    /sbin/fuser -s -n tcp $DAEMON_PORT
    RETVAL=$?
}


case "$1" in
    start)
        start
        echo
        exit $RETVAL
    ;;
    stop)
        stop
        echo
        exit $RETVAL
    ;;
    status)
        getstatus
        if [ $RETVAL != "0" ];then
            echo "$NAME is not running."
        else
            echo "$NAME is running."
        fi
        exit $RETVAL
    ;;
    restart|reload)
        stop
        start
    ;;
    *)
    echo "Usage: benno-rest {start|stop|status|reload|restart}"
    exit 1
    ;;
esac
exit $?
