#!/usr/bin/perl -w
# https://wiki.innerweb.novell.com/index.php/Bugzilla_XML-RPC_API
#http://www.bugzilla.org/docs/tip/en/html/api/Bugzilla/WebService/Bug.html#add_comment
#http://bzr.mozilla.org/bmo/3.6/annotate/head:/contrib/bz_webservice_demo.pl
# /suse/holgi/testopia/2.3/
use strict;
use SOAP::Transport::HTTP;  # Need for Basic Authorization subroutine
use XMLRPC::Lite;           # From the SOAP::Lite Module
use JSON::XS;
 
our ($username,$password);
eval(`/bin/cat $ENV{HOME}/.bugzillarc`);

my $bugid=shift(@ARGV); #685877; 
my @sr=@ARGV;
my $debug=0;
$|=1;

sub srurl(@)
{
	return join("",map {"https://build.opensuse.org/request/show/$_\n"} @_);
}


$bugid=~s/(\w+)#//;
my $tracker=$1||"bnc";

my $issuetrackers=decode_json(`cat issuetrackers.json`);
my $trackerurl=$issuetrackers->{lc($tracker)};
if($trackerurl) {
	print "$trackerurl$bugid was mentioned in: \n".srurl(@sr)."\n";
}

exit 0 unless $tracker eq "bnc";

my $proxy = XMLRPC::Lite->proxy("https://apibugzilla.novell.com/tr_xmlrpc.cgi");
#my $proxy = XMLRPC::Lite->proxy("https://bugzilla.innerwebtest.novell.com/tr_xmlrpc.cgi"); # broken
#my $proxy = XMLRPC::Lite->proxy("http://apibugzillastage.provo.novell.com/tr_xmlrpc.cgi"); # broken

# Result is a hash map
#my $soapresult = $proxy->call('TestPlan.get', 3470);
#my $soapresult = $proxy->call('Bug.get', {ids=>[685002]});
my $soapresult = $proxy->call('Bug.comments', {ids=>[$bugid]});
#Bug.add_comment, {id => $bug_id, comment => $comment, private => $private, work_time => $work_time}

# Error checking
die_on_fault($soapresult);

# dump response:
my $coder = JSON::XS->new->ascii->pretty->allow_nonref->allow_blessed->convert_blessed;
# Print each key/value pair 
my $bugjson=$coder->encode ($soapresult->{_content}->[4]);
#foreach (keys(%$soapresult)) { 
#	my $r=$$soapresult{$_};
#	print "$_: $r\n"; 
#	print $coder->encode ($r);
#}

#$/=undef; #my $comment = <STDIN>;#"This is comment 2 for testing the other account\nwith two lines\nor more.";

my @sr2;
# drop linked SRs:
foreach my $sr (@sr) {
	next if $bugjson=~m/request\/show\/$sr\b/;
	push(@sr2, $sr); # keep sr
}

exit unless @sr2;

my $comment="This is an autogenerated message for OBS integration:\nThis bug ($bugid) was mentioned in\n".srurl(@sr2)."\n";
#print "https://bugzilla.novell.com/show_bug.cgi?id=$bugid\n".$comment;

if(!$debug) {
	my $soapresult2 = $proxy->call('Bug.add_comment', {id => $bugid, comment => $comment});
	die_on_fault($soapresult2);
}
#print "====\n",$coder->encode ($soapresult2->{_content});

print "OK\n";

# Add the following subroutine to submit a userid/password for basic authorization
sub SOAP::Transport::HTTP::Client::get_basic_credentials 
{ 
	return $username => $password;
}

sub die_on_fault 
{
	my $soapresult = shift;

	if ($soapresult->fault) 
	{
		die $soapresult->faultcode . ' ' . $soapresult->faultstring;
	}
}

