#! /bin/bash
# Start/stop/restart clamav.

# Start clamav:
function clamav_start {
	local CLAMD_COMMAND="/usr/sbin/clamd"
	local MILTER_COMMAND="/usr/sbin/clamav-milter --external
		--quiet --dont-scan-on-error --local --max-children=2
		--pidfile=/var/run/clamav-milter/milter.pid
		local:/var/run/clamav-milter/milter.sock"
	local TIMER=0

	test -x /usr/sbin/clamd || return

	echo "Starting clamd daemon: " ${CLAMD_COMMAND%% *}
	eval $CLAMD_COMMAND

	test -x /usr/sbin/clamav-milter || return

	# Give clamd a chance to make the socket
	while ! test -S /var/run/clamav-milter/clamd.sock; do
		sleep .2
		let TIMER+=1
		if test $TIMER -gt 50; then  # give it 10 seconds
			echo "ERROR: Cannot start clamav-milter, because clamd did not make its socket."
			return
		fi
	done

	echo "Starting clamav-milter daemon: " ${MILTER_COMMAND%% *}
	eval $MILTER_COMMAND
}

function clamav_stop_process {
	local TIMER=0
	local PID

	if test -f $2; then
		read PID < $2
		echo -n "Stopping $1... "
		kill -15 $PID				# 15=SIGTERM
		while test -d /proc/${PID#-}; do	# omit any leading `-'
			sleep .2
			let TIMER+=1
			if test $TIMER -gt 25; then 	# give it 5 seconds
				echo "Failed. Force-killing it."
				kill -9 $PID		# 9=SIGKILL
				rm --force $2
				return
			fi
		done
		echo "OK."
	else
		killall --verbose -9 $1
	fi
}

# Stop clamav:
function clamav_stop {
	clamav_stop_process clamd /var/run/clamav-milter/clamd.pid
	clamav_stop_process clamav-milter /var/run/clamav-milter/milter.pid
}

case "$1" in
	( 'start' )
		clamav_start
		;;
	( 'stop' )
		clamav_stop
		;;
	( 'restart' )
		clamav_stop
		clamav_start
		;;
	( * )
		echo "Usage: $0 start|stop|restart"
		exit 1
		;;
esac
