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

use strict;
use CGI ();
use Mail::Internet ();

  use vars qw($q);
  use lib qw(.); 
  use HTML qw($q); # HTML.pm is in the same dir as script.pl
  $q = CGI->new;

# avoid mailx etc.
$ENV{'PERL_MAILERS'} = "mail:/donotuse:sendmail:/usr/sbin/sendmail";
$ENV{'MAILADDRESS'} = 'webmaster@mail.lns.cornell.edu';

my $to = "chris237\@gmail.com";

my $query = new CGI;

my @fields = ( 'Name', 'Email', 'Phone', 'InstName', 'InstStreet', 'InstCity', 'InstState', 'InstZip', 'Lodging', 'ContactName', 'ContactPhone' );

print $query->header();

HTML::printmyheader();

if (!$query->param('Name')) {
    print "<h1>Missing a name.</h1>\nPress the back button and please provide your name.\n";
} else {
    my @body;

    for my $field (@fields) {
	push @body, sprintf("%-15s %s\n", $field.":", $query->param($field))
	    if $query->param($field);
    }

    push @body, sprintf("\nsubmitted from: %s (%s)\n", 
			$ENV{'REMOTE_ADDR'},
			$ENV{'REMOTE_HOST'} || "no reverse DNS"
		       );

    my $msg = Mail::Internet->new(Body => \@body);
    my $head = $msg->head;
    
    $head->replace('Subject', $query->param('Subject'));
    $head->replace('From', $query->param('Email'));
    $head->replace('To', $to);

    if ($msg->smtpsend(To => $to)) {
	# remove the remote host info
	pop @body;

	print qq(
		 <p>Thank you for registering!<br>
                   A confirmation email will be sent to your address.</p>
		 <pre>);
	print @body;
    } else {
	print qq(<h1>Script Error</h1>
		 <p>Please send mail to
		 <a href="mailto:service\@mail.lns.cornell.edu">
		 service\@mail.lns.cornell.edu</a></p>);
    }

# Send confirmation email
    if($query->param('Name')){
    	my @body2;

    	for my $field (@fields) {
	    push @body2, sprintf("%-10s %s\n", $field, $query->param($field))
	    	if $query->param($field);
    	}

	push @body2, sprintf("\nsubmitted from: %s (%s)\n", 
			$ENV{'REMOTE_ADDR'},
			$ENV{'REMOTE_HOST'} || "no reverse DNS"
		       );
	
	my $msg2 = Mail::Internet->new(Body => \@body2);	
	my $head2 = $msg2->head;	
        $head2->replace('Subject', $query->param('Subject'));
        $head2->replace('From', $query->param('Email'));
        $head2->replace('To', $query->param('Email'));	

	if ($msg2->smtpsend(To => $query->param('Email'))) {}
    }
}

HTML::printmytrailer();