#!/usr/bin/perl -w
#
# $Id$
#
# We receive the contents of an email on stdin and our username, password
# and an email address to which to report errors on the command line (yes
# it's not secure but this is LiveJournal not your brokerage account). We
# fix up the formatting and then submit the text as a LiveJournal entry.

use POSIX;
use URI::URL;
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Request::Common;
use HTML::Entities;

my $usage = "Usage: $0 username password email [text on stdin]\n\n" .
    "  username: LiveJournal username\n" .
    "  password: LiveJournal hashed password (look at the source of the\n" .
    "            journal entry submission page and it'll be tucked away\n" .
    "            in a form field\n" .
    "  email: an email address to which to send email in the event of a\n" .
    "         failure submitting the journal entry\n\n";

my $username = shift or die $usage;
my $password = shift or die $usage;
my $email = shift or die $usage;

# compute a nice client version based on the CVS version number
my $clientrev = '$Revision$';
$clientrev =~ s/.*(\d+\.\d+).*/$1/;
my $clientver = "email2lj.pl-$clientrev";

my $past_headers = 0;
my $quoted = 0;
my $new_para = 0;

my $content = "";
my $raw = "";

while (<>) {
    if ($past_headers) {
        # keep a copy of the raw email
        $raw .= $_;
        chomp;

        # if we've hit a blank line, put a couple of newlines into the
        # content
        if (/^\s*$/) {
            if ($quoted) {
                $content .= "</pre>\n";
                $quoted = 0;

            } else {
                # trim the trailing whitespace we left
                $content =~ s/\s*$//;
                # make a note to start a new paragraph when we see new text
                $new_para = 1;
            }

        } elsif (/^-- /) {
            # we've hit the sig, stop processing
            last;

        } else {
            # if this line starts with a >, we may be entering a quoted block
            if (/^>/ && !$quoted) {
                $quoted = 1;
                $new_para = 0;
                # suck up any whitespace prior to this preformatted block
                $content =~ s/\s*$//;
                $content .= "\n<pre>\n";
            }

            # if we're in a pre-formatted block, append things as is, with
            # a newline
            if ($quoted) {
                # check to see if we just ended our quoted block
                if ($_ =~ /^[^>]/) {
                    $content .= "</pre>\n";
                    $quoted = 0;

                } else {
                    $content .= encode_entities($_) ."\n";
                }
            }

            if (!$quoted) {
                if ($new_para) {
                    $content .= "\n<p>\n";
                    $new_para = 0;
                }
                # no whitespace!
                $_ =~ s/^\s*//;
                $_ =~ s/\s*$//;
                # append to the end of the currently accumulating text
		$content .= "$_ ";

		# we used to encode entities in this text, but that
		# prevents us from putting markup in our emails which is
		# undesirable. we do encode entities in "pre-formatted"
		# blocks which catches the > in quoted text
                # $content .= encode_entities($_) . " ";
            }
        }

    } elsif (/^Subject: (.*)$/) {
        $subject = $1;
        chomp($subject);

    } elsif (/^\s*$/) {
        # when we see a blank line, we're past the headers
        $past_headers = 1;
    }
}

# print "$content\n";

# no sendy
# exit 0;

# figure out what time it is
my @now = localtime(time());
my $year = strftime("%Y", @now);
my $mon = strftime("%m", @now);
my $day = strftime("%d", @now);
my $hour = strftime("%H", @now);
my $min = strftime("%M", @now);

# now submit it to LiveJournal
my $ua = LWP::UserAgent->new;
my $url = "http://www.livejournal.com/cgi-bin/log.cgi";
# my $url = "http://dev.samskivert.com:4040/cgi-bin/log.cgi";

my $res = $ua->request(POST "$url",
                       ["mode" => "postevent",
                        "clientversion" => "$clientver",
                        "user" => "$username",
                        "hpassword" => "$password",
                        "year" => "$year",
                        "mon" => "$mon",
                        "day" => "$day",
                        "hour" => "$hour",
                        "min" => "$min",
                        # "security" => "private",
                        "prop_opt_preformatted" => "1",
                        "subject" => "$subject",
                        "event" => "$content",
                        ]);

# make sure the submission went alright
my $failure = 1;
if ($res->is_success) {
    my $content = $res->content;
    # make sure the content contains "success"
    if ($content =~ /success/) {
        $failure = 0;
    }
}

# if not, send email to let me know that submission failed (wankers!)
my $sendmail = "/usr/sbin/sendmail -t";
open(SENDMAIL, "|$sendmail") or die "Cannot open $sendmail: $!\n";
print SENDMAIL "Subject: $subject\n";
print SENDMAIL "To: $email\n";
print SENDMAIL "Content-type: text/plain\n\n";
print SENDMAIL $res->as_string;
if ($failure) {
    print SENDMAIL "-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n";
    print SENDMAIL $raw;
}
close(SENDMAIL);
