#!/usr/bin/perl -w

# send-postcard.pl

use strict;
use diagnostics;
use CGI;  # available from http://www.perl.com/CPAN/
use Mysql;

# This should match the mail program on your system.
my $mailprog = '/usr/lib/sendmail';

# Create an instance of CGI
my $query = new CGI;

# Send an appropriate MIME header
print $query->header("text/html");

# Grab values from some 
my $sender_name = $query->param("sender_name");
my $sender_email = $query->param("sender_email");
my $recipient_name = $query->param("recipient_name");
my $recipient_email = $query->param("recipient_email");
my $graphic_id = $query->param("graphic_id");
my $postcard_text = $query->param("postcard_text");

# Get the lowest digits from the time of day, which should serve
# as a relatively unique ID number
my $id_number = time & 0xFFFFF & $$;

# Connect via Unix sockets to the database on this server
my $dbh = Mysql->connect("localhost", "test");

# Build up our SQL command
my $command = "";
$command = "insert into postcards ";
$command .= "  (id_number, sender_name, sender_email, recipient_name, ";
$command .= "   recipient_email, graphic_id, postcard_text) ";
$command .= "values ";
$command .= "  ($id_number, \"$sender_name\", \"$sender_email\", ";
$command .= "   \"$recipient_name\", \"$recipient_email\", ";
$command .= "   \"$graphic_id\", \"$postcard_text\") ";

# Uncomment for debugging
# print "<P>SQL command: <B>$command</B></P>\n";

# Send the query
my $sth = $dbh->query($command);

# Make sure that $sth returned reasonably
die "Error with command <"$command<"" unless (defined $sth);

# ------------------------------------------------------------
# Send a postcard notification via e-mail
open (MAIL, "|$mailprog $recipient_email") || die "Can't open $mailprog!\n";

# Headers in the mail message
print MAIL "From: $sender_email\n";
print MAIL "To: $recipient_email\n";
print MAIL "Reply-to: $sender_email ($sender_name)\n";
print MAIL "Subject: Postcard waiting for you\n\n";

# Body of the mail message
print MAIL "A postcard from $sender_name ($sender_email) is waiting for you\n";
print MAIL "at the URL \n\n";
print MAIL "http://www.oursitename.com/cgi-bin/show-postcard.pl?$id_number\n";
close (MAIL);

# ------------------------------------------------------------
# Begin the HTML output
print $query->start_html(-title => "Thanks!");

print "<P>Thanks for sending a postcard!</P>\n";

# End the HTML
print $query->end_html;

exit;

