#!/usr/bin/perl

use Bccd;
use Bccd::TestDb qw/open_db insert_results/;
use POSIX;
use Cwd;
use Getopt::Long;
use warnings;
use strict;

my $Bccd = new Bccd();
my %opts;
my $dir = getcwd();
my $stage = $Bccd->get_stage();
my $testname = "Rmpi";
my $svnrev = $Bccd->get_rev();
my $tmpdir;
my $ft;

GetOptions(
           'updatedb=s' => \$opts{'updatedb'},
           'nocleanup' => \$opts{'nocleanup'}
           );

if($opts{'updatedb'}) {
    $ft = new File::Temp();
    if( $opts{'nocleanup'} ) {
        $tmpdir = $ft->tempdir('bccd',CLEANUP => 0);
    } else {
        $tmpdir = $ft->tempdir('bccd',CLEANUP => 1);
    }
    $Bccd->redirect_stdio("$tmpdir");
}

$Bccd->run_test(
              "chdir",
              "",
              "cd /tmp",
              "/tmp"
              );

$Bccd->run_test(
              "system",
              "",
              "Initialized Rmpi w/ two slaves.",
              "echo -e \"library(Rmpi) \n mpi.spawn.Rslaves(nslaves=2)\"|R --slave; wipe"
              );

$Bccd->run_test(
              "system",
              "",
              "Wiped LAM.",
              "wipe"
              );

if($opts{'updatedb'}) {
    my $dbh = open_db("$opts{'updatedb'}");
    if( $Bccd->get_passed() < $Bccd->get_total() ) {
        insert_results($testname,$stage,$svnrev,$Bccd->snarf_file("$tmpdir/allout"),"FAILURE",$dbh);
    } else {
        insert_results($testname,$stage,$svnrev,$Bccd->snarf_file("$tmpdir/allout"),"SUCCESS",$dbh);
    }
    $Bccd->close_stdio();
    $dbh->disconnect;
}

exit $Bccd->get_total()-$Bccd->get_passed();
