#!/bin/sh
# kFreeBSD do not accept scripts as interpreters, using #!/bin/sh and sourcing.
if [ true != "$INIT_D_SCRIPT_SOURCED" ] ; then
    set "$0" "$@"; INIT_D_SCRIPT_SOURCED=true . /lib/init/init-d-script
fi

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

DESC="The Minager web app server"
NAME='minager'
MINECRAFT_HOME='/home/minecraft'
MINAGER_HOME="$MINECRAFT_HOME/minager"
DAEMON_HOME="$MINAGER_HOME/bin"
DAEMON="$DAEMON_HOME/$NAME.jar"
PIDFILE="$DAEMON_HOME/$NAME.pid"
SCRIPTNAME="$DAEMON_HOME/$0"

start()
{
    # If PIDFILE exists and PID is in running processes
    if [ -f $PIDFILE ] && kill -0 `cat $PIDFILE` 2>/dev/null
    then
        echo 'Service already running\n'
    else    
        echo "Starting service $NAME"
	cd $DAEMON_HOME
        nohup 2>/dev/null java -jar $DAEMON &>/dev/null &
        expr $! - 1 > $PIDFILE
        echo "Service started [`cat $PIDFILE`]\n"
    fi
}

stop()
{
    # If PIDFILE doesn't exists or PID isn't in running processes
    if [ ! -f "$PIDFILE" ] || ! kill -0 `cat "$PIDFILE"`
    then
        echo 'Service not running\n'
    else
        echo 'Stopping service...'
        # Send signal to end to the process
        kill -15 `cat "$PIDFILE"` && rm -f "$PIDFILE"
        echo 'Service stopped\n'
    fi
}

status()
{
    if [ -f $PIDFILE ] && kill -0 `cat $PIDFILE` 2>/dev/null
    then
        echo "Service is running (${GREEN}● active${NC})\n"
    else
        echo "Service not running (${RED}● inactive${NC})\n"
    fi
}

case "$1" in
    'start')
        start
        ;;
    'stop')
        stop
        ;;
    'status')
        status
        ;;
    'restart')
        stop
        sleep 5
        start
        ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|status|restart}\n" >&2
        exit 3
        ;;
esac
exit 0
