#!/bin/sh
#
# clamsmtp init.d script for Debian
#
# This script is Public Domain.
#
# See also: clamsmtpd.conf(5), clamsmtpd(8)
#
###########################################################################

DESC="ClamSMTP Daemon"
NAME=clamsmtp                                   # Daemon's Name
DAEMON=/usr/sbin/clamsmtpd                      # Binary
CONFFILE=/etc/clamsmtpd.conf                    # Configuration File
SCRIPTNAME=/etc/init.d/${NAME}

CGROUP="clamav"                                 # Group for lib dir

DAEMON_OPTS=""

# Pull in configuration options set in $CONFFILE.
if [ -r ${CONFFILE} ] ; then
eval `sed -e '
# Delete comments
/^#.*/d

# Delete blank lines
/^[[:space:]]*$/d

# Replace first ": " with "="
s/^\([a-zA-Z]*\):[[:space:]]*\(.*\)$/\1\=\2;/
' < ${CONFFILE}`
fi

# Now, use the variables that we care about
PIDFILE=${PidFile:="/var/run/${NAME}/${NAME}.pid"}      # PID File
RUNDIR=`dirname ${PIDFILE}` 
CUSER=${User:=clamav}                                   # clamsmtpd user
SPOOLDIR=${TempDirectory:="/var/spool/${NAME}"}         # Spool Directory

# Override default values
[ -f /etc/defaults/${NAME} ]  && . /etc/defaults/${NAME}

# Make sure permissions of /var/spool/clamsmtp and /var/run/clamsmtp are O.K.
# clamd needs read access to /var/spool/clamsmtp, and clamsmtpd needs write
# access to both.
function fixperms() {
        [ ! ${DO_FIXPERMS} ] && return

	# Don't touch /tmp or /var/tmp
	if [ "x${SPOOLDIR}" != "x/tmp" -a "x${SPOOLDIR}" != "x/var/tmp" ] ; then
		chown ${CUSER}:${CGROUP} ${SPOOLDIR}
		chmod 750 ${SPOOLDIR}
	fi
	
	if [ "x${RUNDIR}" != "x/var/run" ]  ; then 
		chown ${CUSER}:${CGROUP} ${RUNDIR}
		chmod 755 ${RUNDIR}
	fi
}

# Start the daemon
function d_start() {
	# Try to fix the permissions
	fixperms

        start-stop-daemon --start --group "${CGROUP}" \
            --pidfile ${PIDFILE} --quiet --oknodo \
            --exec ${DAEMON} -- ${DAEMON_OPTS}
}

# Stop the daemon
function d_stop() {
        start-stop-daemon --stop --quiet --oknodo --pidfile ${PIDFILE} \
                --exec ${DAEMON}
}

###########################################################################
# Main Body

case ${1} in
    start)
        echo -n "Starting ${DESC}: ${NAME}"
	d_start
	echo "."
        ;;
    stop)
        echo -n "Stopping ${DESC}: ${NAME}"
	d_stop
	echo "."
        ;;
    restart|force-reload)
	echo -n "Restarting ${DESC}: ${NAME}"
        d_stop
	sleep 1
        d_start
	echo "."
        ;;
    *)
        echo "Usage: ${SCRIPTNAME} {start|stop|restart|force-reload}" >&2
	exit 1
        ;;
esac

exit 0
