# -*- mode: cmake -*-

set(MPI_LIBRARIES "")

if (DEFINED CMAKE_C_COMPILER AND NOT MPI_C_COMPILER)
  message(STATUS "MPI disabled")

else()

  # Eduard, had to rework this part, otherwise it breaks on Linux

  # see if MPI_CXX_COMPILER compiles MPI
  if (NOT DEFINED MPI_C_COMPILER)
    CHECK_CXX_SOURCE_COMPILES(
      "
      #include <mpi.h>
      int main(int argc, char **argv) {
          MPI_Init(&argc, &argv);
          MPI_Finalize();
      }
      "  CXX_COMPILER_COMPILES_MPI)
    if (CXX_COMPILER_COMPILES_MPI)
      set(HAVE_MPI TRUE)
      # assume C sources are compatible with C++
      set(MPI_CXX_COMPILER ${CMAKE_CXX_COMPILER})
      message(STATUS "C++ compiler (${CMAKE_CXX_COMPILER}) compiles and links MPI")
    endif()
  endif()
  
  # if MPI_C_COMPILER was provided, or the default compilers are not capable of MPI
  # find MPI
  if (NOT HAVE_MPI)
    find_package(MPI)
  
    if (NOT MPI_FOUND)
      message(FATAL_ERROR "MPI not found")
    else()
      set(HAVE_MPI TRUE)
      set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MPI_LINKER_FLAGS}")

      include_directories(${MPI_INCLUDE_PATH})

      list(APPEND CMAKE_REQUIRED_INCLUDES ${MPI_INCLUDE_PATH})
      list(APPEND CMAKE_REQUIRED_LIBRARIES ${MPI_LIBRARIES})

      message(STATUS "MPI_LIBRARIES: ${MPI_LIBRARIES}")
      message(STATUS "MPI_LINKER_FLAGS: ${MPI_LINKER_FLAGS}")

    endif()
  endif()
  
  # This should be outside the conditionals, ask Ed
  if (HAVE_MPI)
     option(ALWAYS_USE_MPI "Always use MPI" TRUE)
  endif()

  # check for MPI IO
  if (HAVE_MPI)
    CHECK_CXX_SOURCE_COMPILES(
      "
      #include <mpi.h>
      int main(int argc, char **argv) {
          MPI_Init(&argc, &argv);
          MPI_File file;
          MPI_File_open(MPI_COMM_WORLD, \"dummy.txt\", MPI_MODE_CREATE|MPI_MODE_WRONLY,
                        MPI_INFO_NULL, &file);
          MPI_File_close(&file);
          MPI_Finalize();
      }
      "  CXX_COMPILER_COMPILES_MPIIO)
    if (CXX_COMPILER_COMPILES_MPIIO)
      set(HAVE_MPIIO TRUE)
    endif()
  endif()
  
endif()
