#!/bin/bash

function restartService() {
	name=$1
	rv=0
	subject="Warning: service $name not running"
	message="The service $name is not running."
	# try to stop first
	service $name stop 1>/dev/null 2>&1
	output=$(service $name start 2>&1)
	if [ $? = 0 ]; then
		message="$message\nRestarted successfully."
	else
		message="$message\nRestart failed:\n$output"
		rv=1
	fi
	message=$(echo -e "$message")
	auralis-console mail:send_admin --disable-exceptions "$subject" "$message"
	if [ $? -ne 0 ]; then
		# print subject and message to stdout such that it can be catched by
		# cron
		echo $subject
		echo "$message" # the quotes are required to preserver line breaks
	fi
	return $rv
}

function isServiceDisabled() {
	name=$1
	ls /etc/rc*.d/S*$name >/dev/null 2>&1
	[ $? -eq 0 ] && return 0
	return 1
}

# Returns 0 if service is running or is not running and should not run.
# Returns 1 if service is succesfully restared. Returns 2 otherwise.
function checkService() {
	name=$1
	rv=0
	service $name status >/dev/null
	status=$?
	isServiceDisabled $name
	disabled=$?
	# http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
	if [[ ($status -ne 0 && $status -ne 3) || ($status -ne 0 && $disabled -eq 0) ]]; then
		# restart if service is not running and not intentionally stopped
		restartService $name
		if [ $? -eq 0 ]; then
			rv=1
		else
			rv=2
		fi
	fi
	return $rv
}

# Returns 0 if activesyncfilterd is running or is not running and should not run.
# Returns 1 if service is succesfully restared. Returns 2 otherwise.
function checkActiveSyncFilterService() {
	name=activesyncfilterd
	isServiceDisabled $name
	disabled=$?
	if [ $disabled -eq 1 ]; then
		return 0
	fi
	
	rv=0
	auralis-console filterserver:status >/dev/null 2>&1
	status=$?
	if [ $status -ne 0 ]; then
		restartService $name
		if [ $? -eq 0 ]; then
			rv=1
		else
			rv=2
		fi
	fi
	
	return $rv
}

checkService apache2
checkService mysql
checkService auralis-apnsd
checkService auralis-gcmd
checkService snmpd
checkActiveSyncFilterService
