# This script serves to generate an HTML file for web execution of your
# favorite ELZA command files. Any variables defined using setvar
# will be converted to HTML form fields.

$HtmlElzaVersion = '0.0.1';
$PathToElza = 'http://localhost/cgi-elza/elza.pl';

$WebEnabled = 0;

print "Hello! This is the HTMLELZA script version $HtmlElzaVersion.\n";
$CmdFile = $ARGV[0];
$HtmFile = $ARGV[1];

if (($CmdFile eq '') || ($HtmFile eq '')) {
	print "The usage is as follows:\n\n";
	print "\t htmlelza COMMANDFILE HTMLFILE\n";
	exit;
}

if (!(-e $CmdFile)) {
	print "!!! File named \'$CmdFile\' does not exist. Exiting...\n";
	exit;
}

$CMDFILE = '<'.$CmdFile;
$HTMFILE = '>'.$HtmFile;

open CMDFILE or die "!!! Unable to open command file: $!\n";
open HTMFILE or die "!!! Unable to open html file: $!\n";

print HTMFILE "<HTML><HEAD>\n";
print HTMFILE "<TITLE>Remote web execution of $CmdFile</TITLE>\n";
print HTMFILE "<\/HEAD><BODY>\n";
print HTMFILE "<FORM ACTION=\"$PathToElza\" METHOD=\"POST\"><P>\n";
print HTMFILE "<TABLE>\n";
while (<CMDFILE>) {

	s/[\r\n]//g;
	s/^[ \t]*//;
	next if(/^\#/);
	@Param = split(' ');
	@ParamAfter = ();

	for $PrmCnt (0..$#Param) {
		$ParamAfter[$PrmCnt] = '';
		for $Index ($PrmCnt..($#Param-1)) {
			$ParamAfter[$PrmCnt] .= "$Param[$Index] ";
		}
		$ParamAfter[$PrmCnt] .= $Param[$#Param];
	}
	if ($_ eq 'var silent = on') {
		print STDOUT "Script is set to run in silent mode.\n";
		print STDOUT "Do not forget to construct HTTP header yourself.\n";
		print HTMFILE "<INPUT TYPE=\"HIDDEN\" NAME=\"silent\" VALUE=\"on\">\n";
	}
	if ( ($Param[0] eq "subst") && ( ($Param[2] eq "=") || ($Param[2] eq "?") ) ) {

		$Variable{$Param[1]} = $ParamAfter[3];

		print "--- Subst: $Param[1] . Default: $Variable{$Param[1]}\n";

		print HTMFILE "<TR>\n";
		print HTMFILE "<TD>\n";
		print HTMFILE "<FONT FACE=\"Arial\">\n";
		print HTMFILE "$Param[1]\n";
		print HTMFILE "<\/FONT>\n";
		print HTMFILE "<\/TD>\n";
		print HTMFILE "<TD>\n";
		print HTMFILE "<FONT FACE=\"Arial\">\n";
		print HTMFILE "<INPUT TYPE=\"TEXT\" NAME=\"$Param[1]\" VALUE=\"$Variable{$Param[1]}\">";
		print HTMFILE "<\/FONT>\n";
		print HTMFILE "<\/TD>\n";
		print HTMFILE "<\/TR>\n";
	}

	if ($_ eq "elza-web-enabled") {
		$WebEnabled = 1;
	}
}

close CMDFILE;

print HTMFILE "<INPUT TYPE=\"SUBMIT\" VALUE=\"RUN\">\n";
print HTMFILE "<INPUT TYPE=\"HIDDEN\" NAME=\"elza-web-script\" VALUE=\"$CmdFile\">\n";
print HTMFILE "<\/TABLE><\/FORM><\/BODY><\/HTML>";
close HTMFILE;

if ($WebEnabled == 0) {
	print "!!! \'$CmdFile\' does not have the elza-web-enabled tag.\n";
}

print STDOUT "Done.\n"
