#!/usr/local/bin/perl
# 
# install_form.pl
#
# Installs forms and CGIs generated by wondertwin.pl on the local
# server. Should be password protected, so that only registered
# users may install execute the script.

$| = 1;                # output NOT buffered
print "Content-Type:\ttext/html\n\n\n";

$host = $ENV{SERVER_NAME};
$ENV{SCRIPT_NAME} =~ s/([a-zA-Z0-9\.\-_]+)$//;
$program = $1;
$scriptpath = $ENV{SCRIPT_NAME};

## formlib stuff.

if (($ENV{REQUEST_METHOD} eq "POST") &&
   ($ENV{CONTENT_TYPE}   eq "application/x-www-form-urlencoded")){
   
# extract form data - adapted liberally from 
# Brigette Jellinek's formlib.pl

	read(STDIN,$input,$ENV{CONTENT_LENGTH});
	
	    foreach (split("&", $input)) {
        	/(.*)=(.*)/;
            $name = $1;
            $value = $2;
            
            $value =~ s/\+/ /g ;
            $value =~ s/%(..)/pack('c',hex($1))/eg;  
            	# unescape characters
            	
            if (defined $in{$name}) { 
            	$in{$name} .= "#" . $value
            } else { 
            	$in{$name} = $value; 
            }
        }
        
        foreach (keys (%in)) {
        	print "<B>$_:</B>\t$in{$_}<BR>";
        }
        
        $in{TARGET} =~ /(\/)$/;
        
        unless ($1) {
        	$in{TARGET} .= "/";
        }
        
        if (open (TARGET, ">$in{TARGET}/$in{FORM}")) {
		open (SOURCE, "$in{FORM}");
		print TARGET while <SOURCE>;
		close SOURCE;
		close TARGET;
        	print "Form installed successfully<P>";
        } else {
        	print "<B>Trouble installing form: $!</B>";
        	exit(1);
        }
        
        if (chmod 0755, "$in{TARGET}/$in{FORM}") {
        	print "Permissions changed successfully. Document ",
        		  "installation complete!";
        } else {
        
        	print "Problems changing permissions : $!";
        }
	
} else {

	print "<H1>Error - must be called from an HTML Form</H1>",
		  "<B>Using the \"POST\" Method</B><BR>",
		 "Contact your system administrator, at $host, for help.";
		 
}

