###
#
# GENERATE_PASTIXCONF: generate pastix-conf script according to the options
#
###
macro(generate_pastixconf _file)

  # set libs
  set(LIBS "-L${CMAKE_INSTALL_PREFIX}/lib -lpastix")
  if (PASTIX_ORDER_LIBDIRS)
    foreach(_libdir ${PASTIX_ORDER_LIBDIRS})
      list(APPEND LIBS "-L/${_libdir}")
    endforeach()
  endif()
  if (PASTIX_ORDER_LIBS)
    list(APPEND LIBS "${PASTIX_ORDER_LIBS}")
  endif()
  if (PASTIX_EXTRA_LIBDIRS)
    foreach(_libdir ${PASTIX_EXTRA_LIBDIRS})
      list(APPEND LIBS "-L/${_libdir}")
    endforeach()
  endif()
  if (PASTIX_EXTRA_LIBS)
    list(APPEND LIBS "${PASTIX_EXTRA_LIBS}")
  endif()
  if (PASTIX_WITH_MPI)
    if (MPI_C_LIBRARIES)
      list(APPEND LIBS ${MPI_C_LIBRARIES})
    endif()
    if (MPI_CXX_LIBRARIES)
      list(APPEND LIBS ${MPI_CXX_LIBRARIES})
    endif()
    if (MPI_Fortran_LIBRARIES)
      list(APPEND LIBS ${MPI_Fortran_LIBRARIES})
    endif()
  endif()
  list(APPEND LIBS ${CMAKE_Fortran_IMPLICIT_LINK_LIBRARIES})
  set(LIBS_CPY "${LIBS}")
  set(LIBS "")
  foreach(_dep ${LIBS_CPY})
    string(REGEX MATCH "^/" test_dep1 ${_dep})
    string(REGEX MATCH "^-" test_dep2 ${_dep})
    if (test_dep1 OR test_dep2)
      string(REPLACE "-L//" "-L/" _dep ${_dep})
      list(APPEND LIBS "${_dep}")
    else()
      list(APPEND LIBS "-l${_dep}")
    endif()
  endforeach()
  list(REMOVE_DUPLICATES LIBS)
  string(REPLACE ";" " " LIBS "${LIBS}")

  # set pastix include
  set(INC "-I${CMAKE_INSTALL_PREFIX}/include")
  # other includes
  set(INCS "")
  foreach(_dir ${PASTIX_EXTRA_INCDIRS})
    list(APPEND INCS "-I${_dir}")
  endforeach()
  list(REMOVE_DUPLICATES INCS)

  get_property(DEFS DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY COMPILE_DEFINITIONS)
  set(OPTS "")
  foreach(_def ${DEFS})
    list(APPEND OPTS "-D${_def}")
  endforeach()

  # set C compiler
  get_filename_component(CC ${CMAKE_C_COMPILER} NAME)
  set(CL "${CC}")
  set(CCOPT "${CMAKE_C_FLAGS} ${OPTS}")
  list(REMOVE_DUPLICATES CCOPT)
  string(REPLACE ";" " " CCOPT "${CCOPT}")

  # set CXX compiler
  get_filename_component(CXX ${CMAKE_CXX_COMPILER} NAME)
  set(CXXOPT "${CMAKE_CXX_FLAGS} ${OPTS}")
  list(REMOVE_DUPLICATES CXXOPT)
  string(REPLACE ";" " " CXXOPT "${CXXOPT}")

  # set Fortran compiler
  get_filename_component(FC ${CMAKE_Fortran_COMPILER} NAME)
  set(FL "${FC}")
  set(FCOPT "${CMAKE_Fortran_FLAGS} ${OPTS}")
  list(REMOVE_DUPLICATES FCOPT)
  string(REPLACE ";" " " FCOPT "${FCOPT}")

  string(REPLACE ";" " " OPTS "${OPTS}")

  # set version
  set(VERSION "${PASTIX_VERSION_MAJOR}.${PASTIX_VERSION_MINOR}.${PASTIX_VERSION_MICRO}")

  # set BLAS libraries
  set(BLAS "${BLAS_LIBRARIES}")

  # Create the pastix-conf file
  # ---------------------------
  set(_output_file "${CMAKE_BINARY_DIR}/pastix-conf")
  configure_file("${_file}" "${_output_file}" @ONLY)

  # installation
  # ------------
  install(PROGRAMS ${_output_file} DESTINATION bin)

endmacro(generate_pastixconf)
