#!/usr/local/bin/perl
#
# $Header: /home/vikas/netmgt/nocol/src/perlnocol/RCS/mailmon,v 1.2 1994/11/29 20:52:43 vikas Exp $
#
#
# mailmon -- 
#
#	Look into the mailq on MAILHOSTNAME, and report the number of 
#	messages for each host listed in the config file. Flag if the
#	the number of messages for the various destinations exceeds
#	the marked thresholds.
#	This is a part of the NOCOL monitoring package.
#
# AUTHOR:
#	David M. Meyer 503/346-1747
#	meyer@phloem.uoregon.edu
#	Fri Mar 11 08:46:07 1994
#
#  Modified to add multiple thresholds, etc.:
#	Vikas Aggarwal, vikas@navya.com
#
#

$PROGRAM	=	"/usr/lib/sendmail -bp"; # /usr/local/bin/mailq
$SLEEPMINS	=	30;

require  "nocollib.pl" ;

#
#	depends on nocollib.pl
#

$varname	=	"Mail_Queue";
$varunits	=	"Length";
$debug 		= 	0;		# set to 1 for debugging output
$libdebug 	= 	0;		# set to 1 for nocollib.pl debugging

&nocol_startup;
&readconf;

# first item is localhost's total queue length

foreach $item (@items) {
    local($host, $ipaddr, $wthres,$ethres,$cthres) = split(/\t/,$item);
    &init_event("$host", "$ipaddr", $item);
}

while (1) {
    &dotest;

    foreach $item (@items) {
	local($host, $ipaddr, $wthres,$ethres,$cthres) = split(/\t/,$item);

	($isok, $varthres, $maxsev) = 
	    &calc_status($NTo{$host}, $wthres, $ethres, $cthres);
	&update_event($item, $isok, $NTo{$host}, $maxseverity);
    }
    open(OEVENTS,">$datafile");
    &writeevent(OEVENTS, 0);
    foreach $item (@items)  {
	&writeevent(OEVENTS, $item);
    }
    close(OEVENTS);
    sleep($SLEEPMINS * 60);
}

##
##	dotest
##
#	Count recipients...
#

sub dotest
{
    local ($qsize, $host);
    
    foreach $host (sort keys(%NTo)) {
	$NTo{$host} = 0;
    }
    open(STDERR, ">&STDOUT")		|| die "Can't dup stdout";
    open(PROGRAM, "$PROGRAM  |")	|| die "Can't open $PROGRAM $!";
    
    while (<PROGRAM>) { 
	next if (/^[A-Z]+\d+\s+/); # From: this 
	next if (/Deferred|warning|timeout/);
	if (/Mail Queue/) {	# Mail Queue (152 requests)
	    ($x,$y,$paren,$qsize) = split(/[ \(]/);
	} else {
	    chop;
	    ($user,$host) = split(/[@]/);
	    $host =~ y/A-Z/a-z/; 	# canonicalize lower
	    $host =~ s/>//g;	 	# watch angle brackets
	    $host =~ s/^\s*//; 		# remove leading whitespace
	    $NTo{$host} += 1;
	}
    }
    $NTo{"Local_QLen"} = $qsize;	# entire queue length on localhost
}

##
#
sub readconf {
    open(CONFIG,"< $cfile") || die("Couldn't find $cfile, exiting");
    while(<CONFIG>) {
	chop;
	next if /^$/;				# throw blank lines
	next if /^[\s]*[\#]/;			# throw comments 
	if (/^\s*QLEN\s+(\d+)\s+(\d+)\s+(\d+)\s*/) {
	    push(@items, "Local_QLen\t127.0.0.1\t$1\t$2\t$3");
	    next;
	}
	if (/^\s*(\S+)\s+(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s*/) {
	    push(@items, "$1\t$2\t$3\t$4\t$5");
	    next;
	}
	print STDERR "$me: bad config line- $_\n";
	next;
    }
    close(CONFIG);
}


