#!/bin/sh
#
# $NetBSD: clamd.sh,v 1.1.1.1 2010/12/24 07:11:05 kefren Exp $
#
# clamd does anti-virus checking.
#
# PROVIDE: clamd
# REQUIRE: DAEMON
# BEFORE: mail local
# KEYWORD: shutdown

if [ -f /etc/rc.subr ]; then
	. /etc/rc.subr
fi

name="clamd"
rcvar=$name
command="/usr/pkg/sbin/${name}"
scan_command="/usr/pkg/bin/clamdscan"
required_files="/usr/pkg/etc/clamd.conf"
start_precmd="clamd_precmd"
stop_cmd="clamd_stopcmd"

if [ -f "${required_files}" ]; then
	pidfile_=`/usr/bin/awk '/^#/ {next}; /^PidFile[ 	]/ {r = $2};
			END {print r}' ${required_files}`
	if [ -n "${pidfile_}" ]; then
		pidfile=${pidfile_}
	fi
	logfile=`/usr/bin/awk 'BEGIN {r = "/tmp/clamd.log"};
			/^#/ {next}; /^LogFile[ 	]/ {r = $2};
			END {print r}' ${required_files}`
	socket=`/usr/bin/awk 'BEGIN {r = "/tmp/clamd"};
			/^#/ {next}; /^LocalSocket[ 	]/ {r = $2};
			END {print r}' ${required_files}`
	clamd_user=`/usr/bin/awk 'BEGIN {r = "clamav"};
			/^#/ {next}; /^User[ 	]/ {r = $2};
			END {print r}' ${required_files}`
fi

clamd_precmd()
{
	/bin/rm -f ${socket}
	if [ -n "${logfile}" ]; then
    		/usr/bin/touch ${logfile}
    		/usr/sbin/chown ${clamd_user} ${logfile}
	fi
	if [ -n "${pidfile}" ]; then
    		/usr/bin/touch ${pidfile}
    		/usr/sbin/chown ${clamd_user} ${pidfile}
	fi
}

clamd_stopcmd()
{
	# Workaround bug when clamd is built against pth by send TERM to
	# clamd, then forcing it to start a worker thread that exits.
	# This forces the main thread to awaken and realize that it's
	# supposed to shutdown.
	#
        echo "Stopping ${name}."
        doit="/usr/bin/su -m ${clamd_user} -c \"kill -TERM $rc_pid\""
        if ! eval $doit && [ -z "$rc_force" ]; then
                return 1
        fi
        ${scan_command} --quiet ${scan_command} 2>/dev/null
        wait_for_pids $rc_pid
}

if [ -f /etc/rc.subr -a -f /etc/rc.conf \
     -a -d /etc/rc.d -a -f /etc/rc.d/DAEMON ]; then
	load_rc_config $name
	run_rc_command "$1"
else
	echo -n " ${name}"
	eval ${start_precmd}
	${command} ${clamd_flags} ${command_args}
fi
