#!/usr/bin/perl

# http://blog.rot13.org/2008/09/request_tracker_subversion_svnweb_microblogging.html

use strict;
use warnings;

use RT::Client::REST;
use RT::Client::REST::Ticket;

# Request Tracker
my ( $server, $username, $password ) = ( 'https://bugs.example.com/rt', 'rtuser', 'rtpasswd' );
# patternt to recognize RT references in commits log or diff
my $rt_re = qr/\brt\s*#?\s*(\d+)\b/i;
my $svnweb_fmt = 'http://svn.example.com/svnweb/index.cgi/%s/revision/?rev=%d';

die "usage: $0 repo rev\n" unless @ARGV;

my ( $repo, $rev ) = @ARGV;

sub svnlook {
	my $command = shift;
	my $txt = `svnlook $command --revision $rev $repo`;
	chomp( $txt );
	return $txt;
}

my $log = svnlook 'log';
my $diff = svnlook 'diff';

if ( $log =~ $rt_re || $diff =~ $rt_re ) {

	my $id = $1 or die "no id";

	my $rt = RT::Client::REST->new( server => $server );
	$rt->login( username => $username, password => $password );
	my $ticket = RT::Client::REST::Ticket->new( rt => $rt, id => $id );

	my $repo_only = $repo;
	$repo_only =~ s{^.*/([^/]+)$}{$1};

	my $message =
		sprintf($svnweb_fmt,$repo_only, $rev) . "\n" . 
		svnlook('author') . "\t" . svnlook('date') . "\n\n" .
		svnlook('changed --copy-info') . "\n\n" .
		$log
	;

	$ticket->comment( message => $message );
}
