#! /bin/bash
# Copyright (c) 2012,2017 Stefan Schaefer - FSP Computer & Netzwerke
# LICENSE GPLv3
#
# Author: Stefan Schaefer - stefan.schaefer@fsproductions.de

# Read configuration
SERVICE="$1"
[ -r /etc/default/$SERVICE ] && . /etc/default/$SERVICE
[ -r /etc/benno/benno-global-service.conf ] && . /etc/benno/benno-global-service.conf

if [[ $SERVICE != "benno-smtp" ]]; then
    [ -r /etc/benno/$SERVICE-service.conf ] && . /etc/benno/$SERVICE-service.conf
else
    [ -r /etc/$SERVICE/$SERVICE-service.conf ] && . /etc/$SERVICE/$SERVICE-service.conf
fi

# Exit if components are not installed
test -x $SERVICE_BIN || { echo "$SERVICE_BIN not installed";
    if [ "$2" = "stop" ]; then exit 0; else exit 5; fi; }

test -r $SERVICE_JAR || { echo "$SERVICE_JAR not existing";
    if [ "$2" = "stop" ]; then exit 0; else exit 6; fi; }

# Set environment variables
export LANG=C

# Should the benno service be started?
if [ "$START_DAEMON"x != "yes"x ]; then
                echo "$SERVICE disabled: not starting. To enable it edit /etc/default/$SERVICE"
                exit 0
fi

# create service pidfile path
SERVICE_PID="$PIDDIR/$SERVICE.pid"

# PID lookup
getpid() {
	pid=`ps -eo pid,args |grep -v "grep" | grep "$SERVICE_JAR" |sed "s/^[ \t]*//" |cut -d " " -f1`
	echo $pid
}

case "$2" in
    start)
	echo "Starting Service: $SERVICE"

	nohup $SERVICE_BIN $SERVICE_START_OPTS > $SERVICE_LOG 2>&1 &
	#nohup $SERVICE_BIN $SERVICE_START_OPTS > /var/log/benno/benno-smtp.log 2>&1 &
	pid=`getpid`
	echo $pid > $SERVICE_PID
	;;
    stop)
	echo "Shutting down Service: $SERVICE"
	echo stop | $SERVICE_MGMT $DAEMON_ADDRESS $DAEMON_PORT 2>/dev/null
	kill -0 `cat $SERVICE_PID` 2>/dev/null
	exitcode=$?
	if [[ $exitcode = 0 ]];then
	    sleep 5
	    kill `cat $SERVICE_PID` 2>/dev/null
	    pid=`getpid`
	    if [[ -z $pid ]]; then
		rm $SERVICE_PID
		exit 0
	    else
		exit 1
	    fi
	fi
	;;
    restart)
	## Stop the service and regardless of whether it was
	## running or not, start it again.
	$0 $1 stop
	# perhaps Sleep Time
	# sleep xy
	$0 $1 start
	;;
    *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
	;;
esac
