#!/usr/bin/perl

#
#  Read number of local hosts probed and responding from 
#     previously created HTML reports
#  Append new values to log and create plot
#
#

#  Find path to gnu date program
$GNUDATE = defined $ENV{GNUDATE} ? $ENV{GNUDATE} : "date";

$IP_DIR=`pwd`;
chomp $IP_DIR;
$HTML_DIR="$IP_DIR/reports/30min/0traffic/html";
$LOG_NAME="$IP_DIR/reports/30min/graphic/ReportExternal.log";

die "Need arguments\n" unless @ARGV>=3;

($HTML_DIR, $LOG_NAME, $SEARCH) = @ARGV;


#  Last date/time to use (only date/time PREVIOUS to this are calculated)
#  is 1/2 hour ago, because most current report may not be done yet  
($Date,$Hour,$Min) = split(/[ \n]/,`$GNUDATE -d "30 min ago" "+%Y-%m-%d %H %M"`);
# Round min to nearest halfhour
$Min = sprintf ("%02d", 30 * int ($Min/30));

#  Final date to search log for
$LastDateTime = $Date . '-' . $Hour . ":" . $Min;


#
#  Find first and last date/time for updating log
#
#  Get last line from current output file
$StartDateTime="";
if ( open (LOG, $LOG_NAME) ) {
	while (<LOG>) { $line = $_ if (! /^\s*#/ ); }
	close (LOG);
	($StartDateTime) = split (/ /, $line);
}

#  First date/time to use (same as last if no previous log)
if ($StartDateTime eq "") {
	$StartDateTime = `$GNUDATE -d "$Hour:$Min 60 min ago" "+%Y-%m-%d-%H:%M"`;
	chomp $StartDateTime;
}

#
#  Update log
#

#  Loop from $FirstDateTime to $LastDateTime
($CurDate,$CurTime) = ($StartDateTime=~/(\d{4}-\d\d-\d\d)-(\d\d:\d\d)/);
$CurDateTime = $CurDate . "-" . $CurTime;


#  Open log for appending
open (LOG, ">>" . $LOG_NAME) || die "$0: Cannot open $LOG_NAME for appending";


$limit = 0;
while ( $CurDateTime ne $LastDateTime) {

	#  Increase current date/time by 30 min
	($CurDate, $CurTime) = split (/[ \n]/,`$GNUDATE +"%Y-%m-%d %H:%M" -d "$CurDate $CurTime + 30 min"`);
	$CurDateTime = $CurDate . "-" . $CurTime;
	#  Prevent runaway loop (this time stuff can easily go wrong)
	last if (++$limit>1000);

	#  Read Info from 30min HTML file
	$FileName = $HTML_DIR . "/" . $CurDateTime . ".html";
	@f = &ReadFileInfo ($FileName,$SEARCH);
	print LOG $CurDateTime, " ", join(" ",@f), "\n"  if defined(@f) && $f[0] ne "";
}

close (LOG);



exit;

#
#  Find probed and responding values from Local Host for 30min HTML file
#  HTML line format is
#     Traffic:  Total [  n,nnn]  Incoming [ n,nnn]  Outgoing [ n,nnn]
#
sub ReadFileInfo {
	my ($FileName,$SEARCH) = @_;
	my (@f);

	#  Cannot open file, return blank fields
	open (HTML, $FileName) || return @f;

	#  Find LocalHosts line
	@f = ();
	while (<HTML>) {
		if (/^\s*$SEARCH/) {
			@f = /([0-9,]+)/g;
			for (@f) {
				s/,//g;
			}
		last;
		}
	}
	
	close (HTML);

	return @f;
	}
