#!/opt/ActivePerl/bin/perl

use LWP::Simple;
use Alvin::BatchLoad;
use strict 'vars';
use Getopt::Std;
use File::stat;
use LWP::UserAgent;
use Time::Local;
use Date::Format;
use HTTP::Response;
use File::Basename;

package main;

my %opt;

#-------------------------------------------------------------------------

getopts('o:i:d:s:', \%opt);
if ( !defined $opt{'o'} or (!defined $opt{'i'} and !defined $opt{'d'}) or !defined $opt{'s'} ){
    printHelp();
    exit;
}
if ( defined $opt{'i'} and defined $opt{'d'}) {
    printHelp();
    exit;
}

my $inFile = '';
my $inDir = '';
if (defined ($opt{'i'}) ){  
    $inFile= $opt{'i'}; 
    unless (-e $inFile) {
	print "Input file $inFile doesn't exist\n";
	exit;
    }
}
elsif  (defined ($opt{'d'}) ){ 
    $inDir= $opt{'d'};  
    unless (-e $inDir) {
	print "Input dir $inDir doesn't exist\n";
	exit;
    }
}

my $outFile = $opt{'o'};
my ($name, $path, $suffix ) = fileparse( $outFile, "\.[^.]*" );
my $outRaw = join('',$path,$name, ".raw");

open RAW, ">$outRaw" or die $!;
print RAW "start\n";

my $spreadsheet = $opt{'s'};

my($day, $month, $year) = (localtime)[3,4,5];
$month = sprintf '%02d', $month+1;
$day   = sprintf '%02d', $day;
$year  = $year+1900;
my $today = "$month$day$year";

my $data = new Alvin::BatchLoad::DataSource (filename => $spreadsheet, sheetno => 1, header_rowno => 1);

my %listPCs = ();  # these are PC that are on the public PC list
foreach my $rec ($data->records) {
    my $current = [];
    push (@$current, $rec->get('Lib'));
    push (@$current, $rec->get('LocalMachineName'));
    push (@$current, 0);
    push (@$current, 0);
    $listPCs{ $rec->get('IPAddress') } = $current;
}

#printHash(%listPCs); # debug

# Check if it's a directory or a file
if ($inDir ne '') {
    %listPCs = processDirectory($inDir, %listPCs);
}
else {
    %listPCs = processFile($inFile,%listPCs);
}

# Build the output
open OUT, ">$outFile" or die $!;
print OUT "IPAddress, Library, MachineName, # opening page, # logins\n";
foreach my $key ( keys %listPCs )  {
    print OUT "$key, $listPCs{$key}->[0], $listPCs{$key}->[1], $listPCs{$key}->[2],  $listPCs{$key}->[3]\n"; # comma delimited
}

print "Done with script\n";

#--------------- SUBS ---------------------------------------------
sub printHelp() {
    print "usage: publicPC.pl -o <outputFIle> [ -i <logInputFile> | -d <logInputDir>] -s <Spreadsheet>\n\nWhere -o output use <DateRange>.csv\n-i is the log file to analyze\n-d is the directory with the log files to analyze\n<Spreadsheet> is a .xls file with the list of public PC and their ID\n-i & -d are mutually exclusive\n";
}
#---------------------
sub processDirectory {
    my ($localdir, %localPCs) = @_;
    my $file; 

    opendir (DIR, $localdir) or die "can't open directory: $!";

    my @files = map { $localdir . '/' . $_ } grep { !/^\.{1,2}$/ } readdir (DIR);
    foreach (@files)  {
	$file = $_;
	print "$file\n";
	%localPCs = processFile($file,%localPCs);
    }
    closedir DIR;

    return %localPCs;
}
#--------------------
sub processFile {
    my ($file, %localPCs) = @_;
    my $ip;

    open FILE, "<$file" or die $!;
    while (<FILE>) {
	my $line = $_;
	if ($line =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(.*)\/cgi-bin\/(anth|arth|bios|busi|chem|eal|eart|edp|engi|envi|es|igs|law|math|mrc|musi|opto|phys|publ|socw|sseal|sun3)home.cgi HTTP(.*)$/ or  $line =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(.*)\/cgi-bin\/inhouse.cgi HTTP(.*)$/) {  
	    print RAW "$line\n";
	    $ip = $1;
	    if (exists $localPCs{$ip}) { # it's one of the public PCs
		#incremente value of the general page
		my $array = $localPCs{$ip};
		$array->[2] = $array->[2]+1;
		$localPCs{$ip} = $array;
	    }
	    else {
		my $current = [];
		push (@$current,"UNKOWN");
		push (@$current, "UNKNOWN");
		push (@$current, 1);
		push (@$current, 0);
		$listPCs{ $ip } = $current;
	    }
	}
	elsif ($line =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(.*)\/cgi-bin\/(anth|arth|bios|busi|chem|eal|eart|edp|engi|envi|es|igs|law|math|mrc|musi|opto|phys|publ|socw|sseal|sun3)home.cgi\?choice=logon(.*)$/  or $line =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(.*)\/cgi-bin\/inhouse.cgi\?choice=logon(.*)$/ ) {
	    print RAW "$line\n";
	    # count the login *** Confirm with Zed
	    $ip = $1;
	    if (exists $localPCs{$ip}) { # it's one of the public PCs
		#incremente value of the general page
		my $array = $localPCs{$ip};
		$array->[3] = $array->[3]+1;
		$localPCs{$ip} = $array;
	    }
	    else {
		my $current = [];
		push (@$current,"UNKOWN");
		push (@$current, "UNKNOWN");
		push (@$current, 0);
		push (@$current, 1);
		$listPCs{ $ip } = $current;
	    }
	}
    }
    return %localPCs;
}
#------------------------------------
sub printHash1 {
    my %thisHash = @_;
    foreach my $key ( keys %thisHash )  {
	foreach (@{$thisHash{$key}}) {
	    print "$_\n";
	}
    }
}

#------------------------------------
sub printHash {
    my %thisHash = @_;
    foreach my $key ( keys %thisHash )  {
	print "$key is $thisHash{$key}->[0], $thisHash{$key}->[1], $thisHash{$key}->[2], $thisHash{$key}->[3]\n";
    }
}

