#!/usr/bin/perl -w
use strict;
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);

my $htmlHead = "../nitsloch1-gpl/scenarios/head";
my $htmlFoot = "../nitsloch1-gpl/scenarios/foot";
my $scenarioDir = "../nitsloch1-gpl/scenarios/";
my $scenarioExt = "zip";
my $infoExt = "txt";

my @scenarioFiles = glob $scenarioDir."*.".$scenarioExt;

sub process_scenarios {
  print "<table>\n";
  print "<colgroup><col width=\"300px\"></col>";
  print "<col width=\"200px\"></col>";
  print "<col width=\"100px\"></col>";
  print "<col width=\"100px\"></col></colgroup>\n";
  print "<tr><th>Scenario Name</th>";
  print "<th>Author</th>";
  print "<th>Age (Days)</th>";
  print "<th>Size (KB)</th></tr>\n";
  foreach (@_){
    my $file = $_;
    my $basename = $_;
    my $size = -s $_;
    my $classA = "gray";
    my $classB = "blue";
    $size /= 1024;
    $size = int $size;
    my $age = -M $_;
    $age = int $age;
    $age++;
    if ($age <= 5) {
      $classA = "red";
      $classB = "red";
    }
    $basename=~s/.*\/(.*)\.$scenarioExt/$1/;
    my $info = "${basename}.${infoExt}";
    my ($author, $name);
    open INFO, "<$scenarioDir$info";
    my $i = 0;
    while (<INFO>) {
      $i++;
      if ($i == 1) {
	chomp;
	$author = $_;
      } elsif ($i == 2) {
	chomp;
	$name = $_;
      }
    }
    close INFO;
    print "<tr><td class=\"${classA}\"><a href=\"${file}\">${name}</a></td>";
    print "<td class=\"${classB}\">${author}</td>";
    print "<td class=\"${classA}\">${age}</td>";
    print "<td class=\"${classB}\">${size} KB</td></tr>\n";
  }
  print "</table>\n";
}

sub main {
  print "Content-type: text/html\n\n";
  open HEAD, "<$htmlHead";
  while (<HEAD>) {
    print;
  }
  close HEAD;
  process_scenarios @scenarioFiles;
  open FOOT, "<$htmlFoot";
  while (<FOOT>) {
    print;
  }
  close FOOT;
}

&main;
