#  Copyright (c) 2018
#  Charles Jordan (Hokkaido University, Sapporo, Japan),
#  Michael Joswig, Lars Kastner (Technische Universitaet Berlin, Germany)
# 
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 3, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
# 
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-------------------------------------------------------------------------------


@conf_vars=qw( MPI_PATH MPICXX MPICC MPIRUN NO_MPI );

sub allowed_options {
   my ($allowed_options, $allowed_with)=@_;
   @$allowed_with{ qw( mpi mpi-include mpi-lib) }=();
}


sub usage {
   print STDERR "  --with-mpi=PATH          path to mpi installation, e.g. Open MPI.\n",
                "  --with-mpi-include=PATH  Path to the folder containing mpi.h\n",
                "  --with-mpi-lib=PATH      Path to the folder containing libmpigmp.{a,so,dylib} \n",
                "  --without-mpi            Disable usage of mpi, build single threaded version only\n";
}


#######################################################################
sub proceed{
   my ($options, $CXX, $CC)=@_;
   # Check mpi compiler with temporary switch
   my $mpicxx = "mpicxx";
   my $mpicc = "mpicc";
   my $mpirun = "mpirun";
   if($options->{mpi} ne ""){
      $MPI_PATH = $options->{mpi};
      $mpicxx = "$options->{mpi}/bin/mpicxx";
      $mpicc = "$options->{mpi}/bin/mpicc";
      $mpirun = "$options->{mpi}/bin/mpirun";
   } else {
      $mpicxx = `which mpicxx 2>/dev/null`;
      chomp $mpicxx;
      $? == 0 or $mpicxx = "mpicxx";
      $mpicc = `which mpicc 2>/dev/null`;
      chomp $mpicc;
      $? == 0 or $mpicc = "mpicc";
      $mpirun = `which mpirun 2>/dev/null`;
      chomp $mpirun;
      $? == 0 or $mpirun = "mpirun";
   }
   eval{
      Polymake::Configure::check_program($mpicxx);
      Polymake::Configure::check_program($mpicc);
      Polymake::Configure::check_program($mpirun);
   };
   if($@){
      die "failed to check mpicc, mpicxx: $@";
   }
   # -showme:version is certainly not portable, no reason to die on non-Open MPI
   # we shouldn't hide the compiler change here: users should set their
   # environment variables as they like and won't expect a hidden over-ride
   # only on Open MPI
   my $version = `$mpicxx -showme:version`;
   my $isOMPI = $version =~ m/Open MPI/;
   chomp $version;
   $version =~ s/.*?:\s*//;
   if($isOMPI){
      $MPICXX = "OMPI_CXX=$CXX $mpicxx";
      $MPICC = "OMPI_CC=$CC $mpicc";
      $MPIRUN = "$mpirun";
   }
   else{
      $MPICXX = "$mpicxx";
      $MPICC = "$mpicc";
      $MPIRUN = "$mpirun";
   }
   return ["$version", $mpirun];
}
