#!/usr/bin/perl -w
# This code is a part of Slash, and is released under the GPL.
# Copyright 1997-2001 by Open Source Development Network. See README
# and COPYING for more information, or see http://slashcode.com/.
# $Id: tailslash,v 1.3.2.1 2001/06/05 11:51:44 pudge Exp $

use strict;
use File::Basename;
use Getopt::Std;
use Slash;
use Slash::DB;
use Slash::Utility;

(my $VERSION) = ' $Revision: 1.3.2.1 $ ' =~ /\$Revision:\s+([^\s]+)/;
my $PROGNAME = basename($0);

my %opts;
# Remember to doublecheck these match usage()!
usage('Options used incorrectly') unless getopts('hvu:y:', \%opts);
usage() if ($opts{'h'} || !keys %opts);
version() if $opts{'v'};
$opts{'u'} ||= 'slash';

{
	my $slashdb = Slash::DB->new($opts{'u'});

	if ($opts{'y'} eq "today") {
		my($total, $today, $hour, $count);
		my $pages = $slashdb->pagesServed();

		print "| Hour  | Total for hour | Total for day | Per second\n";

		for (@$pages) {
			my($cnt, $time) = @$_;
			my $h = timeCalc($time, '%d_%H');
			my $d = timeCalc($time, '%d');

			$hour = $h unless defined $hour;

			if ($h eq $hour) { # don't print
				$count += $cnt;
			} else { # print, then reset $cnt to current hour
				printf("| %s | %-7d\t | %-9d\t | %.2f\n",
					$hour, $count, $total, $count/3600);
				$count = $cnt;
			}

			$total = 0 unless $today == $d;
			$today = $d;
			$total += $cnt;
			$hour = $h;
		}
		print "$total pages served so far today.\n";

		exit;
	}

	my $id = $slashdb->maxAccessLog();
	my $total;
	my $starttime = time;

	while (1) {
		sleep 3;
		my $info = $slashdb->getAccessLogInfo($id);

		my $sec = time - $starttime;
		$total += @$info;

		print "$sec\t| " . @$info . "\t| " . sprintf("%.2f", $total/$sec) . "\n"
			if $opts{'y'} eq "sec";
		for (@$info) {
			my($host_addr, $uid, $op, $dat, $ts, $id) = @$_;
			my $w = "$ts $host_addr ($uid)";
			$w .= "\t" if length $w < 24;
			$w .= "\t$op";
			$w .= "\t" if length($op) < 8;
			$w .= "\t$dat\n";
			print $w unless $opts{'y'} eq "sec";
			$id = $id if $id > $id;
		}
	}
}

sub usage {
	print "*** $_[0]\n" if $_[0];
	# Remember to doublecheck these match getopts()!
	print <<EOT;

Usage: $PROGNAME [OPTIONS] ... [FILES]

SHORT PROGRAM DESCRIPTION

Main options:
	-h	Help (this message)
	-v	Version
	-u	Virtual user (default is "slash")
	-y	Period of time ("today" or "sec"); if "today", ...

EOT
	exit;
}

sub version {
	print <<EOT;

$PROGNAME $VERSION

This code is a part of Slash, and is released under the GPL.
Copyright 1997-2001 by Open Source Development Network. See README
and COPYING for more information, or see http://slashcode.com/.

EOT
	exit;
}

__END__
