#!/bin/bash

PATH="/sbin:/usr/sbin:/bin:/usr/bin"
export PATH

# Source function library.
. /etc/init.d/functions

# Source clamav-milter configuration.
SourceIfNotEmpty /etc/mail/milters_watchdog.conf

if [ "x$MILTERS_LIST" == "x" ]; then
    logger -p mail.error -i -t $0 "MILTERS_LIST is not defined in /etc/mail/milter_watchdog.conf"
    exit 99
fi

ERRORS=0

for SERVICE_NAME in $MILTERS_LIST; do

    COUNT=`ps axm|grep $SERVICE_NAME|egrep -v "grep|_watchdog"|wc -l`

    if [ $[ $COUNT < 3 ] == 1 ]; then
	#echo "$SERVICENAME restarting..."
	service $SERVICE_NAME restart
	ERRORS=$(( $ERRORS +1 ))
	logger -p mail.warning -i -t $0 "service $SERVICE_NAME was restarted"
    fi

done

[ $ERRORS -eq 0 ] || logger -p mail.warning -i -t $0 "$ERRORS service(s) was  restarted"

exit $ERRORS
			