#!/bin/bash

### BEGIN INIT INFO
# Provides:          eltex-pcrf
# Required-Start:    $network $syslog $remote_fs
# Required-Stop:     $network $syslog $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Eltex.PCRF
# Description:       Eltex.PCRF, part of Eltex.SoftWLC
### END INIT INFO

NAME=eltex-pcrf

# defaults
JAVA=/usr/bin/java

if [ -f /etc/default/$NAME ]; then
    source /etc/default/$NAME || exit 1
fi

JAVA_ARGS="$JVM_OPTS -jar $JAR"
PIDFILE="/var/run/$NAME.pid"
USER="pcrf"
GROUP="pcrf"
VAR_DIR="/var/lib/$NAME"

source /lib/lsb/init-functions || exit 1

if [ ! -e "$JAVA" ]; then
    log_failure_msg "Java not found in $JAVA"
    exit 1
fi

if [ ! -e "$JAR" ]; then
    log_failure_msg "Service is not installed"
    exit 0
fi

start() {
    if ! /sbin/start-stop-daemon --status -p $PIDFILE > /dev/null ; then
        log_daemon_msg "Starting $NAME"
        /sbin/start-stop-daemon --start -d $VAR_DIR -b -c $USER:$GROUP -m -p $PIDFILE -x $JAVA -- $JAVA_ARGS
        log_end_msg $?
    else
        log_warning_msg "$NAME is already running"
    fi
}

stop() {
    if /sbin/start-stop-daemon --status -p $PIDFILE > /dev/null ; then
        log_daemon_msg "Stopping $NAME"
        /sbin/start-stop-daemon --stop -p $PIDFILE -u $USER --retry 5
        log_end_msg $?
    else
        log_warning_msg "$NAME is not running"
    fi
    rm -f $PIDFILE
}

# Check the status of the process.
status() {
    if [ -e ${PIDFILE} ]; then
        status_of_proc -p ${PIDFILE} ${JAVA} "$NAME process" && exit 0 || exit $?
    else
        log_daemon_msg "$NAME process is not running"
        log_end_msg 0
    fi
}

case $1 in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart|force-reload)
        stop
        start
    ;;
    status)
        status
    ;;
    *)
        # For invalid arguments, print the usage message.
        echo "Usage: $0 {start|stop|restart|force-reload|status}"
        exit 2
    ;;
esac
