#!/usr/bin/perl
$home = "/usr/users/luyer/snmp/perl";
require "$home/lib/config.pl";
require "$home/lib/webgraph.pl";
chdir $config'outdirs{'ServerD'}."/".week();
$| = 1;
$mtime = &GetYYMMDD(time);
webgraph'CgiStart();
$Selected{$in{'Sample'}} = "SELECTED" if (defined($in{'Sample'}));
if(defined($in{'Query'})) {
	$in{'Query'} = undisp($in{'Query'});
	$Selected{$in{'Query'}} = "SELECTED";
}
@files = (keys %config'servers,keys %config'numbers);
$in{'Query'} = "9".$in{'Query'} if($in{'Query'} =~ /^3/);
$file = $in{'Query'};
$in{'Sample'} = "1 Hour" if(!defined($in{'Sample'}));
$Sample = 60 if ($in{'Sample'} eq "1 Hour");
$Sample = 120 if ($in{'Sample'} eq "2 Hours");
$Sample = 180 if ($in{'Sample'} eq "3 Hours");
$Sample = 360 if ($in{'Sample'} eq "6 Hours");
$Sample = 720 if ($in{'Sample'} eq "12 Hours");
$Sample = 1440 if ($in{'Sample'} eq "1 Day");
$Sample = 2880 if ($in{'Sample'} eq "2 Days");
$Sample = 4320 if ($in{'Sample'} eq "3 Days");
$Sample = 5760 if ($in{'Sample'} eq "4 Days");
$Sample = 10080 if ($in{'Sample'} eq "1 Week");
# REFRESH causes an IMS get of 60 * black.gif, etc.
#$seconds = $Sample ? $Sample : 60;
$PageWidth = 360;
print "Content-Type: text/html\n\n";
print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n";
print "<HTML><HEAD>\n";
print "<TITLE>UWA Terminal Server Statistics</TITLE>\n";
print "<LINK REV=made HREF=\"mailto:luyer\@ucs.uwa.edu.au\">\n";
#print "<META HTTP-EQUIV=REFRESH CONTENT=$seconds>\n";
print "</HEAD>\n";
print "<BODY BGCOLOR=\"#ABCDEF\">\n";
print "<H2 ALIGN=CENTER><STRONG>UWA Terminal Server Statistics Page\n";
print "</STRONG><BR>$mtime</H2>\n";
#print "<P ALIGN=CENTER>This page is automatically refreshed every $seconds seconds.\n";
if (defined($in{'Query'})) {
	&ProcessFile($file);
} else {
	$Selected{"1 Hour"} = 1;
	$Selected{"$config'default{'ServerD'}"} = 1;
	$Sample = 60;
	$file = $config'default{"ServerD"};
	&ProcessFile($file,1);
}
print "<P>You might also be interested in Alan's \n";
print "<A HREF=\"http://samos.ucs.uwa.edu.au/info/dialins.html\">individual dialin line list</A>.\n";
print "<P>This page was produced by <A HREF=\"/\">typhaon</A>.\n";
print "<ADDRESS>--<BR><A HREF=\"http://www.ucc.gu.uwa.edu.au/~luyer\">David Luyer</A>\n";
print "<A HREF=\"mailto:luyer\@ucs.uwa.edu.au\">&lt;luyer\@ucs.uwa.edu.au&gt;</A>\n";
print "</ADDRESS>\n";
print "<A HREF=\"http://www.uwa.edu.au/cgi-bin/validate\"><IMG ALIGN=RIGHT SRC=\"http://www.uwa.edu.au/cwis/valid32.gif\" ALT=\"HTML 3.2 Checked!\" BORDER=0></A>\n";
print "</BODY></HTML>\n";

