#!/usr/bin/perl -w
######################################################################################
# AddBugzillaVersion.pl
# Adds a new version to all products in a Bugzilla database
# Version 1.01
# Written by: Yuval Baror
######################################################################################

### Packages #########################################################################
use strict;
use FindBin qw($Bin);
use lib ($Bin, "$Bin/lib");
use Bugzilla;
use Bugzilla::Product;
use Bugzilla::Version;

### Globals ##########################################################################
use vars qw//;

### Function Declarations ############################################################

### Signal Handling ##################################################################

### Main Function ####################################################################
sub main(@)
{
	# Read the commandline arguments
	while (@_ and $_[0] =~ /^-/)
	{
		my $arg = shift;
		if ($arg =~ /^-h(elp)?$/)
		{
			Usage();
			next;
		}
		
		warn "Unknown argument '$arg'\n";
		Usage();
	}
	
	unless(@_)
	{
		Usage();
	}

	my $newVersionName = shift;

	# Connect to Bugzilla
	my $dbh = Bugzilla->dbh;

	# Get the list of products
	my @products = Bugzilla::Product->get_all();
	print "Found " . scalar(@products) . " products:\n";

	# Go over the products and add the new version if necessary
	foreach my $product (@products)
	{
		my $versions = $product->versions();
		if (grep(/^$newVersionName$/, map {$_->name()} @$versions))
		{
			print "Version $newVersionName already exists for product " . $product->name() . "\n";
			next;
		}

		my $newVersion = Bugzilla::Version::create($newVersionName, $product);
		print "Version " . $newVersion->name() . " added to product " . $product->name() . "\n";

	}

	return 0;
}

exit(main(@ARGV));

######################################################################################
### Subroutines section 
######################################################################################

######################################################################################
# Name: Usage
# Purpose: Print a usage message and quit the program
# Arguments: none
# Return Value: none
# Semantics: none
######################################################################################
sub Usage()
{
	die "Usage: $0 <new_version>\n";
}

