#!/usr/bin/perl
use Socket;
use CGI qw(:standard escape);

#
# Change to url of the FogBugz server
# examples: "https://mysite.fogbugz.com/", "http://fogbugz.company.com:8080", etc.
#
$BUGZ_URL = "https://fogbugz.my.domain.com:443/";
$IXREPOSITORY="10"; # ixRepository for this repo. (Not required.)

#
# The full path to wget on your system
#
$wget_path = "/usr/bin/wget";

######### That's all you have to do! ###########
#                                              #
#                                              #
#  You shouldn't need to edit anything below   #
#                  here!                       #
################################################

$BUGZ_URL =~ s|/$||;    # Strip trailing slash
$sRepo = $ARGV[2];
$sRepo =~ s|^.*/||g;    # Strip everything but repo name


$logmsg = "";
while (<STDIN>)
{
	$logmsg .= $_;
}

#
# Get BUG number if its there
#
$bugIDString = "";
@rgLine = split("\n", $logmsg);

foreach (@rgLine)
{
        if ($_ =~ /\s*(fog)?bug[zs]*\s*(IDs*)?\s*[#:; ]+((\d+[ ,:;#]*)+)/i)
	{
		$bugIDString .= " " . $3;
	}
}

#
# Read the SVNLOOK CHANGED info from a file specified on the command line
#
print "ARG[1]: $ARGV[1]\n";
open FILE, $ARGV[1] or die "Can't open $ARGV[1] :: $! ::";
while ( <FILE> ) {
	$sChangeInfo .= $_;
} close FILE or die "Can't close $ARGV[1] :: $! ::";

#
# Now, do the submission. We loop through the bug IDs, and submit
# all checked in files against each in turn.
#

@bugIDlist = split("[ ,:;#]+", $bugIDString);

foreach (@bugIDlist)
{
	if (/\d+/)
	{
		$ixBug = int($_);

		print "Adding bug info for Bug ID #$ixBug...\n";

		foreach $sChangeLine (split("\n", $sChangeInfo))
		{

			if ( $sChangeLine =~ /^([AUDRM])\s+(.*)$/ )
			{
			
				$sChangeType = $1;
				$sFile = $2;

				if( $sChangeType =~ "A" )
				{
					$sPrev = 0;
				}
				else
				{
					$sPrev = $ARGV[0] - 1;
				}
				$sNew = $ARGV[0];

				if ( $ixBug > 0 )
				{
					my $url = $BUGZ_URL."/cvsSubmit.asp?ixBug=".$ixBug."&sRepo=".escape($sRepo)."&sFile=".escape($sFile)."&sPrev=".$sPrev."&sNew=".$sNew."&ixRepository=".$IXREPOSITORY;
                                        #print "$wget_path --no-check-certificate '$url' -q -O /dev/null\n";
					system("$wget_path --no-check-certificate '$url' -q -O /dev/null");
				}
			}
		}
	}
}