sub	ProcessFile {
	local($file = $_[0],$SAMPLE = $_[1],$i,%tot,%inp);
	close(IN);
	$us=0;
	if($config'servers{$file}) {
		open(IN,"-|") || exec "/usr/bin/tail","-$Sample",$file;
		while(<IN>) {
			($time,@data) = split /\|/;
			$time += 8*3600;
			if(!$btime) {
				$btime = $time;
				$tot{"poll"} = 1;
			} else {
				$tot{"poll"}++;
			}
			$inp{"$time"} = 1;
			for($i=0;$i<$config'pports{$file};) {
				if($data[$i/32]&(1<<($i%32))) {
					$inp{"$time"}++;
					$us++;
					$i++;
					$i = ($i<10) ? " $i" : $i;
					$tot{"$file $i"}++;
				} else {
					$i++;
				}
			}
		}
		$ftime = $time;
		close IN;
	} else {
		$config'ports{$file} = 0;
		$first = 1;
		for $i (@{$config'numbers{$file}}) {
			$config'ports{$file}++;
			$anx = ${$config'annex}{substr($i,0,1)};
			$i = substr($i,1);
			if(!$ana{$anx}) {
				open(IN,"-|") || exec "/usr/bin/tail","-$Sample",$anx;
				while(<IN>) {
					($time,@data) = split /\|/;
					$time += 8*3600;
					if(!$btime) {
						$btime = $time;
						$tot{"poll"} = 1;
						$inp{"$time"} = 1;
						$ana{$anx}{"$time"} = [@data];
					} elsif($first) {
						$tot{"poll"}++;
						$inp{"$time"} = 1;
						$ana{$anx}{"$time"} = [@data];
					} elsif($time >= $btime && $time <= $ftime) {
						$ana{$anx}{"$time"} = [@data];
					}
				}
				if($first) {
					$ftime = $time;
					$first = 0;
					$Sample ++;
				}
				close IN;
			}
			$data = $ana{$anx};
			$i = ($i<10)?" $i":$i;
			for $time (keys %{$data}) {
				if(@{@{$data}{$time}}[($i-1)/32]&(1<<(($i-1)%32))) {
					$inp{"$time"}++;
					$tot{"$anx $i"}++;
					$us++;
				}
			}
		}
	}
	undef $f;
	undef $time;
	undef $oldday;
	if(!$config'ports{$file}) {
	  $config'ports{$file} = 100;
	  print "<P>Port count unknown, setting to 100\n";
	}
	if(!$tot{"poll"}) {
	  print "<P>No data\n";
	  $tot{"poll"} = 1;
	  print STDERR "No data! Number or file $file!\n";
	}
	$us /= ($tot{"poll"}*$config'ports{$file})/100;
	$t = $x = 0;
	for $time (sort bynumber keys %inp) {
		$t++;
		$hour = $time - ($time % 3600);
		$day = $time - ($time % (3600*24));
		if(defined($oldday)) {
			if($oldday != $day) {
				$x++;
			} elsif($oldhour != $hour) {
				$x++;
			}
		}
		$oldday = $day;
		$oldhour = $hour;
	}
	undef $oldday;
	if($t ne $tot{"poll"}) {
		print "<P>Database error detected: aborting.";
		exit;
	}
	if($t > 60) {
		if ($x < 12) {
			$t = 60;
		} elsif ($x >= 47 && $x <= 96) {
			$t = $x;
		} elsif ($t > 144) {
			$t = 144;
		}
	}
	if($x > $t) {
		$x = $t;
	}
	if($t == 0) {
		print "<P>Data error.  Aborting.";
		exit;
	}
	$W = int($PageWidth/$t);
	print "<DIV ALIGN=CENTER><TABLE BORDER=1>\n";
	printf "<TR><TH VALIGN=MIDDLE><STRONG>Utilization (%%) %s</STRONG><BR><EM>Average Usage: %2.1f%% (of $config'ports{$file} ports)</EM></TH>\n",disp($file),$us;
	print "<TR><TD VALIGN=BOTTOM>\n";
	$cum = $this = $cnt = 0;
	$n = 1;
	for $time (sort bynumber keys %inp) {
		$this++;
		$cnt++;
		$cum += $inp{$time} - 1;
		if($tot{"poll"}==$t || $cnt>=($n*$tot{"poll"})/$t) {
			$hour = $time - ($time % 3600);
			$day = $time - ($time % (3600*24));
			$E = int(100 * ($cum/$this) / $config'ports{$file});
			$cum = $this = 0;
			$n++;
			if (defined($oldday)) {
				if ($oldday != $day) {
					print "<IMG SRC=\"/pixels/blue.gif\" HEIGHT=100 WIDTH=1 ALIGN=bottom ALT=\"\">";
				} elsif ($oldhour != $hour) {
					print "<IMG SRC=\"/pixels/red.gif\" HEIGHT=100 WIDTH=1 ALIGN=bottom ALT=\"\">";
				}
			}
			if($n != 2) {
				print "<IMG SRC=\"/pixels/black.gif\" HEIGHT=$E WIDTH=$W ALIGN=bottom ALT=\"\">";
			} else {
				print "<IMG SRC=\"/pixels/black.gif\" HEIGHT=$E WIDTH=$W ALIGN=bottom ALT=\"[main graphic]\">";
			}
			$oldhour = $hour;
			$oldday = $day;
		}
	}
	undef $cnt;
	undef $cum;
	undef $this;
	undef $n;
	undef $E;
	undef $time;
	print "</TABLE></DIV>\n";
	print "<P ALIGN=CENTER>From ",GetYYMMDD($btime - 8*3600)," to ",GetYYMMDD($ftime - 8*3600),"\n";
	print "<P ALIGN=CENTER>(note: a blue line represents a new day; a red line represents a new hour)\n";
	&ServerForm;
	return if (defined($SAMPLE));
	return if ($in{'Type'} eq "Graph Only");
	return if (!defined(%tot));
	print "<DIV ALIGN=CENTER><TABLE BORDER=1>\n";
	print "<TR><TH><IMG SRC=\"/pixels/red.gif\" HEIGHT=1 WIDTH=100 ALT=\"\"></TH><TH><STRONG>Usage %</STRONG></TH><TH><STRONG>Port</STRONG></TH>";
	if($tot{"poll"} != 0) {
		for $port (sort keys %tot) {
			if($port ne "poll") {
				$E = 100 * $tot{$port} / $tot{"poll"};
				$DE = int($E);
				printf "<TR><TD><IMG SRC=\"/pixels/blue.gif\" HEIGHT=17 WIDTH=$DE ALIGN=LEFT ALT=\"\"></TD><TD>%2.1f%%</TD><TD>$port</TD>\n",$E;
			}
		}
	}
	print "</TABLE></DIV>\n";
}
sub     GetYYMMDD {
        local(@tmp,$sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst,$time);
        $time = $_[0];
        ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($time);
        @tmp = ($mday,$mon+1,$year,$hour,$min);
        return(sprintf("%.2d\-%.2d\-19%.2d %.2d\:%.2d",@tmp));
}

sub	bynumber { $a <=> $b }
sub	ServerForm {
	for $str ("1 Hour", "2 Hours", "3 Hours", "6 Hours", "12 Hours",
		  "1 Day", "2 Days", "3 Days", "4 Days", "1 Week") {
		if(!exists($Selected{$str})) {
			$Selected{$str} = "OPTION";
		} else {
			$Selected{$str} = "OPTION SELECTED";
		}
	}
	print <<EOF;
<P><FORM METHOD="GET" ACTION="$ENV{'SCRIPT_NAME'}">
<TABLE><TR><TD ROWSPAN=3><SELECT NAME="Sample">
<$Selected{"1 Hour"}>1 Hour
<$Selected{"2 Hours"}>2 Hours
<$Selected{"3 Hours"}>3 Hours
<$Selected{"6 Hours"}>6 Hours
<$Selected{"12 Hours"}>12 Hours
<$Selected{"1 Day"}>1 Day
<$Selected{"2 Days"}>2 Days
<$Selected{"3 Days"}>3 Days
<$Selected{"4 Days"}>4 Days
<$Selected{"1 Week"}>1 Week
</SELECT>
<TD ROWSPAN=2><SELECT NAME=Query SIZE=4>
EOF
	foreach $file(@files) {
		if (defined($Selected{$file})) {
			print("<OPTION SELECTED>",disp($file),"\n");
		}
	}
	foreach $file(@files) {
		if (!defined($Selected{$file})) {
			print("<OPTION>",disp($file),"\n");
		}
	}
	print <<EOF;
</SELECT></TD>
<TD><INPUT TYPE=SUBMIT NAME=Type VALUE="Graph & Ports"></TD>
<TR><TD><INPUT TYPE=SUBMIT NAME=Type VALUE="Graph Only"></TD>
</TABLE></FORM>
EOF
}

sub disp {
  local($nm) = @_;
  $nm =~ s/ /-/;
  if($config'comment{$nm}) {
    return "$nm ($config'comment{$nm})";
  } else {
    return $nm;
  }
}

sub undisp {
  local($nm) = @_;
  if ($nm =~ /^([a-zA-Z\-0-9\/]+)/) {
    $nm = $1;
  }
  $nm =~ s/-/ /;
  return $nm;
}  
