#!/usr/bin/perl
#
# Create an issue in an external bug tracker
#
# As an example we're using Fog Creek FogBugz but this 
# script can be adapted to any external issue tracker.
#

# ***********************************************************
# You should edit these variables to reflect your environment:

# URL to the Code Collaborator Server
$CCOLLAB_URL = "http://localhost:8080";

# Login of Code Collaborator User who will mark the Defect as external
$CCOLLAB_USER = "admin";

# Password of Code Collaborator User who will mark Defect as external
$CCOLLAB_PASSWORD = "";

# URL to the FogBugz server
$FOGBUGZ_URL = "http://bugs";

# Email of user to use to create Case in to FogBugz
$FOGBUGZ_USER_EMAIL = "person\@yourcompany.com";

# Password of user to use to create Case in to FogBugz
$FOGBUGZ_USER_PASSWORD = "yourpasswordhere";

#***********************************************************

#
# usage: mirror-defect.pl <review-id> <defect-id> <defect-title>
#

use LWP::Simple;
use URI::Escape;

# read parameters from command-line
$reviewId = $ARGV[0];
$defectId = $ARGV[1];
$defectTitle = $ARGV[2];

# logon to FogBugz
my $response = get("$FOGBUGZ_URL/api.php?cmd=logon&email=$FOGBUGZ_USER_EMAIL&password=$FOGBUGZ_USER_PASSWORD");

# extract authentication token
$response =~ /<token>(?:<!\[CDATA\[)?([^\]]+)(?:\]\]>)?<\/token>/;
my $token = $1;

# create new Case
$defectTitle = uri_escape($defectTitle);
$description = uri_escape("Defect D$defectId mirrored from Code Collaborator Review $reviewId ($CCOLLAB_URL/index.jsp?page=ReviewDisplay&reviewid=$reviewId)");
$response = get("$FOGBUGZ_URL/api.php?token=$token&cmd=new&sTitle=$defectTitle&sEvent=$description");

# extract Case id
$response =~ /ixBug="(\d+)"/;
my $case = $1;

print("Mirrored Defect D$defectId in FogBugz as Case $case\n");

# log off from FogBugz (invalidate authentication token)
$response = get("$FOGBUGZ_URL/api.php?token=$token&cmd=logoff");

# mark Defect as "external" in Code Collaborator
$ccollabOptions = "--url $CCOLLAB_URL";
$ccollabOptions .= " --user $CCOLLAB_USER";
$ccollabOptions .= " --password \"$CCOLLAB_PASSWORD\"";
$ccollabOptions .= " --quiet --non-interactive"; 
system("ccollab $CCOLLAB_OPTIONS admin review defect mark-external $defectId \"Case $case\""); 