cmake_minimum_required(VERSION 3.21)
project(py_cdhit LANGUAGES CXX)

set(upstream "${CMAKE_CURRENT_SOURCE_DIR}/vendor/cdhit")
set(aux "${upstream}/cd-hit-auxtools")
if(NOT EXISTS "${upstream}/cdhit-common.c++")
  message(FATAL_ERROR "Missing CD-HIT source. Run git submodule update --init.")
endif()
if(WIN32 AND NOT MINGW)
  message(FATAL_ERROR "The Windows build requires MinGW-w64 GCC.")
endif()

find_package(OpenMP REQUIRED COMPONENTS CXX)
find_package(ZLIB REQUIRED)

add_library(cdhit_core STATIC
  "${upstream}/cdhit-common.c++" "${upstream}/cdhit-utility.c++")
target_compile_definitions(cdhit_core PUBLIC MAX_SEQ=1000000 WITH_ZLIB)
target_link_libraries(cdhit_core PUBLIC OpenMP::OpenMP_CXX ZLIB::ZLIB)
if(MINGW)
  target_compile_options(cdhit_core PUBLIC
    -include "${CMAKE_CURRENT_SOURCE_DIR}/cmake/windows_string.h")
endif()

set(programs cd-hit cd-hit-2d cd-hit-est cd-hit-est-2d cd-hit-div cd-hit-454)
foreach(program IN LISTS programs)
  string(REPLACE "cd-hit" "cdhit" source "${program}")
  add_executable(${program} "${upstream}/${source}.c++")
  target_link_libraries(${program} PRIVATE cdhit_core)
endforeach()

add_library(cdhit_aux STATIC "${aux}/bioSequence.cxx"
  "${aux}/mintlib/minString.cxx" "${aux}/mintlib/minMap.cxx")
target_include_directories(cdhit_aux PUBLIC "${aux}" "${aux}/mintlib")
target_compile_options(cdhit_aux PUBLIC "$<$<CONFIG:Release>:-O2;-UNDEBUG>")
foreach(tool IN ITEMS dup lap)
  add_executable(cd-hit-${tool} "${aux}/cdhit-${tool}.cxx")
  target_link_libraries(cd-hit-${tool} PRIVATE cdhit_aux)
endforeach()

install(TARGETS ${programs} cd-hit-dup cd-hit-lap
  RUNTIME_DEPENDENCY_SET cdhit_runtime RUNTIME DESTINATION pycdhit/bin)
if(MINGW)
  get_filename_component(compiler_bin "${CMAKE_CXX_COMPILER}" DIRECTORY)
  install(RUNTIME_DEPENDENCY_SET cdhit_runtime
    DIRECTORIES "${compiler_bin}"
    PRE_EXCLUDE_REGEXES "^[aA][pP][iI]-" "^[eE][xX][tT]-"
    POST_EXCLUDE_REGEXES "[/\\\\][Ss][Yy][Ss][Tt][Ee][Mm]32[/\\\\]"
    RUNTIME DESTINATION pycdhit/bin)
endif()
