#!/bin/sh

# description: start/stop Clam AntiVirus database update daemon
#
# default: S/K40 0/K40 1/K40 2/S87

# License: CDDL 1.0 - see http://www.opensource.org/licenses/CDDL-1.0
# Copyright (c) 2006-2011 Jens Elkner. All rights reserved.

# $Id$

# default clamfresh configuration file
CONF=/etc/clamav/freshclam.conf

NAME="Clam AntiVirus signature database update daemon"
SPATH=@CLIENT_BASEDIR@/bin
DAEMON="freshclam"

. /lib/svc/share/smf_include.sh

function getSvcProp {
	typeset -n RES=$2
	typeset VAL="${ svcprop -p "$1" ${SMF_FMRI} 2>/dev/null ; }"
	[[ ${VAL} != '""' && -n ${VAL} ]] && RES="${VAL}" || RES="$3"
}

[[ -z ${SMF_FMRI} ]] && SMF_FMRI='clamfresh:default'

case "$1" in
start)
	getSvcProp config/file CONF "${CONF}"
	if [[ ! -r ${CONF} ]]; then
		print -u2 "Unable to read config file '${CONF}'."
		exit ${SMF_EXIT_ERR_CONFIG}
	fi

	print "Starting ${NAME} ..."
	if ! ${SPATH}/${DAEMON} -d --config-file="${CONF}" ; then
		print -u2 "'${SPATH}/${DAEMON} -d --config-file=${CONF}' failed."
		exit ${SMF_EXIT_ERR_FATAL}
	fi
	print 'done.'
	;;
stop|update|log)
	integer CID
	getSvcProp restarter/contract CID 0
	if (( ! CID )); then
		print -u2 "${SMF_FMRI} is not running."
	else
		# NOTE: update does not reload the config - just updates DBs
		SIG='USR1'
		[[ $1 == 'stop' ]] && SIG='TERM' || { [[ $1 == 'log' ]] && SIG='HUP' ; }
		print "Sending SIG${SIG} to contract ${CID} ..."
		smf_kill_contract "${CID}" "${SIG}"
		print 'done.'
	fi
	;;
*)
	print "Usage: $0 { start | stop | update | log }"
	exit ${SMF_EXIT_ERR_NOSMF}
	;;
esac
exit ${SMF_EXIT_OK}
