#!/usr/bin/perl
=head1 NAME

twitterpost.pl - script to post RT ticket details to a twitter account.

=head1 SYNOPSIS

twitterpost.pl < /path/to/message

=head1 DESCRIPTION

Takes an RT notification email, turns it into a string, and uploads it to a
twitter account.  It uses the Subject and RT-Originator headers.  It will strip
the domain from the RT-Originator, and strip the [rt.some.host] blurb from the
subject, giving a string of: <ticketno>|<originator local_part>|<subject>.

=head1 BUGS

There is currently no testing done that the string sent to twitter is within
the required length limits (~160 chars).

There is no help function.

=head1 AUTHOR INFORMATION

Copyright 2007, Michael Howe <michael@michaelhowe.org>.

=cut

use strict;
use warnings;
use Net::Twitter;
use POSIX qw(strftime);

# You can override these in the config file:
our $username;
our $password;
# Set debug to non-zero to log
our $debug = 0;
# Logging is good
our $logfile = "/home/michael/.twitterpost.log";

my $config = "/home/michael/.twitter-worcgtrt.pl";

unless (my $return = do $config) {
    warn "couldn't parse $config: $@"         if $@;
    warn "couldn't do $config: $!"            unless defined $return;
    warn "couldn't run $config"               unless $return;
}


open( LOG, ">>$logfile" ) or die "Ack!  Can't open logfile: $!";

my ( $subject, $originator, $ticketnumber );
debug("Script started");

while (<>) {
    # Blank lines separate the headers from the body.
    last if ( m{^$} );
    # Subject test:
    if ( m{^[Ss]ubject: } ) {
	( $subject ) = m{^Subject: (.*)$};
	debug( "Subject found: $subject" );
    }
    # Originator test:
    if ( m{^RT-Originator: } ) {
	( $originator ) = m{^RT-Originator: (.*)$};
	debug( "Originator found: $originator" );
    }
}
# Sanity tests
unless ( $subject ) {
    debug( "Subject not set" );
    die "Subject not set";
}
unless ( $originator ) {
    debug( "Originator not set" );
    die "Originator not set";
}

# Trim things:
#
( $ticketnumber ) = ( $subject =~ m{\[rt.worc.ox.ac.uk #(\d+)]} );
$subject =~ s{\[rt.worc.ox.ac.uk #\d+] }{};
$originator =~ s{@.*$}{};

# We don't care if this is an autoreply:
#
if ( $subject =~ m{^AutoReply: } ) {
    debug( "This is an autoreply - exiting" );
    exit;
}

# Update twitter:
#
my $updatestring = "$ticketnumber|$originator|$subject";

debug( "Update string: $updatestring" );

my $twit = Net::Twitter->new( username => $username, password => $password );
my $result = $twit->update( $updatestring );

debug( "Update result: " . $result->{id} );
debug("Script ended");

close( LOG );

sub debug {
    my ( $string ) = @_;
    if ( $debug ) {
        my $timestamp = strftime "%a %b %e %H:%M:%S", localtime;
        print LOG "$timestamp: $$: $string\n";
    }
}

=head1 SAMPLE CONFIG

cat ~/.twitter-worcgtrt.pl

    $username = 'MyTwitterUser';
    $password = 'SekritTwitterPassword';
    $logfile = "/home/michael/.twitterpost.log";
    $debug = 1;

=cut

