#!/usr/bin/env perl

# Execute this script in the directory containing the test-driver 
# scripts (~components/cam/test/system) to loop through the CAM test 
# lists (filenames matching test_*) and create an html file 
# (test_table.html) with the specifics of each test detailed.

use strict;
use warnings;
use diagnostics;

my $fout = 'test_table.html';
my $fmaster = 'input_tests_master';

# Parse the master test list and format the test components for HTML output.
my $masterlist_html = gen_masterlist_html($fmaster);

# Get list of the files containing tests, and do some sorting so the pretag test
# tables are first, then the posttag tables, and finally the miscellaneous tables.
my @test_lists = <tests_*>;

my @pretag_tests = grep /pretag/, @test_lists;
my @posttag_tests = grep /posttag/, @test_lists;
my @misc_tests = grep { !/pretag/ and !/posttag/ } @test_lists;

my @test_lists_sorted = (@pretag_tests, @posttag_tests, @misc_tests);


### Produce the web page here ###

# open file for output
open my $fh_out, '+>', $fout  or die "*** can't open $fout\n";

# output header info
print_header($fh_out);

# Generate a table for each test list.
foreach my $test_list (@test_lists_sorted) {
    print_test_table($masterlist_html, $test_list);
}

# Finish the page
print {$fh_out} "</body></html>\n";

close $fh_out;

#====================================================================================

sub gen_masterlist_html{

    my $fmaster = shift(@_);

    # Parse master test list and store each line as an array of elements (<TD>)
    # in an HTML formatted row of a table.  Then store these arrays in the hash
    # %masterlist_html indexed by the test IDs.  Return a pointer to this hash.

    open my $fh_master, '<', $fmaster  or die "*** can't open $fmaster\n";

    my %masterlist_html;

  LINE: while (my $line = <$fh_master>) {

      my @test_desc = split " ", $line;
      # check for empty lines or for file header line
      if (! defined($test_desc[0]) or $test_desc[0] =~ /<id>/) {next LINE;}

      # Apply HTML table formatting to each component of the test description.
      my @test_desc_html = ();

      foreach my $comp (@test_desc) {

	  # Add HTML links for all the components of the test description
	  # which are files.  This includes the names of the test scripts
	  # and input files for the configure and build-namelist utilities.
	  my $html_str;

	  if ($comp =~ /([-\.\w]+)\+([-\.\w]+)/) {

	      my $str1 = add_html_link($1);
	      my $str2 = add_html_link($2);
	      $html_str = "<TD>$str1+$str2</TD>";
	  }
	  else {
	      my $str1 = add_html_link($comp);
	      $html_str = "<TD>$str1 </TD>";
	  }

	  push @test_desc_html, $html_str ;
      }

      # Add empty cells as necessary so that all descriptions contain
      # 7 cells.  The cells are added in a way that pushes the run length 
      # component to the last column so they all line up.
      my $num_test_comp = scalar(@test_desc_html);
      my $num_empty_cells = 7 - $num_test_comp;
      if ($num_test_comp <= 4) {
	  # When a test description has <= 4 components then there is no
	  # run length component.  So just add the empty cells to the end.
	  push @test_desc_html, ("<TD> </TD>") x $num_empty_cells;
      }
      else {
	  # When a test description has 5 or more components then the last component
	  # is the run length.  In this case add empty cells in front of the last one
	  # until the total array length is 7.
	  splice @test_desc_html, -1, 0, ("<TD> </TD>") x $num_empty_cells;
      }
      
      $masterlist_html{$test_desc[0]} = \@test_desc_html;
  }
    close $fh_master;
    return \%masterlist_html;
}

#====================================================================================

sub print_test_table{

    my $masterlist_html = shift(@_);
    my $test_list       = shift(@_);

    # open file read only
    open my $fh, '<', $test_list  or die "*** can't open $test_list\n";

    print {$fh_out} "<H1>$test_list</H1><TABLE>".
	            '<TR><TH>test# </TH><TH>testid </TH><TH>test script </TH>'.
                    '<TH>build 1</TH><TH>namelist 1</TH><TH>build 2</TH><TH>namelist 2</TH>'.
                    '<TH>run length</TH></TR>';

    # read test IDs in input file
    my @test_ids;
    while (my $line = <$fh>) {
	push @test_ids, split " ", $line;
    }

    my $test_num = 0;
    foreach my $test_id (@test_ids) {

	++$test_num;
	my $test_num_str = sprintf "%03d", $test_num;

	# print a table row for each test
	print {$fh_out} "<TR><TD>$test_num_str</TD> ".
                        "@{$$masterlist_html{$test_id}}</TR>\n";
    }

    print {$fh_out} "</TABLE><BR /><BR />\n";
}

#====================================================================================

sub add_html_link{

    # Add HTML links to the parts of the test description that correspond to a file.

    my $fname = shift(@_);

    my $result = $fname;

    if (-f "./$fname") {
	$result = "<A HREF=\"./$fname\">$fname </A>";
    }
    elsif (-f "./config_files/$fname") {
	$result = "<A HREF=\"./config_files/$fname\">$fname </A>";
    }
    elsif (-f "./nl_files/$fname") {
	$result = "<A HREF=\"./nl_files/$fname\">$fname </A>";
    }
    elsif (-f "../use_cases/$fname.xml") {
	$result = "<A HREF=\"../use_cases/$fname.xml\">$fname </A>";
    }

    return $result;
}

#====================================================================================

sub print_header{

    my $fh = shift(@_);

    print {$fh} <<'END_HERE'
<html>	
<head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<title>CAM Regression Test Tables</title>

<link rel="STYLESHEET" type="text/css" href="gen-test-style.css"/>

</head>
<body>
END_HERE
}
