#! /bin/bash

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

PROGNAME=`basename $0`
#PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`
PROGPATH=/usr/lib/nagios/plugins
REVISION=`echo '$Revision: 1.0 $' | sed -e 's/[^0-9.]//g'`
CONF=/etc/clamav/clam_test.conf

. $PROGPATH/utils.sh


print_usage() {
	echo "Usage: $PROGNAME"
}

print_help() {
	print_revision $PROGNAME $REVISION
	echo ""
	print_usage
	echo ""
	echo "This plugin checks ClamAV status."
	echo ""
	support
	exit 0
}

case "$1" in
	--help)
		print_help
		exit 0
		;;
	-h)
		print_help
		exit 0
		;;
	--version)
   	print_revision $PROGNAME $REVISION
		exit 0
		;;
	-V)
		print_revision $PROGNAME $REVISION
		exit 0
		;;
	*)
		if [ ! -f $CONF ]; then
			echo $CONF missing
			exit -1
		fi

		source $CONF

		if [ ! -x $CLAMSCAN ]; then
			echo $CLAMSCAN not executable
			exit -1
		fi

		NB_ERR_FRESH=`/usr/bin/tail $CLAM_LOG | /bin/grep -E '(ERROR|WARNING)' | grep -cvE '(Your ClamAV installation is OUTDATED|Local version: .* Recommended version: .*)'`
		$CLAMSCAN --quiet $VIRUS_TEST
		CLAM_RESULT=$?
		$CLAMSCAN --quiet $VIRUS_NONE
		CLAM_RESULT2=$?

		if test "$1" = "-v" -o "$1" = "--verbose"; then
			/usr/bin/tail $CLAM_LOG | /bin/grep -E '(ERROR|WARNING)'
			$CLAMSCAN $VIRUS_NONE
			$CLAMSCAN $VIRUS_TEST
		fi
		if test ${NB_ERR_FRESH} -ne 0; then
			echo "WARNING - CLAMAV logs have ${NB_ERR_FRESH} error or warning"
			exit 1
		fi
		if test ${CLAM_RESULT} -ne 1 ; then
			echo "CLAMAV CRITICAL - Cannot detect Virus"
			exit 2
		elif test ${CLAM_RESULT2} -ne 0 ; then
			echo "CLAMAV CRITICAL - Detect Virus but it's not"
			exit 2
		else
			echo CLAMAV OK
			exit 0
		fi
		;;
esac
