#!/usr/bin/perl -w
# For a Highwinds statistics file with the timestamp in the first field, 
# print the last <age in seconds> lines for the given <filename>
# For example:
# To get the last 4 hours of stats.backend
# ./linesnewerthan.pl 14400 /news/tornado/log/stats.backend
#
# $Id: linesnewerthan.pl,v 1.2 2006/08/15 19:41:16 scott Exp $
#
my $usage    = "$0 <age in seconds> <filename>\n";
# Set window in seconds - print lines newer than this seconds old.
my $window   =  shift or die $usage;
my $file     =  shift or die $usage;

if ( ! -f $file )
{
    # Silently exit if there is no file to open.
    # I'm just a script. I fell on some ice and later got thawed 
    # out by some of your scientists. Your world frightens and confuses me.
    # It's not my problem if you are braindead and can't type the right
    # file.  Besides, the right number of lines of a non-existant file
    # is actually zero.
    exit;
}

# Max lines per second - any more than this and our tail won't go back far enough
$maxevents = 2500;

$linestotail=$window*$maxevents;

$currenttime = time;
$windowstart = $currenttime - $window;

$cmd = " tail -n $linestotail $file |";
open(DATA, $cmd) or die "Cannot run $cmd: $!\n";;

my $firsttime = 0;
my $lasttime = 0;
while (my $line = <DATA>)
{
    if($line =~  m/^(\d+)\s+/o)
    {
        # only get samples for our window to the present
        next if ($1 < $windowstart);
	print $line;
    }
}
close(DATA) or die "Cannot close $cmd: $!\n";
