# 输入变量:
# 输入mpi_PATH, THIRDLIB_PATH, 
# 依据这两个输入路径搜索需要的头文件和库文件,
#
# 输出变量:
# 输出mpi_FOUND, mpi_INCLUDES, mpi_LIBRARIES.
# 并将mpi_INCLUDES追加到THIRDLIB_INCLUDES,
# 将mpi_LIBRARIES追加到THIRDLIB_LIBRARIES


# 定义搜索路径
set(mpi_search_PATHS ${mpi_PATH})
foreach (path ${THIRDLIB_PATH})
  list(APPEND mpi_search_PATHS ${path}/mpi)
endforeach()

# 这个模块由很多的库文件组成
if (NOT mpi_FIND_COMPONENTS)
  set(mpi_FIND_COMPONENTS mpi)
endif ()

# 设置搜索路径
set(_OLD_PREFIX_PATH ${CMAKE_PREFIX_PATH})
set(CMAKE_PREFIX_PATH ${mpi_search_PATHS})
if (NOT THIRDLIB_FIND_ARGUMENTS)
  set(THIRDLIB_FIND_ARGUMENTS "PATHS ${mpi_search_PATHS} PATH_SUFFIXES lib NO_DEFAULT_PATH")
endif ()

# 搜索需要的头文件
find_file(mpi_INCLUDES NAMES include ${THIRDLIB_FIND_ARGUMENTS})
if (mpi_INCLUDES)
  # do nothing
elseif (mpi_FIND_REQUIRED)
  message(FATAL_ERROR "Not found 'include' directory in ${mpi_search_PATHS}")
endif ()

# 搜索需要的库文件
foreach (module ${mpi_FIND_COMPONENTS})
  find_library(mpi_LIBRARIES_${module} NAMES ${module} ${THIRDLIB_FIND_ARGUMENTS})
  if (mpi_LIBRARIES_${module})
    list(APPEND mpi_LIBRARIES ${mpi_LIBRARIES_${module}})
  else ()
    list(APPEND mpi_NO_LIBRARIES ${mpi_LIBRARIES_${module}})
    if (mpi_FIND_REQUIRED)
      message(FATAL_ERROR "Not found lib/'${module}' in ${mpi_search_PATHS}")
    endif ()
  endif ()
endforeach ()

# 恢复CMAKE_PREFIX_PATH
set(CMAKE_PREFIX_PATH ${_OLD_PREFIX_PATH})

# 输出信息
if (NOT mpi_FIND_QUIETLY)
  message(STATUS "Found mpi: ${mpi_INCLUDES}, ${mpi_LIBRARIES};${mpi_NO_LIBRARIES} in ${mpi_search_PATHS}")
endif ()

# 定义输出变量
if (mpi_INCLUDES AND mpi_LIBRARIES)
  set(mpi_FOUND TRUE)
  string(TOUPPER mpi _UPPER_CASE)
  set(HAVE_${_UPPER_CASE} 1)
  unset(_UPPER_CASE)
else ()
  set(mpi_FOUND FALSE)
endif ()

# 只是为了方便, 其实破坏了封装
# 追加包含变量到THIRDLIB变量里面
if (mpi_INCLUDES)
  list(APPEND THIRDLIB_INCLUDES ${mpi_INCLUDES})
endif ()
# 追加库文件变量到THIRDLIB变量里面, 只是为了方便, 其实破坏了封装
if (mpi_LIBRARIES)
  list(APPEND THIRDLIB_LIBRARIES ${mpi_LIBRARIES})
endif ()

