#!/bin/bash

OPERATION=$1
PIDFILE=$2
NAME=$3
EXEC=$4
MAINDIR=$5

function start_server()
{
	# Starting child process.
	$EXEC $MAINDIR
	# Finished child process.
}

function get_mailserver_pid()
{
	KMS_PID="$(pidof -s $NAME)"
	let "KMS_PID += 0"	# make an integer number from empty string, if no process is found (0)
	return $KMS_PID
}

function is_mailserver_process_running()
{
	get_mailserver_pid
	if [ $? -gt 0 ]; then
		return 1
	else
		return 0
	fi
}

function should_server_run()
{
	if [ -e $PIDFILE ];	then
		# Server should run.
		return 1
	else
		# Server should not run.
		return 0
	fi
}

function start_watchdog()
{
	stop_watchdog

	while [ 1 ]; do

		is_mailserver_process_running
		res=$?
		if [ $res -eq "1" ]; then

			# Server is running, starting or stopping.
			sleep 5

		else
			# Server is not running.

			should_server_run
			res=$?
			if [ $res -eq "1" ]; then

				start_server &
			fi

			sleep 5
		fi

	done
}

function stop_watchdog()
{
	# Looking for watchdog process. 
	# Exclude the watchdog process, which invoked this function.

	MY_PID=$$
	WDOG_SCRIPT_NAME="$(basename $0)"
	WDOG_PID="$(pidof -x $WDOG_SCRIPT_NAME)"
	for i in $WDOG_PID; do
		if [ $i -ne $MY_PID ]; then
			# Quit process: $i
			kill -SIGTERM $i  >/dev/null 2>&1
		fi
	done
}

if [ "$OPERATION" == "start" ]; then
	start_watchdog
elif [ "$OPERATION" == "stop" ]; then
	stop_watchdog
else
	echo Missing or incorrect parameter.
fi
