#!/usr/local/bin/php
<?php

/*
 * Gaby Vanhegan <gaby@vanhegan.net> 2004-12-03
 *
 * Munge logs from spamd (pf) and put them into an rrd file
 * for handling by rrdtool.
 */

// Sample log line:
// Dec  2 16:52:33 trim spamd[32669]: 218.71.255.117: disconnected after 12 seconds. lists: china

function log_msg ( $input ) {
	$msg	= trim( $input );
	$lines	= explode( "\n", $msg );
	foreach ( $lines as $line ) {
		$when	= date( "Y-m-d H:i:s" );
		print "[$when] $line\n";
		}
	}

// Where are we?  Where do RRD's go?  Where do the logs come from?
$BASE		= "/home/gaby/prel/rrd";
$BASE_RRD	= "/var/symon/rrds/localhost";
$LOG		= "/var/log/spamd.0";
$LOG_TMP	= tempnam( "/tmp", "rrd-rblsmtpd" );

// No log?  Nothing to do.
if ( !( file_exists( $LOG ) ) ) { exit; }

// Move the log file out of active duty
copy( $LOG, $LOG_TMP );
$fh		= fopen( $LOG_TMP, "r" );

// Information about our lists
$lists		= array();

// Now going through our log data...
while( $line = fgets( $fh ) ) {

	$hit	= false;

	// Single up the whitespace in the line
	$hit	= preg_match( "/^(.+) (\d+:\d+:\d+) trim spamd\[.+\]: \d+.\d+.\d+\.\d+: disconnected after (\d+) seconds. lists: (.+)$/", $line, $matches );

	// If it matches a line
	if ( $hit ) {

		// Normalise the time to the nearest half hour (1800 seconds)
		$the_date	= $matches[1] . " " . date( "Y" );
		$the_hour	= $matches[2];

		// Ensure we're not working in the future here
		$the_time	= strtotime( $the_date . " " . $the_hour );
		if ( $the_time > time() ) { $the_time = time(); }

		// Lock down to the nearest 1800 seconds, or half hour.
		$the_time	= ( $the_time - ( $the_time % 1800 ) );

		// How long were they waiting?
		$wait_time	= $matches[3];

		// Which lists?
		$the_lists	= explode( " ", $matches[4] );

		// Increment the number of blocks and the wait time for each list
		foreach ( $the_lists as $list ) {
			$lists[ $list ][ $the_time ][ "blocks" ]	+= 1;
			$lists[ $list ][ $the_time ][ "time" ]		+= $wait_time;
			}

		// Also do this for the global all list
		$lists[ "all" ][ $the_time ][ "blocks" ]	+= 1;
		$lists[ "all" ][ $the_time ][ "time" ]		+= $wait_time;
		}

	}

fclose( $fh );
unlink( $LOG_TMP );

foreach ( $lists as $list => $data ) {

	$rrd_file	= "spamd_" . $list . ".rrd";
	if ( $list == "all" ) { $rrd_file = "spamd.rrd"; }

	$command_base	= "/usr/local/bin/rrdtool update $BASE_RRD/$rrd_file";
	$command		= $command_base;
	$count			= 1;

	// Sort out data in ascending date please
	ksort( $data );

	foreach ( $data as $time => $values ) {

		$count++;

		$blocks		= $values[ "blocks" ];
		$wait		= $values[ "time" ];

		if ( ( $count % 30 ) < 1 ) {
			//log_msg( $command );
			print trim( shell_exec( $command ) );
			$command	= $command_base;
			}

		$command	.= " $time:$blocks:$wait";
		}

	//log_msg( $command );
	print trim( shell_exec( $command ) );
	}
?>
