#!/usr/local/bin/perl5

# That is the path to PERL just above It MUST be first in the script
# The following accepts the data from the form 

require "cgi-lib.pl";
require "thanks.pl";

if ($ENV{'REQUEST_METHOD'} eq 'POST')
{

  read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});

  @pairs = split(/&/, $buffer);

  foreach $pair (@pairs)
  {
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    $FORM{$name} = $value;
  };

	#Output HTML header
  print "Content-type: text/html\n\n";
  print "<HTML>\n";
  print "<HEAD>\n";
  print "<TITLE>Perl script</TITLE>\n";
  print "</HEAD>\n";
  print "<BODY BGCOLOR=#FFFFCC TEXT=#000000>\n";

	#Show command-line params
 	print "<p>Buffer = $buffer</p>";

	#write to test file
	&write_file(@pairs);
	
	#send email
 	#&send_email($FORM);

	#write thank you message from external script
  #&thank_you;
  
  #end HTML
  print "</BODY>\n"; 
  print "</HTML>\n";
}

sub write_file(@pairs) {
	$home = (getpwnam("wfp63998"))[7];
	$filename = "$home/www/temp/testfile.txt";
	print "<p>Home = $home</p>";
	print "<p>Filename = $filename</p>";
	print "<br />";
	
	open(test,">$filename") || die "can't open testfile.txt: $!";
	print test "line 1\n";
	print test "line 2\n";
	print test "line 3\n";

  foreach $pair (@pairs)
  {
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    print test "$name = $value\n";
  };

	close(test);
  
  print "</BODY>\n";
  print "</HTML>\n";
};

sub send_email($FORM) {
	open (MESSAGE,"| /usr/lib/sendmail -t");
  print MESSAGE "To: $FORM{submitaddress}\n";
  print MESSAGE "From: $FORM{name}\n";
  print MESSAGE "Reply-To: $FORM{email}\n";
  print MESSAGE "Subject: Feedback from $FORM{name} at $ENV{'REMOTE_HOST'}\n\n";
  print MESSAGE "The user wrote:\n\n";
  print MESSAGE "$FORM{feedback}\n";
  close (MESSAGE);
};


