#!/bin/sh
#
# $NetBSD: amavisd.sh,v 1.3 2010/12/24 07:19:35 kefren Exp $
#
# PROVIDE: amavisd
# REQUIRE: DAEMON
# BEFORE:  mail
#
#
# You will need to set some variables in /etc/rc.conf to start amavisd:
#
# amavisd=YES
#
# The following variables are optional:
#
#	amavisd_user="vscan"	# user to run amavisd as
#	amavisd_group="vscan"	# ${amavisd_user}'s group
#	amavisd_dirs="/var/amavis"	# directories that should be created
#					# before starting amavisd

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

name="amavisd"
rcvar=$name
command="/usr/pkg/sbin/${name}"
command_interpreter="/usr/pkg/bin/perl"
pidfile="/var/amavis/amavisd.pid"
required_files="/usr/pkg/etc/${name}.conf"
: ${amavisd_user="vscan"}
: ${amavisd_group="vscan"}
: ${amavisd_dirs="/var/amavis /var/amavis/db /var/amavis/tmp /var/virusmails"}

start_precmd="amavisd_prestart"
stop_cmd="amavisd_stop"

amavisd_prestart()
{
	/bin/rm -f /var/amavis/amavisd.sock
	for dir in ${amavisd_dirs}; do
		/bin/mkdir -p $dir
		/usr/sbin/chown ${amavisd_user}:${amavisd_group} $dir
		/bin/chmod 0750 $dir
	done
}

# Net::Server breaks rc.subr's techniques for detecting whether the
# process running at a certain PID is actually the process we wish to
# stop.  Just unconditionally send SIGTERM to the PID instead.
#
amavisd_stop()
{
	echo "Stopping ${name}."
	if [ -f ${pidfile} ]; then
		pid=`/usr/bin/head -1 ${pidfile}`
		doit="/usr/bin/su -m ${amavisd_user} -c \"kill ${pid}\""
		if ! eval $doit && [ -z "$rc_force" ]; then
			return 1
		fi
		wait_for_pids $pid
	fi
	/bin/rm -f ${pidfile}
	for dir in ${amavisd_dirs}; do
		/bin/rmdir -p $dir 2>/dev/null || true
	done
}

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} ${amavisd_flags} ${command_args}
fi
