#!/usr/bin/perl
#
# Domtools Sessions Reporter
#
# Looks at how many domtools are running on the system right now
# according to the domtools.cgi program, and prints the answer.
#
# Usage:  domtoolsstat [-s]
#
# Options:
#	-s     Display summary line only
#
# by Paul Balyoz <pab@domtools.com> <pbalyoz@jammed.com>
# 04/01/1999
#

# Path to the domtools CGI log file
$logfile = "/home/www/lib/domtoolscgi.log";

# Number of lines from log file to display
$lines = 10;

#
# Main
#
use Getopt::Std;
use Time::Local;

&parse_args;
&tail_log  if $lines > 0;
&check_session;
exit 0;

#
# Parse Arguments
#

sub parse_args {
	if (! getopts ('s')) {
		print STDERR "usage: domtoolsstat [-s]\n";
		exit 1;
	}
	$lines = 0  if $opt_s;
}

#
# Check how many other Domtools sessions are running; if over limit, boot user off.
#
sub check_session {
	my($counter) = 0;
	my($pid,@a);

	opendir (D,"/proc") || die "open D";
	foreach (readdir(D)) {
		next if ! /^\d+$/;		# only use file names with all-digits
		$pid = $_;

		if (open (F,"/proc/$pid/cmdline")) {
			$_ = scalar <F>;
			close F;

			@a = split (/\000/,$_);		# nul chars between args
			if ($a[0] =~ /perl/ && $a[1] =~ /domtools\.cgi/) {
				$counter++;		# add them up
			}
		}
	}
	closedir D;

	print "Current domtools web sessions on this server: $counter\n";
}

#
# Show last N lines of the domtools cgi log
#
sub tail_log {
	my(@log,$now,$mon,$mday,$year,$hour,$min,$sec,$diff,$days,$hours,$mins,$secs);
	my($timestr);

	print "Last $lines lines of the domtoolscgi.log:\n";
	$now = time;

	@log=`tail -$lines $logfile`;
	for (@log) {
		@f = split;
		($mon,$mday,$year) = split(/\//,$f[0]);
		$mon--;
		($hour,$min,$sec) = split(/:/,$f[1]);
		$time = timelocal($sec,$min,$hour,$mday,$mon,$year);

		$diff = $now - $time;

		$days = int($diff/(60*60*24));	$diff -= $days*60*60*24;
		$hours = int($diff/(60*60));	$diff -= $hours*60*60;
		$mins = int($diff/60);		$diff -= $mins*60;
		$secs = $diff;			$diff -= $secs;

		print "$_";

		$timestr = "(age ";
		$timestr .= "${days}d " if $days;
		$timestr .= sprintf ("%02d:", $hours) if ($hours || $days);
		$timestr .= sprintf ("%02d:", $mins);
		$timestr .= sprintf ("%02d)", $secs);
		print ' ' x (20-length($timestr)), "$timestr\n";
	}
}
