#!/usr/bin/perl -w

use strict;

use CGI qw(:standard escapHTML);

my $dataDir = '/usr/l/lib/addList/unconfirmed';
my $subscribersFile = '/usr/l/lib/addList/who';
my $thisScript = "http://www.cs.kent.ac.uk/sharingpracticesurvey/addList.pl";
my $finishedHTML = '<p><a href="http://www.sharingpractice.ac.uk/homepage.html">Back to Sharing Practice</a></p>';

my $nonce= param('id');

if (defined $nonce) {
	$nonce =~ s/\///g; # ensure nonce is safe
	my $path = "$dataDir/$nonce";
	if (!open my $inFile, "<$path") {
		print header(), start_html("Problem"), h1("ID wrong or has already been used"),
			p("Sorry, but either you've already used this link or the ID in the URL is wrong in some way."),
			p("If you have already visited this link then don't worry, you're already on the list."),
			p("If not, then maybe you cut and pasted the link incorrectly?"),
			$finishedHTML, end_html();
			exit(0);
	} else {
		my $address = <$inFile>; chomp $address;
		my $escapedAddress = escapeHTML($address);
		close $inFile;
		open my $outFile, ">>$subscribersFile" or &HTMLdie("cannot append to $subscribersFile: $!");
		print $outFile "$address\n";
		close $outFile;
		print header(), start_html("You're signed up"),
			p("Thank you. Email address $escapedAddress will be kept informed of the Share Project Change Stories preliminary results."),
			$finishedHTML,
			end_html();
		unlink $path or p("(not a problem for you, but) cannot delete file $inFile: $!");
	}
	exit(0);
}

my $address = param('address');

if (!defined $address) {
	print header(), start_html("Sign Me Up"), <<END;
<p>Please input your email address here to be added to the list of people
who will be kept informed of the Share Project Change Stories preliminary results.</p>
<p>It is important that you check you've typed it correctly before you press <em>Submit</em>.</p>
END
	print <<END;
<form action="" method="post">
Email address: <input type="text" name="address" /><br />
<input type="submit" value="Submit" />
</form>
END
end_html();
} else {
	my $escapedAddress = escapeHTML($address);
	
	if ($address !~ /.+@.+/) {
			print header(), start_html("Invalid email address"), <<END, end_html();
<h1>Sorry</h1>
<p>$escapedAddress is not a valid email address. Please
<a href="$thisScript">try again</a>.
</p>
END
		exit(0);
	}
	my $nonce = &nonce();
	my $path = "$dataDir/$nonce";
	open my $of, ">$path" or &HTMLdie("open of $path failed: $!");
	print $of "$address\n";
	close $of;
	print header(), start_html("Success"), <<END, end_html();
<h1>One more step</h1>
<p>Thank you. You will shortly receive a message at $escapedAddress.</p>
<p>You need to click on the link in that email to add $address to the
mailing list. <em>Nothing will happen until you do so</em>.</p>
$finishedHTML
END
	mailUser($address, "Action required to be kept informed of the Share Project Change Stories results", <<END);
Hi,

You, or someone pretending to be you, filled in a web form to be kept informed of the
Share Project Change Stories preliminary results.

To complete the process please visit the following link:

$thisScript?id=$nonce

If it wasn't you that initiated this request then don't worry, if you don't visit the above link then
you won't be added to the list.

Thanks,

The Share Project Team
END
}

sub nonce {
	return sprintf("%0x%0x%0x%0x", int rand 0xffffffff, int rand 0xffffffff, int rand 0xffffffff, int rand 0xffffffff);
}

sub HTMLdie {
	my ($err) = @_;
	
		print header(), start_html("Error"), p($err), end_html();
		die($err);
}

sub mailUser {
	my ($to, $subject, $message) = @_;
	
	my $EMAIL_FROM = "cs-syshelp\@kent.ac.uk";
	my $EMAILHEADER_FROM = '"The Share Project" <cs-syshelp@kent.ac.uk>';
	
	delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};    # Make %ENV safer
	$ENV{PATH} = '/bin';

	my ($sendmail_command) = "/usr/lib/sendmail -f $EMAIL_FROM -t";
	#or "/bin/cat" for testing;

	open SENDMAIL, "|$sendmail_command" or die "executing $sendmail_command returned $!";

	print SENDMAIL <<END;
From: $EMAILHEADER_FROM
Subject: $subject
To: $to

$message
END

	close SENDMAIL;

	# And again, for a BCC

	open SENDMAIL, "|$sendmail_command" or die "executing $sendmail_command returned $!";

	print SENDMAIL <<END;
From: $EMAILHEADER_FROM
Subject: BCC: $subject
To: mcw\@kent.ac.uk

To: $to

$message
END

	close SENDMAIL;
}
