#!/usr/local/bin/perl -w

use CGI qw(:standard);


package main; # I am _not_ anal.

# this script generates an index (placing it inside the template file) from a directory.
# all files to be indexed must end with the letters 'html', 'pdf', or 'xls'

print "Content-type: text/html", "\n\n";
print "\n";

#get the query string...
my $specified_path = $ENV{'QUERY_STRING'};
unless(defined $specified_path) {       #this is for execution of the script on the command line.
	$specified_path= "/courses/chem100";
}
my $target_path = $specified_path;

my $cgi_to_html_path = "";  	#this corrects the path so that the query string acts as if
		                        #it were pointing to a file in the system's directory.

my $cgi_depth = "";  #this should have one ../ for each level the CGI directory is burried.
my $server_location = "http://depts.washington.edu/chemcrs/";
my $page_location = $server_location . "cgi-bin/page.cgi?";

my $template_path = "templates/";                    #the location of the template directory relative to cgi-bin
my $template_name = "general_template.htmlt";        #the name of the template file in the template directory.
my $template_file = $template_path . $template_name; #the location of the template
my $readme_file = "readme.txt";                      #this is put at the top of the index.

my $correction_directory = "";                       #this should be the path out of the directory
                                                     #of the CGI program (cgi-bin).

my $target_correction = $cgi_to_html_path . $target_path;  #corrects the path to any images.  Not used in the
                                                           #index since the content of the image contains no
                                                           #urls or images at the moment.

