#!/usr/bin/perl
#
# Name: mpisrun
#
# Syntax:
#  mpisrun
#       [mpirun option] {srun option] executable
#
# $Revision: 5743 $
#
# Examples:
#
# End

select(STDERR); $| = 1;
select(STDOUT); $| = 1;

my $silent=1;
my $debug=0;

my $opt;
my $opt2;
my @options; 
my @srunoptions;
my @mpirunoptions;
my @restofcmd;
my @appfilecmd;
my @appfileargs;
my @exefileargs;
my @ignoreargs;
my $doingcmd=0;

# keywords we care about in abbreviated form from slurm
my %kwrds = ( "-n",1,"-N",2,"-m",3,"-w",4,"-x",5,"-O",6);

# look for an option that is a substring of one of the 
# keywords in the %kwrds hash. This handles arguments of 
# the form -Nxxx where there is no intervening space.
sub srunkeysearch {
 $a = $_[0];
 foreach $key (keys %kwrds) {
   if (substr($a,0,length($key)) eq $key) {
   	return 1;
   }
 }
 return 0;
}

sub ignoresearch {
    $a = $_[0];
    my @locargs = @ignoreargs;
    while (@locargs) {
	$b = pop(@locargs);
	if ($b eq $a ) {
	    return 1;
	}
    }
    return 0;
}
$runmode=0;
$srunmode=1;
$prunmode=2;

$prog = $0;
if ($ENV{"MPI_USESRUN"} >= 1) { 
    $runmode=$srunmode;
    $pname = "srun";
}

if ($ENV{"MPI_USEPRUN"} >= 1 ) {  
    $runmode=$prunmode;
    $pname = "prun";
}

$prog =~ s/mpisrun/mpirun/;
$prog =~ s/mpisrun/mpirun/;

if ($runmode == 0) {
   print "Error: bad mode detected\n";
   die(1);
}

if ($ENV{"MPI_USESRUN_VERBOSE"} >= 1) {
    $silent=0;
}

if ($ENV{"MPI_USESRUN_DEBUG"} >= 1 ) {
    $silent =0;
    $debug=1;
} 

if ($runmode == $srunmode) {
  $s = $ENV{"MPI_USESRUN_IGNORE_ARGS"};
} else { # prunmode
  $s = $ENV{"MPI_USEPRUN_IGNORE_ARGS"};
}

if ($s ne "") {
    @ignoreargs = split(" ",$s);
    print "ignoreargs: $s\n" if ($debug);
}


print "$prog\n" unless  $silent;
print %kwrds,"\n" if ($debug);

@options =  @ARGV;
while (@ARGV) {
  $opt = shift ;
  print "$opt\n" if ($debug);
    if ($doingcmd == 0) { 
    
      # is it a pure keyword for srun (no appended arg)?
      if (@kwrds{$opt})  {
        $opt2 = shift;
        print "got $pname option $opt $opt2\n" if ($debug) ;
	push @srunoptions, $opt;
        push @srunoptions, $opt2;


      # look for ignorable args
      } elsif (ignoresearch($opt)) {
          print "ignoring mpirun option $opt" if ($debug) ;

      # look for -np , handle and translate
      } elsif (substr($opt,0,3) eq "-np") {
        $opt2 = shift;
        print "got mpirun option $opt $opt2 translating to -n #\n" if ($debug) ;
        push @srunoptions, "-n$opt2";

      # look for -ndd
      } elsif (substr($opt,0,4) eq "-ndd") {
        print "got mpirun option $opt  #\n" if ($debug) ;
        push @mpirunoptions, "$opt";

      # look for -srun , handle and discard  
      } elsif (substr($opt,0,5) eq "-$pname") {
        print "discarding extraneous -$pname\n" if ($debug) ;

      # look for -f appfile , handle and discard
      } elsif (substr($opt,0,2) eq "-f") {
        $opt2 = shift;
        print "discarding extraneous -f\n" if ($debug) ;
        appfilesearch($opt2);

      # if this is a -- all by itself then its appfile stuff              
      # add it all to the end of exefileargs 
      } elsif ($opt eq "--") {
        print "got appfile executable options $opt\n" if ($debug) ;
        while (@ARGV) {
          $opt = shift ;
          print "$opt\n" if ($debug);
          push @exefileargs, $opt;
        }

      # if this is a -- then it is a slurm keyword, or if the keyword is 
      # a proper substring of one of our 'well known' keywords 
      } elsif (srunkeysearch($opt) || substr($opt,0,2) eq "--") {
        print "got $pname option $opt\n" if ($debug) ;
        push @srunoptions, $opt;
      
      # else its an mpirun option
      } elsif (substr($opt,0,1) eq "-") {
        print "got mpirun option $opt\n" if ($debug) ;
        if ($opt eq "-e") {
	      $opt2 = shift;
	      if (substr($opt2,0,12) eq "MPI_WORKDIR=") {
	         $opt2 = substr($opt2,12);
		print "got --chdir option $opt2\n" if ($debug) ;
		push  @srunoptions, "--chdir=".$opt2;
	      } else {
                print "got -e option $opt2\n" if ($debug) ;
                push @mpirunoptions, $opt;
                push @mpirunoptions, $opt2;
              }
        } else {
           push @mpirunoptions, $opt;
        }

      # else its the command and so is everything that follows.
      } else {
        print "got cmd/option $opt\n" if ($debug) ;
        push @restofcmd, $opt;
        $doingcmd = 1;
      }

    # we are now just gobbeling arguments for the executable
    } else {
      print "got cmd/option $opt\n" if ($debug) ;
      push @restofcmd, $opt;
    }
  }

