cmake_minimum_required(VERSION 3.15)

project(spydlog)

set(LIB_NAME spydlog)

# utils
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")

include(target_options)

# options
option(SANITIZE "Build with sanitizer" OFF)

# python
if(CMAKE_VERSION VERSION_LESS 3.18)
    set(DEV_MODULE Development)
else()
    set(DEV_MODULE Development.Module)
endif()

find_package(Python ${PYTHON_VERSION} COMPONENTS Interpreter ${DEV_MODULE} REQUIRED)

if(NOT ${Python_FOUND})
    message(FATAL_ERROR "Python can't be found, exiting CMake")
endif()

include_directories(${Python_INCLUDE_DIRS})
link_directories(${Python_LIBRARY_DIRS})

# nanobind
add_subdirectory(${CMAKE_SOURCE_DIR}/ext/nanobind CONFIG)
include_directories(${CMAKE_SOURCE_DIR}/ext/nanobind/include)

# spdlog
set(spdlog_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/ext/spdlog/include")
include_directories(${spdlog_INCLUDE_DIRS})

# spydlog module
if(SANITIZE)
    # We can't link nanobind statically when building with sanitizer
    nanobind_add_module(${LIB_NAME} NB_SHARED src/spydlog.cpp)
else()
    nanobind_add_module(${LIB_NAME} NB_STATIC src/spydlog.cpp)
endif()

set_target_options(${LIB_NAME})

# install
install(TARGETS ${LIB_NAME}
        DESTINATION spydlog)

install(FILES src/__init__.py
        DESTINATION spydlog)

if(EXISTS ${CMAKE_SOURCE_DIR}/src/_version.py)
    install(FILES src/_version.py
            DESTINATION spydlog)
elseif(EXISTS ${CMAKE_CURRENT_BINARY_DIR}/_version.py)
    install(FILES ${CMAKE_CURRENT_BINARY_DIR}/_version.py
            DESTINATION spydlog)
else()
    message(STATUS "_version.py not found, will be generated by setuptools-scm")
endif()

# if building in debug (with sanitizer) we need to copy the asan dll
if(MSVC)
    if(SANITIZE)
        # asan
        get_filename_component(CL_DIR ${CMAKE_CXX_COMPILER} DIRECTORY)

        install(FILES ${CL_DIR}/clang_rt.asan_dynamic-x86_64.dll
                DESTINATION spydlog)

        install(CODE [[
            file(GET_RUNTIME_DEPENDENCIES
                 EXECUTABLES $<TARGET_FILE:spydlog>
                 RESOLVED_DEPENDENCIES_VAR RESOLVED_DEPS
                 UNRESOLVED_DEPENDENCIES_VAR UNRESOLVED_DEPS
                 PRE_EXCLUDE_REGEXES "api-ms-" "ext-ms-" "hvsifiletrust" "pdmutilities" "aclui"
                 POST_EXCLUDE_REGEXES ".*[Ss]ystem32/.*\\.dll")

            foreach(FILE ${RESOLVED_DEPS})
                file(INSTALL
                     DESTINATION ${CMAKE_INSTALL_PREFIX}/spydlog
                     TYPE SHARED_LIBRARY
                     FOLLOW_SYMLINK_CHAIN
                     FILES "${FILE}")
            endforeach()
        ]])
    endif()
endif()
