#!/usr/bin/perl -w
use strict;

use Getopt::Std;
use RallyClock;
use Data::Dumper;

use vars qw(%opts $usermap $user);

# RallyClock server
our $rallyclock_uri = 'http://go.rallyclock.com';

# This is the RallyClock billing (user-code) code id you want to update timers for.
# This value wil usually look like xxx.xxx.
# If you have an active timer for this billing code it will be updated.
# If you don't have an active timer for this project nothing will happen.
our $billing_code = '';

# this is a map of the SVN user to RallyClock username and API key
$usermap = {
  # svn username => {Rallyclock username and api key}
  jpowers => {user=>'jay', key=>'XXXXXXX'},
  dpfeffer => {user=>'doug', key=>'XXXXXXXXX'},
};

getopts("a:c:r:m:f:h", \%opts);

if ($opts{h} or !($opts{a} and $opts{c})) {

print <<HELPMSG;
rallyclock-update-timer.pl: A perl script to send svn commit message to rallyclock active timer
--
This is intended to be launched by the SVN post-commit hook.

  -h  : help, this message
  -a  : author of SVN change (required)
  -c  : changeset/revision number (required)
  -r  : repository path
  -f  : files changes
  -m  : message body

HELPMSG
exit;

}

#check that the user is valid
if (exists $usermap->{$opts{a}}) {
  $user = $usermap->{$opts{a}}
} else {
  print "\nERROR: User '".$opts{a}. "' does not appear in the usermap\n";
  exit;
}

#Fork this process 
my $pid = fork();

if (not defined($pid)) {
  die "Resources not available!";
} elsif ($pid == 0) {
  # This is the child
   update_timer();
   exit;
}

sub update_timer { 

  my $rc = RallyClock->new(uri=>$rallyclock_uri, 
    user=>$user->{'user'}, key=>$user->{'key'}, Debug=>1
  );

  if (my $timer = $rc->active_timer()) {
    # if the billing_codes match try to update the timer
    if ($timer->{'user-code'} eq $billing_code) {
      my $message = '('.$opts{c}.'): '.$opts{m}.' ';
      $rc->timer($timer->{'id'}->{'content'}, $message);
    } else {
      return;
    }
  } else {
    return
  }
}
