#!/usr/bin/perl -w

#	Copyright (C) 2009-2010 Nathan Gibbs nathan@cmpublishers.com
#
#	This program is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License version 1
#	as published by the Free Software Foundation.

eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}' if 0;

use strict;
use Getopt::Std;
use Sys::Hostname;
use vars qw($opt_d $opt_m);
my $usage="virusevent [-d] [-m message] virus [virus]\n";
#  -d for debug
getopts ("m:d") || die $usage;
my $DEBUG = $opt_d || "";
my $msg = $opt_m || "Found VIRUS";
my @Virus;
my $tmp;
my $VF;
my $VR;
# Set these to suit your environment.
my $mail = "/usr/bin/mail";
my $To = "user\@example.com";

# Test for Clamd Environment
if ( $ENV{"CLAM_VIRUSEVENT_VIRUSNAME"} ) {
	$VR = $ENV{"CLAM_VIRUSEVENT_VIRUSNAME"};
}else{
	$VR = "";
}
if ( $ENV{"CLAM_VIRUSEVENT_FILENAME"} ) {
	$VF = $ENV{"CLAM_VIRUSEVENT_FILENAME"};
}else{
	$VF = "";
}

if(@ARGV) {
	# Viruses are handed to us on cmd line.
	@Virus = @ARGV;
	if (scalar ( @ARGV ) == 1 ) {
		$tmp = $Virus[0];
		&alert ($tmp);
	}else{
		foreach $tmp (@Virus) {
			&alert ($tmp);
		}
	}
}else{
	# Nothing handed to us.
	if ( $VF && $VR ) {
		# Get it from the clamd Environment
		if ( $VF eq "stream" ) {
			&alert ("$VR");
		}else{
			&alert ("$VR in file $VF");
		}
	}
}

sub alert {
	my ( $tmp ) = @_;
	my ( $subject, $lmsg );
	if ( $DEBUG ) {
		print "$tmp\n";
	}
	my $Host = "Host " . &hostname;
	if ( $tmp=~m/(ClamAV-Test-File)/ || $tmp=~m/(Eicar-Test-Signature)/ ) {
		if ( $DEBUG ) {
			$subject = "VIRUS TEST: $Host $tmp\n";
			$lmsg = "$Host Debuging message.";
		}else{
			$lmsg = "";
		}
	}else{
		$subject = "VIRUS ALERT: $Host $tmp\n";
		$lmsg = "$msg $tmp";
	}
	if ( $lmsg ne "") {
		$lmsg = "$Host\n$lmsg";
		system ( "echo \"$lmsg\"|$mail -s \"$subject\" $To" );
	}
}