#!/usr/bin/env perl

# Generate a flat text file of tags from EIS

my $DEFAULT_MASTER='SRC680';

use Cws;
use Eis;

sub print_tags($$)
{
    my $ft = shift;
    my $childws = shift;

    if ($ft ne 'STDOUT') {
	open(MYOUT, ">>$ft");
    } else {
	open MYOUT, ">&STDOUT" or die "Can't dup STDOUT: $!";
    }

    my $master = $DEFAULT_MASTER;

    my $eis = Cws::eis();
    $id = $eis->getChildWorkspaceId
	( Eis::to_string($master),
	  Eis::to_string($childws) );
    if (!$id) {
	print "# Invalid cws '$childws' / no EIS Id\n";
	return 1;
    }

# skip non-public cws
    return 0 unless ($eis->isPublic($id));

    my @modules = @{$eis->getModules($id)};
    my $milestone = $eis->getMilestone($id);

    my $creation_master = $eis->getCreationMasterWorkspace($id);
    my $cws_branch_tag = 'cws_' . lc($creation_master) . '_' . lc($childws);
    my $master_milestone_tag = uc($master) . "_" . $milestone;

    print(MYOUT "$childws : $master_milestone_tag : $cws_branch_tag : @modules\n");

    return 0;
}

my $eis = Eis->new( uri => Cws::eis_uri(), 
		    proxy_list => Cws::eis_proxy_list(), 
		    net_proxy => Cws::net_proxy()
		    );

# State can be 'integrated', 'ready for QA', 'planned', 'new' (etc.?)
sub get_cws_with_state($)
{
    my $cws_list;
    my $state = shift;

    my $eis = Cws::eis();
    
    $cws_list = $eis->getCWSWithState( Eis::to_string( $DEFAULT_MASTER ),
				       Eis::to_string( $state ) );
    if (!defined $cws_list) {
	return undef;
    }

    my @list = @{$cws_list};
#    print STDERR "CWS list [$DEFAULT_MASTER] : @list\n";

    return @list;
}

print "# List of cws' and modules to test/build\n";
print "# <name> : <master-tag> : <cws-tag> : <modules>\n";

my @ready_for_qa = get_cws_with_state( 'ready for QA' );
if (!@ready_for_qa) {
    exit (1);
}

my @new_cws = get_cws_with_state( 'new' );
if (!@new_cws) {
    exit (1);
}

for $cws (@ready_for_qa) {
    print_tags ('STDOUT', $cws) && exit (1);
}

for $cws (@new_cws) {
    print_tags ('/var/www/tinderbox/tags/tag-list-new.tmp', $cws) && exit (1);
}

exit (0);
