#!/usr/bin/perl

# Execute cobbler.csh & process the output

#	Set file permissions to rw-rw----
system("umask 006");

$mailprog = "/usr/bin/mailx";
$webmaster = "blocks";
$siftmaster = "sift";
$lamamaster = "lama";
$tmp = "../tmp";

select(STDOUT); $| = 1;

print "Content-type: text/html\n\n";
print "<TITLE>Blocks Contact</TITLE>\n";
print "<A NAME=top><H1>Blocks Contact</H1></A>";
print "<PRE>";


if ( $ENV{"REQUEST_METHOD"} ne "POST" ) {
   print "This script should be referenced with a METHOD of POST\n";
   exit;
}

read (STDIN, $QUERY_STRING, $ENV{"CONTENT_LENGTH"});
%names = &parse_query($QUERY_STRING);


#	Get the blocks & write it to a file
if ($names{email} eq "") {
   print "<H1>Error</H1> Please enter your email address.<P>\n";
   exit;
}
if ($names{comment} eq "") {
   print "<H1>Error</H1> Please enter your comment.<P>\n";
   exit;
}
$com = "$tmp/$$.com";
open(BLK, ">$com");
print BLK "REMOTE_HOST=$ENV{\"REMOTE_HOST\"}\n";
print BLK "REMOTE_USER=$ENV{\"REMOTE_USER\"}\n";
print BLK "REMOTE_ADDR=$ENV{\"REMOTE_ADDR\"}\n";
print BLK "REMOTE_IDENT=$ENV{\"REMOTE_IDENT\"}\n";
print BLK "email=$names{email}\n";
print BLK "name=$names{name}\n";
print BLK "topic=$names{topic}\n";
print BLK "$names{comment}\n";
close(BLK);

if ($names{topic} eq "si")
{
   system("$mailprog -s \"comment $names{topic}\" -r $names{email} $siftmaster < $com");
}
elsif ($names{topic} eq "la")
{
   system("$mailprog -s \"comment $names{topic}\" -r $names{email} $lamamaster < $com");
}
else
{
   system("$mailprog -s \"comment $names{topic}\" -r $names{email} $webmaster < $com");
}
print "<P>Thank you for your comment.<P>\n";


#-------------------------------------------------------------------------
exit (0);

#-------------------------------------------------------------------------
#
# parameter: a string that is the html QUERY_STRING environment variable
# returns: an associative array of name/value pairs.  The name is the key.
sub parse_query {
  local($query_string) = @_;
  local(%ans, @q, $pair);
#print $query_string;
  # break up into individual name/value lines
  @q = split(/&/, $query_string);

  foreach $pair (@q) {
    # break the name/value pairs up
    # use split rather than regular expressions because the value may have
    #  newlines in it
    split(/=/, $pair, 2);

    # change '+' to ' '
    $_[1] =~ s/\+/ /g;

    # change the escaped characters (has to be after the split on '&' and '=')
    $_[1] =~ s/%(..)/pack("c",&hextodec("$1"))/eg;

    $ans{$_[0]} = $_[1];
  }

  return %ans;
}

# parameter: a hex representation of a number (doesn't need to be a string)
# returns: the decimal representation of the number
sub hextodec {
  unpack("N", pack("H8", substr("0" x 8 . shift, -8)));
}



