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

# $Id: FreshClamDaemon,v 1.6 2007/09/12 15:31:53 okamura Exp $

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

# Path to the freshclam binary.
freshclam=/usr/local/clamXav/bin/freshclam
processName=freshclam
# Path to the freshclam.conf.
configFile=/usr/local/clamXav/etc/freshclam.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

RETVAL=0

StartService() {
	if [ -e "$configFile" ] && ! GetPID "$processName" > /dev/null ; then
		if [ ! -f "$pidFile" ]; then
			echo "Starting Clam AntiVirus Database Updater Daemon"
			"$freshclam" --daemon
			RETVAL=$?
			if [ $RETVAL -eq 0 -a $isSetPidFileByConfig -eq 0 ]; then
				ps axw | grep "$freshclam --[d]aemon" | awk '{print $1;}' > "$pidFile"
			fi
		fi
	else
		echo "Clam AntiVirus Database Updater Daemon has already running"
	fi
	return $RETVAL
}

StopService() {
	if pid=$(GetPID "$processName"); then
		echo "Stopping Clam AntiVirus Database Updater Daemon"
		kill -TERM "${pid}"
		RETVAL=$?
		if [ $RETVAL -eq 0 -a $isSetPidFileByConfig -eq 0 ]; then
				rm -f "$pidFile"
		fi
	else
		echo "Clam AntiVirus Database Updater Daemon is not running"
	fi
}

RestartService () {
	StopService
	StartService
}

UpdateService () {
	if [ -f "$pidFile" ]; then
		pid=`cat "$pidFile"`
	else
		pid=$(GetPID "$processName")
	fi
	if [ "$pid" == "" ]; then
		echo "Clam AntiVirus Database Updater Daemon is not running"
	else
		kill -ALRM $pid
	fi
}

case "$1" in
	update)
		UpdateService
		;;
	*)
		RunService "$1"
		;;
esac
