#!/usr/bin/perl -w
use strict;

# testdriver script
# runs EpetraTpetraProfile repeatedly on different datasets

# ============================
# parse command-line arguments
# - get HB directory
# - check if we're using MPI
# ============================

my $dataDir;
my $buildDir;
my $numImages;

use Getopt::Long;
GetOptions( "data-dir=s" => \$dataDir,
			"build-dir=s" => \$buildDir,
			"mpi=i" => \$numImages );

if (!$dataDir) {
	die "data-dir value required.\n";
}

if (!$buildDir) {
	die "build-dir value required.\n";
}

if (!$numImages) {
	$numImages = 1;
}

# ============================
# name output file
# We want it to be of the form: machinename_YYYYMMDD_HHMM
# Ex: strider_20050907_1535
# ============================

# Get machine name 
my $machinename=`uname -n`;
chomp($machinename); # remove trailing newline

# Get date and time
my @dateandtime = localtime();
my $year = $dateandtime[5] + 1900; # localtime returns 1900=0, 1901=1, etc.
my $month = $dateandtime[4] + 1; # convert to 1-based
my $day = $dateandtime[3] + 1; # convert to 1-based
my $hour = $dateandtime[2];
my $min = $dateandtime[1];
# add leading zeros if necessary
if ($month < 10) {
	$month = "0" . $month;
}
if ($day < 10) {
	$day = "0" . $day;
}
if ($hour < 10) {
	$hour = "0" . $hour;
}
if ($min < 10) {
	$min = "0" . $min;
}

# put it all together
my $outputfile = $machinename . "_";
if ($numImages > 1) {
	$outputfile .= "mpi" . $numImages . "_";
}
else {
	$outputfile .= "serial_";
}
$outputfile .= $year . $month . $day . "_" . $hour . $min;
print "Output file is: $outputfile\n";

# ============================
# Get testfiles to run on
# ============================
# the call to grep filters out any files that don't end in ".hb", ".rua", or ".rsa".
opendir(DIR, $dataDir);
my @datafiles = grep(/\.hb$|\.rua$|\.rsa$/, readdir(DIR));
closedir(DIR);

# ============================
# Run the tester
# ============================

my $mpiprefix = "mpirun -np $numImages ";

my $command = "/packages/tpetra/example/EpetraTpetraProfile/EpetraTpetraProfile.exe ";
if ($numImages > 1) {
	$command = $mpiprefix . $buildDir . $command;
}
else {
	$command = $buildDir . $command;
}

my $matrix;
foreach $matrix (@datafiles) {
	print "$matrix\n";
	system "$command $dataDir/$matrix >> $outputfile";
}
