cmake_minimum_required(VERSION 3.21...3.30)
if(Python_FIND_ABI MATCHES "ON$")
  cmake_minimum_required(VERSION 3.30)
endif()

project(XoscarCollective)
if(DEFINED PYTHON_PATH)
  set(Python_EXECUTABLE "${PYTHON_PATH}")
endif()
if(Python_FIND_ABI MATCHES "ON$")
  # Windows headers do not define this for the free-threaded build.
  add_compile_definitions(Py_GIL_DISABLED=1)
endif()
find_package(Python REQUIRED COMPONENTS Interpreter Development.Module)
set(PYBIND11_FINDPYTHON ON)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")

if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
  option(USE_LIBUV "Build tcp transport on linux" OFF)
else()
  option(USE_LIBUV "Build libuv transport on others" ON)
endif()

if(MSVC)
  add_compile_options(/utf-8)
  message(STATUS "Done setting /utf-8 for MSVC")
endif()

include_directories(${CMAKE_SOURCE_DIR})
# Set include directories
include_directories(${Python_INCLUDE_DIRS})
if(NOT DEFINED XOSCAR_PYTHON_SOURCE_DIR)
  set(XOSCAR_PYTHON_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/python")
endif()
if(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
  set(libuv_dir ${CMAKE_SOURCE_DIR}/third_party/libuv/build/uvlib)
  if(NOT EXISTS ${libuv_dir})
    set(libuv_source "${CMAKE_CURRENT_SOURCE_DIR}/third_party/libuv")
    set(libuv_binary "${libuv_source}/build")
    execute_process(
      COMMAND
        "${CMAKE_COMMAND}" -S "${libuv_source}" -B "${libuv_binary}"
        "-DCMAKE_INSTALL_PREFIX=${libuv_dir}" -DCMAKE_POLICY_VERSION_MINIMUM=3.10
        COMMAND_ERROR_IS_FATAL ANY)
    execute_process(COMMAND "${CMAKE_COMMAND}" --build "${libuv_binary}" --target INSTALL
                            COMMAND_ERROR_IS_FATAL ANY)
    message(STATUS "Done creating libuv_dir = ${libuv_dir}")
  endif()
  set(libuv_ROOT ${CMAKE_SOURCE_DIR}/third_party/libuv/build/uvlib)
  set(uv_HEADER_PATH ${CMAKE_SOURCE_DIR}/third_party/libuv/include)
  include_directories(${uv_HEADER_PATH})
  #copy uv.dll to /python/xoscar/collective
  file(COPY ${CMAKE_SOURCE_DIR}/third_party/libuv/build/uvlib/bin/uv.dll
       DESTINATION "${XOSCAR_PYTHON_SOURCE_DIR}/xoscar/collective")
  add_definitions(-DNOMINMAX)
endif()

add_subdirectory(third_party/fmt)
add_subdirectory(third_party/pybind11)
add_subdirectory(third_party/gloo)

if(NOT DEFINED BUILD_TMP_DIR)
  file(GLOB TMP_DIRS "${XOSCAR_PYTHON_SOURCE_DIR}/build/temp*")
  foreach(TMP_DIR ${TMP_DIRS})
    set(BUILD_TMP_DIR ${TMP_DIR}/xoscar_pygloo)
  endforeach()
elseif(NOT IS_ABSOLUTE "${BUILD_TMP_DIR}")
  set(BUILD_TMP_DIR "${XOSCAR_PYTHON_SOURCE_DIR}/${BUILD_TMP_DIR}")
endif()
# copy config.h to cpp/gloo/include
file(COPY ${BUILD_TMP_DIR}/third_party/gloo/gloo/config.h
     DESTINATION ${CMAKE_SOURCE_DIR}/cpp/collective/gloo/include)

add_subdirectory(cpp)
