#!/usr/bin/perl

# This script takes a runid of a Condor build and returns runids or
# gids (or both) of all of its associated tests.

# Usage: nmi_gest_tests.pl <buildId> [--runid] [--gid]

use strict;
use warnings;
use DBI;
use Getopt::Long;

use lib $ENV{'NMI_LIB'} || "/nmi/lib";
use NmiConf;
use NmiTools;
my $nmiconf = $NmiConf::NMICONF_DEFAULT if -f $NmiConf::NMICONF_DEFAULT;

if (defined $main::opt_nmiconf) {
  die "Config file ${main::opt_nmiconf} does not exist. Exiting...\n"
    unless -f $main::opt_nmiconf;
  $nmiconf = $main::opt_nmiconf;
}

die "FATAL: $0: No config file specified.\n" unless defined $nmiconf;
die "FATAL: $0: Config file $nmiconf is not readable.\n" unless -r $nmiconf;

## ---------------------------------------------
## Load NMI Configuration
## ---------------------------------------------

my %conf = NmiConf::init($main::opt_nmiconf);

## ---------------------------------------------
## Database Connection
## ---------------------------------------------

my $DB_HOST = $conf{'DB_HOST'};
my $DB_PORT = $conf{'DB_PORT'};
my $DB_NAME = $conf{'DB_NAME'};
my $DB_READER_USER = $conf{'DB_READER_USER'};
my $DB_READER_PASS = $conf{'DB_READER_PASS'};

my $usage = "usage: $0 <buildId> [--runid] [--gid]\n";

GetOptions('help' => $main::opt_help,
	   'runid' => $main::opt_runid,
	   'gid' => $main::opt_gid,
	  ) or die $usage;

if (defined $main::opt_help) {
  print $usage;
  exit 0;
}

unless (defined $main::opt_runid or defined $main::opt_gid) {
  $main::opt_runid = 1;
  $main::opt_gid = 1;
}

die "usage: $0 <buildId>" unless @ARGV == 1;
my $runid = $ARGV[0];

my $DB_CONNECT_STR = "DBI:mysql:database=$DB_NAME;host=$DB_HOST";
$DB_CONNECT_STR .= ";port=$DB_PORT" if $DB_PORT;
      
my $dbh = DBI->connect($DB_CONNECT_STR, $DB_READER_USER, $DB_READER_PASS) ||
   die("Could not connect to mysql db '$DB_NAME' on $DB_HOST: ", $DBI::errstr);

my $cmd_str = <<"END";
select distinct Task.runid,Run.gid from Task,Method_nmi,Run
where Task.runid = Method_nmi.runid AND Method_nmi.input_runid = $runid
AND Run.runid=Method_nmi.runid;
END

my $handle = $dbh->prepare("$cmd_str") or
  die "Could not prepare mysql statement '$cmd_str': ", $DBI::errstr;

$handle->execute() or die
  "FATAL: Could not execute statement '$cmd_str': ${DBI::errstr}";

while (my $arr_ref = $handle->fetchrow_arrayref()) {
  print $arr_ref->[0], ' ', if defined $main::opt_runid;
  print $arr_ref->[1], ' ', if defined $main::opt_gid;
  print "\n";
}

$dbh->disconnect;
