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

#----------------------------------------------------------------------------------
# Process a signup form.
#
# Written by David Mutchler, April 2003, modified October 2006, April 2009.
#----------------------------------------------------------------------------------

$folder     = "/afs/rose-hulman.edu/class/csse/faculty-staff/mutchler/advising/public";
$file       = "signup";

$nSlots = 42;

$htmlFile   = "$folder" . "/" . "$file" . ".html";
$sedFile    = "$folder" . "/" . "$file" . ".sed";
$backupFile = "$folder" . "/backup/" . time() . ".html";
$tempFile   = "$folder" . "/temp";

#----------------------------------------------------------------------------------
#   Load some general-purpose subroutines:
#
#----------------------------------------------------------------------------------

require "cgihacks.pl";

#----------------------------------------------------------------------------------
# Prepare for HTML.
#----------------------------------------------------------------------------------

# print <<END_TEXT;
# 
# <HTML>
# END_TEXT

#----------------------------------------------------------------------------------
#   Find values from the form.
#----------------------------------------------------------------------------------

$slotString = "submit";
for ($k = 1; $k <= $nSlots; $k++) {
	$slotString = $slotString . "|id$k";
}

&find_form_args("$slotString");

for ($k = 1; $k <= $nSlots; $k++) {
	eval "\$slots[$k] = \$id$k;";
}

#----------------------------------------------------------------------------------
#   Foreach non-null slot value, make a SED statement that replaces the form input
#   by its current non-null value.
#----------------------------------------------------------------------------------

open(LOG, ">> $sedFile");
for ($k = 1; $k <= $nSlots; $k++) {
	if ($slots[$k] ne "") {
		printf(LOG "s/<input type=text name=id$k size=15 maxlength=40>/\\&nbsp; = \\&nbsp; $slots[$k] \\&nbsp;/\n");
	}
}
close(LOG);

#----------------------------------------------------------------------------------
#   Backup the file, then apply the SED statements to make the new version.
#----------------------------------------------------------------------------------

$action = "/bin/cp $htmlFile $backupFile";
system("$action");

$action = "sed -f $sedFile $htmlFile > $tempFile";
system("$action");

$action = "/bin/mv $tempFile $htmlFile";
system("$action");

#  &print_file("$htmlFile");

#----------------------------------------------------------------------------------
# End the HTML.
#----------------------------------------------------------------------------------

print <<END_TEXT;

You are signed up!

Go BACK and REFRESH (reload) if you want to confirm your time slot.

END_TEXT
