#!/usr/bin/perl

# $Log$
# Revision 1.5  2004/12/10 18:51:43  jimmyo
# linux/apt* has been forced to LANG=C, to get predictable output.
#
# Revision 1.4  2004/12/10 10:47:47  jimmyo
# Change name from ${scale} to ${graph_period}, to be more consistent.
#
# Revision 1.3  2004/12/09 22:12:55  jimmyo
# Added "graph_period" option, to make "graph_sums" usable.
#
# Revision 1.2  2004/11/21 00:16:56  jimmyo
# Changed a lot of plugins so they use DERIVE instead of COUNTER.
#
# Revision 1.1  2004/01/02 18:50:00  jimmyo
# Renamed occurrances of lrrd -> munin
#
# Revision 1.1.1.1  2004/01/02 15:18:07  jimmyo
# Import of LRRD CVS tree after renaming to Munin
#
# Revision 1.3  2003/11/07 17:43:16  jimmyo
# Cleanups and log entries
#

#%# family=contrib

$pop{'statefile'} = "/var/db/munin-pluginstate/munin-pop-log.state";
$pos   = undef;
$logons = 0;

$pop{'logfile'} = '/var/log/poplog';

if (-f $pop{'logfile'} . ".0")
{
	$pop{'rotlogfile'} = $pop{'logfile'} . ".0";
}
elsif (-f $pop{'logfile'} . ".1")
{
	$pop{'rotlogfile'} = $pop{'logfile'} . ".1";
}
elsif (-f $pop{'logfile'} . ".01")
{
	$pop{'rotlogfile'} = $pop{'logfile'} . ".01";
}
else
{
	$pop{'rotlogfile'} = $pop{'logfile'} . ".0";
}

(-f "/etc/linpro/rrd-client.conf") and eval `cat /etc/linpro/rrd-client.conf`;

if ( $ARGV[0] and $ARGV[0] eq "config" )
{
	print "graph_title POP logon stats\n";
	print "graph_args --base 1000\n";
	print "graph_vlabel logons / \${graph_period}\n";
	print "logon.label logons\n";
	print "logon.type DERIVE\n";
	print "logon.min 0\n";
	print "logon.draw LINE1\n";
	exit 0;
}

if (! -f $pop{'logfile'} and ! -f $pop{'rotlogfile'})
{
	print "logon.value U\n";
	exit 0;
}

if (-f $pop{'statefile'})
{
	open (IN, $pop{'statefile'}) or exit 4;
	if (<IN> =~ /^(\d+):(\d+):(\d+)/)
	{
		($pos, $logons) = ($1, $2, $3);
	}
	close IN;
}

$startsize = (stat $pop{'logfile'})[7];

if (!defined $pos)
{
	# Initial run.
	$pos = $startsize;
}

if ($startsize < $pos)
{
	# Log rotated
	parseEximfile ($pop{'rotlogfile'}, $pos, (stat $pop{'rotlogfile'})[7]);
	$pos = 0;
}

parsePopfile ($pop{'logfile'}, $pos, $startsize);
$pos = $startsize;

print "logons.value $logons\n";

open (OUT, ">" . $pop{'statefile'}) or exit 4;
print OUT "$pos:$logons\n";
close OUT;

sub parsePopfile 
{    
	my ($fname, $start, $stop) = @_;
	open (LOGFILE, $fname) or exit 3;
	seek (LOGFILE, $start, 0) or exit 2;

	while (tell (LOGFILE) < $stop) 
	{
		my $line =<LOGFILE>;
		chomp ($line);

		if ($line =~ / login by/)
		{
			$logons++;
		}
	}
	close(LOGFILE);    
}


# vim:syntax=perl
