#!/usr/bin/perl
#

use FCGI;
use Date::Manip;
use FindBin;

my ($logfile, $inode, $pos, $buffer);
$logfile = "/home/bs/www/logs/history/display.history";
$inode = (stat($logfile))[1];
open (FH, "<$logfile");
$pos = tell (FH);
my $count = 0;
my $start = time;
my @h = ();
while(FCGI::accept() >= 0) {
    print ("Content-type: text/html\r\n\r\n",
	   "<html><head><title>Big Sister History</title></head>\n",
	   "<body><h1>Big Sister History</h1>\n",
	   "Request Number: ", ++$count, "<p>\n",
	   "Script Name: ", $FindBin::Script, "<p>\n",
	   "Script Directory: ", $FindBin::RealBin, "<p>\n");
    
    $len = 0 + $ENV{'CONTENT_LENGTH'};
    print "Started at ".localtime($start)."<p>\n";
    print "Timestamp is ".localtime((stat("/home/bs/www/history.fcgi"))[9])."<p>\n";
    if($len == 0) {
        print("No data from standard input.<p>\n");
    } else {
        print("Standard input:<br>\n<pre>\n");
        for($i = 0; $i < $len; $i++) {
            $ch = getc(STDIN);
            if($ch eq "") {
                print("Error: Not enough bytes received ",
                      "on standard input<p>\n");
                last;
	    }
            print($ch);
        }
        print("\n</pre><p>\n");
    }
    
    # Read new data from disk
    seek (FH, $pos, 0);
    my @newlines = <FH>;
    $pos = tell (FH);
    print "Total of ", $#newlines+1, " records read<p>\n";

    # Parse new lines and put them in the history array.
    foreach $l ( @newlines ) {
	$rec = {};
	$l =~ m/([^.]+)\.([^:]+):\s+([a-z]+)->([a-z]+)(\s+\((\d+)\))?\s+(.{24})\s+(.*)/;
	$rec->{host} = $1;
	$rec->{item} = $2;
	$rec->{ostate} = $3;
	$rec->{nstate} = $4;
	if (not defined $6) {
	    $rec->{when} = &UnixDate(&ParseDate($7),"%s");
	} else {
	    $rec->{when} = $6;
	}
	$rec->{dtstamp} = $7;
	$rec->{short} = $8;
	if ($rec->{short} =~ m/\|>(.*)/) {
	    $rec->{text}  = $1;
	    $rec->{short} = substr ($rec->{short}, 0, -length($rec->{text}));
	    $rec->{text} =~ s/\|>/\n/g;
	}
	$rec->{short} =~ s/\|>/\n/g;

	push @h, $rec;
    }
    print "<center><table border=\"1\">\n";
    for ($i=$#h; $i>$#h-100 && $i>0; $i--) {
	print "<tr>";
	print "<td>$h[$i]{host}</td>";
	print "<td>$h[$i]{item}</td>";
	print "<td align=\"center\">$h[$i]{ostate}</td>";
	print "<td align=\"center\">$h[$i]{nstate}</td>";
	print "<td>".localtime($h[$i]{when})."</td>";
	print "<td>$h[$i]{short}</td></tr>\n";
	if ($h[$i]{text} ne "") {
	    print "<tr>";
	    print "<td colspan=\"2\"></td>";
	    print "<td colspan=\"4\"><pre>$h[$i]{text}</pre></td>";
	    print "</tr>\n";
	}
    }
    print "</table></center>\n";
    
    print "<p>All done!</body></html>\n";
    
    # This means the source code is newer and what we just delivered
    # is an old format.  But I think this is nicer than throwing an
    # error to the browser.
    if ((  ((stat($FindBin::RealScript))[9] > $start))
	or ((-l $0) and ((lstat($0))[9] > $start))) {
	exit 0;
    }
}

# Local Variables:
# mode: perl
# End:
