#!/usr/bin/perl -w
#---------------------------------------------------------------------------------------------------------
# view-log.pl - displays the log data in the browser for parmed file
# written by Eric Pence
#---------------------------------------------------------------------------------------------------------
use strict;
use CGI qw(-oldstyle_urls :standard);
use CGI::Carp qw(fatalsToBrowser);
use FileHandle;

my $q = new CGI;

# Get the parmed file
my $filename = $q->param( 'src' ) || '';
my $source_file = "$filename";

# Format title per file name
my $title = '';
if ($filename =~ /boatpage/) {
  $title = "Boatpage visits";
}
elsif ($filename =~ /ipod/) {
  $title = "My Songs visits";
}
elsif ($filename =~ /video/) {
  $title = "Videos played";
}
elsif ($filename =~ /ebooks/) {
  $title = "My eBooks visits";
}
elsif ($filename =~ /error_log/) {
  $title = $filename;
}
else {
  $title = "Webpage visits";
}

print $q->header();
print "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
<head>
<title>$title</title>
</head>
<body>
<pre>";

my $log_file = (new FileHandle $source_file) || die "Can't find $source_file file";
my @log_data;
my @display_data;

# Put all recs in array
while (<$log_file>) {
  push @log_data, $_;
}

# Put title in array to appear at top of display
$title = "<b>$title...</b><br>";
push @log_data, $title;

# Reverse the order of the log data with most recent visits at top
@display_data = reverse @log_data;

# Display the log data
foreach (@display_data) {
print $_;
}

print "</pre>
</body>
</html>";

BEGIN {
# Set up error log file
my $log_file = "error_log.txt";
use CGI::Carp qw(carpout);
open(LOG, ">>$log_file") || die "Unable to append to error log: $!";
carpout(*LOG);
}