if(! ($target_correction =~ s#(.*/)(.*)#$1#gi)) {          
	$target_correction = "";
}
my $template_correction = $cgi_depth . $template_path;     #corrects URLs in the template.  This is used now
if(! ($template_correction =~ s#(.*/)(.*)#$1#gi)) {
	$template_correction = "";
}

# ---------------------------------------------------------------------------------------
# read in the directory.
my @files = <$cgi_to_html_path$target_path/*>;

# ----------- add the readme file --------------------------------------------------------

if (open (README, "$cgi_to_html_path$target_path$readme_file")) {
	while($_ = <README>) {
		$content .= $_
	}
}

# ----------- add the Course Information -------------------------------------------------
# all files starting with the words 'syllabus' or 'info' are indexed here.
# files must end in either html or pdf

@temp_files = @files;

@prefix = ("syllabus");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix, "true");
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    $content .= "<H4>Course Information</H4>\n";
    $content .= $file_list;
}
#course info is listed under syllabus and the word 'info' is striped from the front of the name.
@prefix = ("info");
my $file_list = listFiles(\@files, \@prefix, \@suffix, "false");
$content .= $file_list;

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

# ----------- add the Handouts ----------------------------------------------------------
# all files that start with the phrase 'handout' are indexed here.
#

@prefix = ("handout", "handouts");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix);
unless($file_list eq "") {
    $content .= "<H4>Course Handouts</H4>\n";
    $content .= $file_list;
}


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

# ----------- add the Sample Exams ------------------------------------------------------
# all files that start with the phrase 'sample_exam' are indexed here.
#

@prefix = ("sample_exam");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix);
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    $content .= "<H4>Sample Exams</H4>\n";
    $content .= $file_list;
}
# ---------------------------------------------------------------------------------------

# ----------- add the Sample Exams Answers __--------------------------------------------
# all files that start with the phrase 'exam_answers' are indexed here.
#
@prefix = ("exam_answers");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix);
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    $content .= "<H4>Sample Exam Answers</H4>\n";
    $content .= $file_list;
}
# ---------------------------------------------------------------------------------------

# ----------- add the Problem Sets ------------------------------------------------------
# all files that start with the phrase 'problem_set' or 'homework' are indexed here.
#
@prefix = ("problem_set", "homework");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix, "true");
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    $content .= "<H4>Problem Sets</H4>\n";
    $content .= $file_list;
}

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

# ----------- add the Answers to Problem Sets -------------------------------------------
# all files that start with the phrase 'problem_answers' are indexed here.
#
@temp_files = @files;
$wrote_title = "false";

@prefix = ("problem_answers", "homework_answers");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix);

# don't ask for log in if there are no homework answers to show.
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    if( (defined &param('pass')) && (&param('pass') eq 'abigsecret')) {
	$content .= "<H4>Problem Set Answers - <I>Logged In</I></H4>\n";
	$content .= $file_list;
    } else {
        $content .= "<H4>Problem Set Answers - <I>Please Log In</I></H4>\n";
        $content .= "<FORM ACTION=\"new_index.cgi?$specified_path\" METHOD=\"POST\">";
        $content .= "Answer to problem sets are only available to students, faculty,\n";
        $content .= "staff of the University of Washington.  You must enter a password\n";
        $content .= "below to access this information.  If you do not know your password\n";
        $content .= "ask your TA or instructor.<BR>\n";
        $content .= "<B>Password:</B> <INPUT TYPE=\"password\" name=\"pass\">";
        $content .= "<INPUT TYPE=\"Submit\" value=\"Login\">";
        $content .= "</FORM>";
    }
}

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

# ----------- add the Lecture Notes -----------------------------------------------------
# all files starting with the words 'syllabus' or 'info' are indexed here.

@prefix = ("notes");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix);
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    $content .= "<H4>Lecture Notes</H4>\n";
    $content .= $file_list;
}

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

# ----------- add the Excel Templates ---------------------------------------------------
# all files starting with the words 'template' as a direct link to the file

@prefix = ("template");
@suffix = ("xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix);
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    $content .= "<H4>Excel Templates</H4>\n";
    $content .= $file_list;
}

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

# ----------- add the prelabs -----------------------------------------------------------
# all files that start with the phrase 'prelab' are indexed here.
#
@prefix = ("prelab");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix, "true");
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    $content .= "<H4>Prelabs</H4>\n";
    $content .= $file_list;
}

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


# ----------- add the lab handouts ------------------------------------------------------
# all files that start with the phrase 'prelab' are indexed here.
#
@prefix = ("lab_handout");
@suffix = ("html", "pdf", "xls");

my $file_list = listFiles(\@files, \@prefix, \@suffix);
unless($file_list eq "") {  #this prevents the header from being printed if there is no files here.
    $content .= "<H4>Laboratory Handouts</H4>\n";
    $content .= $file_list;
}

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

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

#if we can't find the template file, print an error message and exit.
#note that the file below must point to the template file we are going to use.
unless (open (TEMPLATE, "$cgi_to_html_path$template_file")) {

	print "<html>\n";
	print "<head>\n";
	print "<title>Template Not Found</title>\n";
	print "</head>\n";
	print "<body>\n";

	print "<H1>Template Not Found</H1>";
	print "Sorry, there was a misconfiguration in the server.  Please contact the webmaster";
	print " at <a href=\"mailto:webmaster\@chem.washington.edu\">";
	print "webmaster\@chem.washington.edu</a>\n.  Please mention how you got to this page";
	print " and where you were trying to go";
	print "\n";
	print "</body>\n";
	print "</html>\n";
	return;
}

#read in the template files -------------------------------------------------------------
while($_ = <TEMPLATE>) {
	$template .= $_
}
close(TEMPLATE);

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

#get the title to go in the page.

	$title = $specified_path;
	$title =~ s#.*/(.*)/$#$1#gio; #try to extract the name from the directory path
	$title =~ s#.*(\d*).*#$1#gio;  #try to extract the course number;
	$title = "$title Index";

# -------------------------------------------------------------------------------------
# this updates all hrefs and srcs with the target correction for the template file
# except those which start with
# http:// which are absolute addresses.

$template =~ s#(
					(<.*?)
					(href|src|background|HREF|SRC|BACKGROUND)
					(\=")
					(?!(http://|HTTP://))
				)
			#$1$template_correction#xgio;
# -------------------------------------------------------------------------------------
			
$title = $target_path;
$title =~ s#.*/(\w*)/#$1#;

$title .= " Index";

unless(-d "$cgi_to_html_path$target_path") {

	$title = "Course Not Found";
	$content = "Sorry, the course you requested was not found\n";
	$content .= "on the server.  This may be because your instructor has not yet posted any information\n";
	$content .= "or you may not have typed the address correctly.\n";
	$content .= "If this error persists, please contact\n";
	$content .= "the course instructor";
}

# -------------------------------------------------------------------------------------
#namespace is a hash containing the variables that are to be replaced.
%namespace = (
  TITLE, $title,
  CONTENT, $content,
);




# insert the body and title into the template 
#check any word that is all uppercase and starts with $ against namespace.
$template =~ s/\$([A-Z]+)/
					$value = $namespace{$1}/ge;

# -------------------------------------------------------------------------------------
# output the template.

print $template;

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

#
sub listFiles {
    my $return_string;
    
    my $file_array_ref = $_[0];
    my $prefix_ref = $_[1];
    my $suffix_ref = $_[2];
    my $save_prefix = $_[3];
    
    my @file_array = @$file_array_ref;

    my $prefix_regx = join('|', @$prefix_ref);
    my $suffix_regx = join('|', @$suffix_ref);

    @temp_files = @files;

    for($i = 0; $files[$i]; $i++) {

	$temp_files[$i] =~ s#.*/(.*)#$1#gi;
	$location = "$page_location$specified_path$temp_files[$i]";
	
		if($temp_files[$i] =~ m#^($prefix_regx).*\.($suffix_regx)$#) {
			#if it is a .pdf file, the file should be served as it
			$location = "$server_location$specified_path/$temp_files[$i]";
		} 
	
		
		if($temp_files[$i] =~ m#^($prefix_regx).*\.($suffix_regx)$#) {
			if($save_prefix eq "true") {
				$temp_files[$i] =~ s#(.*)\.($suffix_regx)#$1#gi;
			} else {
				$temp_files[$i] =~ s#($prefix_regx)_(.*)\.($suffix_regx)#$2#gi;
			
			}
			$return_string .= "<A href=\"$location\">$temp_files[$i]</A><BR>\n";
		}
    }
    return $return_string;
}

