#!/bin/bash

### BEGIN INIT INFO
# Provides: princity-agent
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start and stop princity-agent
# Description: Princity Agent
### END INIT INFO 

# główny katalog aplikacji, ściezka bezwzględna
APP_HOME=/opt/princity-agent/

# lokalizacja pidFile'a, dla Linuxa powinno to byc w /var/run
PID_FILE=/var/run/princity-agent.pid

# czas oczekiwania na zatrzymanie usługi
SHUTDOWN_WAIT=30

# colors
red='\e[0;31m'
green='\e[0;32m'
yellow='\e[0;33m'
reset='\e[0m'

echoRed() { echo -e "${red}$1${reset}"; }
echoGreen() { echo -e "${green}$1${reset}"; }
echoYellow() { echo -e "${yellow}$1${reset}"; }

start() {
   PID=$(
     cd $APP_HOME &&
     echo `nohup java -XX:-OmitStackTraceInFastThrow -jar princity.jar config/ > /dev/null 2>&1 & echo $!`
   )
}

case "$1" in
start)
    if [ -f $PID_FILE ]; then
        PID=`cat $PID_FILE`
        if [ -z "`ps -axf | grep -w ${PID} | grep -v grep`" ]; then
            start
        else
            echoYellow "Princity already running [$PID]"
            exit 0
        fi
    else
        start
    fi

    if [ -z $PID ]; then
        echoRed "Failed starting Princity"
        exit 3
    else
        echo $PID > $PID_FILE
        echoGreen "Started [$PID]"
        exit 0
    fi
;;

status)
    if [ -f $PID_FILE ]; then
        PID=`cat $PID_FILE`
        if [ -z "`ps -axf | grep -w ${PID} | grep -v grep`" ]; then
            echoRed "Princity is not running (process dead but pidfile exists)"
            exit 1
        else
            echoGreen "Princity is running [$PID]"
            exit 0
        fi
    else
        echoRed "Not running"
        exit 3
    fi
;;

stop)
    if [ -f $PID_FILE ]; then
        PID=`cat $PID_FILE`
        if [ -z "`ps -axf | grep -w ${PID} | grep -v grep`" ]; then
            echoRed "Princity is not running (process dead but pidfile exists)"
            exit 1
        else
            PID=`cat $PID_FILE`
            kill -TERM $PID
            let kwait=$SHUTDOWN_WAIT
            count=0;
            until [ `ps -p $PID | grep -c $PID` = '0' ] || [ $count -gt $kwait ]
            do
               echoYellow "Waiting to exit";
               sleep 1
               let count=$count+1;
            done
 
            if [ $count -gt $kwait ]; then
               echoRed "Killing processes didn't stop after $SHUTDOWN_WAIT seconds"
               kill -9 $PID
            fi

            echoGreen "Princity stopped [$PID]"
            rm -f $PID_FILE
            exit 0
        fi
    else
        echoRed "Princity is not running (pid not found)"
        exit 3
    fi
;;

restart)
    $0 stop
    $0 start
;;

*)
    echo "Usage: $0 {status|start|stop|restart}"
    exit 1
esac
