#!/bin/bash
#
# Startup script for the Clam AntiVirus daemon
#
# description: Clam AntiVirus Daemon
# processname: clamd
# pidfile: /var/run/clamd.pid
# config: /usr/local/clamXav/etc/clamd.conf

# $Id: ClamAntiVirusDaemon,v 1.7 2007/05/05 16:53:58 okamura Exp $

# Source function library.
. /etc/rc.common

# Path to the clamd binary.
clamd=/usr/local/clamXav/sbin/clamd
processName=clamd
# Path to the clamd.conf.
configFile=/usr/local/clamXav/etc/clamd.conf
# Lock file
pidFile=
isSetPidFileByConfig=1
if [ -f "$configFile" ]; then
	pidFile=`sed -n 's/^[ 	]*PidFile[ 	][ 	]*\(.*\)/\1/p' "$configFile" | tail -1 | sed 's/[ 	][ 	]*$//'`
fi
if [ "$pidFile" == '' ]; then
	pidFile="/var/run/${processName}.pid"
	isSetPidFileByConfig=0
fi
# Base directory of this script
basedir=`dirname $0`

RETVAL=0

StartService() {
	if [ -e "$configFile" ] && ! GetPID "$processName" > /dev/null ; then
		if [ ! -f "$pidFile" ]; then
			echo "Starting Clam AntiVirus Daemon"
			"$clamd" --config-file="$configFile"
			RETVAL=$?
			if [ $RETVAL -eq 0 -a $isSetPidFileByConfig -eq 0 ]; then
				ps axw | grep "$clamd --[c]onfig-file=" | awk '{print $1;}' > "$pidFile"
			fi
		fi
	fi

	return $RETVAL
}

StopService() {
	local	waitTimes=0
	local	maxWaitTimes=8

	if pid=$(GetPID "$processName"); then
		echo "Stopping Clam AntiVirus Daemon"
		if [ -f "$pidFile" ]; then
			kill -TERM `cat "$pidFile"`
		else
			kill -TERM $pid
		fi
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			if [ $isSetPidFileByConfig -eq 0 ]; then
				while [ $waitTimes -lt $maxWaitTimes ] && ps ax | grep "^[ 	]*$pid[ 	]" > /dev/null; do
					sleep 1
					waitTimes=`expr $waitTimes + 1`
				done
			else
				while [ $waitTimes -lt $maxWaitTimes -a -f "$pidFile" ]; do
					sleep 1
					waitTimes=`expr $waitTimes + 1`
				done
			fi
			if [ -f "$pidFile" ]; then
				if ps ax | grep "^[ 	]*$pid[ 	]" > /dev/null; then
					echo 'clamd is busy or frozen. Kill it by force.' 1>&2
					kill -9 $pid
				fi
				rm -f "$pidFile"
			fi
		fi
	else
		echo "Clam AntiVirus Daemon is not running"
	fi

	return $RETVAL
}

RestartService () {
	StopService
	StartService
}

RunService "$1"