$doingcmd = 0;

while (@appfileargs) {
  $opt = shift(@appfileargs) ;
  print "$opt\n" if ($debug);
    if ($doingcmd == 0) { 
    
      # else its an mpirun option
      if (substr($opt,0,1) eq "-") {
        print "got mpirun option $opt\n" if ($debug) ;
        push @mpirunoptions, $opt;
        if ($opt eq "-e") {
	      $opt2 = shift(@appfileargs);
              print "got -e option $opt2\n" if ($debug) ;
              push @mpirunoptions, $opt2;
	      if (substr($opt2,0,12) eq "MPI_WORKDIR=") {
                  $opt3 = substr($opt2,12);
                  print "got --chdir option $opt3\n" if ($debug) ;
                  push  @srunoptions, "--chdir=".$opt3;
              }
        }

      # else its the command and so is everything that follows.
      } else {
        print "got cmd/option $opt\n" if ($debug) ;
        push @restofcmd, $opt;
        $doingcmd = 1;
      }

    # we are now just gobbeling arguments for the executable
    } else {
      print "got cmd/option $opt\n" if ($debug) ;
      push @restofcmd, $opt;
    }
  }


print STDERR "\@options: @options\n" if ($debug);
if ($runmode==$prunmode) {
     $cmd = "unset MPI_USEPRUN;$prog @mpirunoptions -$pname @srunoptions @restofcmd @exefileargs\n";
} else {
     $cmd = "unset MPI_USESRUN;$prog @mpirunoptions -$pname @srunoptions @restofcmd @exefileargs\n";
}
print "$cmd\n" unless $silent;

$status = system($cmd) ;

# pulled status code from O'reilly page 230 (with fixes)
$status = 0xffff & $status;
if ($status == 0) { 				# normal exit
   ;
} elsif ($status == 0xffff) { 			# no execute permission
   $status = 1; 
   print STDERR "FAILED: Execution failed\n";
} elsif (($status & 0xff) == 0) { 		# non-zero exit status
   $status >>= 8;
   # print STDERR "FAILED: Non-zero exit status $status\n";
} else {					# signal
   my($signal) = $status;
   if ($status & 0x80) { $signal &= ~0x80; }	# w/ coredump flag
   print STDERR "FAILED: Got signal $signal\n";
}

exit($status);

# open appfile and extract everything but -h and -np options/args
# append to ARGV
sub appfilesearch {
 $a = $_[0];
 print "appfile parse: $a\n" if ($debug) ;
 open APPFILE, "<", $a;
do {
  $a = <APPFILE>; 
  print "appfile line:$a\n" if ($debug) ;
  $a =~ s/#.*$//;
  $a =~ s/^\s+//;
} until (ord($a) != 0);

 $np_seen=0;
 print "appfile line:$a\n" if ($debug) ;
 @appfilecmd = split(" ",$a);
 while (@appfilecmd) { 
  $opt = shift(@appfilecmd) ; 
  if ($opt eq "-h" ) {
    $opt2 = shift(@appfilecmd);
    print "appfile skipping arg:$opt $opt2\n" if ($debug) ;
  } elsif ($opt eq "-np" && $np_seen==0) {
    $opt2 = shift(@appfilecmd);
    print "appfile skipping arg:$opt $opt2\n" if ($debug) ;
    $np_seen =1;
  } else {
    print "appfile arg:$opt\n" if ($debug) ;
    push @appfileargs , $opt; 
  }
}


 return 0;
}

