cmake_minimum_required(VERSION 3.16)
project(mode_metrics C)

set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)

option(MODE_WITH_CURL "Build the libcurl transport" ON)
# The tests are in this repository, not in the download, and build when the core is built on its own.
set(_mode_tests OFF)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests AND CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
  set(_mode_tests ON)
endif()
option(MODE_BUILD_TESTS "Build the tests" ${_mode_tests})
# The GTK and Qt layers for Linux desktop apps are packages of their own, mode-metrics-gtk and
# mode-metrics-qt, added next to this one. tests/linux builds them with the core for their tests.

add_library(mode STATIC src/mj.c src/clean.c src/platform.c src/mode.c src/transport_curl.c)
target_include_directories(mode PUBLIC include PRIVATE src)
target_compile_definitions(mode PRIVATE MODE_BUILD)
if(NOT MSVC)
  target_compile_options(mode PRIVATE -Wall -Wextra -Werror -Wno-unused-parameter)
  target_link_libraries(mode PUBLIC m)
endif()
if(UNIX)
  find_package(Threads REQUIRED)
  target_link_libraries(mode PUBLIC Threads::Threads)
endif()

if(MODE_WITH_CURL)
  find_package(CURL)
  if(CURL_FOUND)
    target_compile_definitions(mode PUBLIC MODE_WITH_CURL)
    target_link_libraries(mode PUBLIC CURL::libcurl)
    find_package(ZLIB)
    if(ZLIB_FOUND)
      target_compile_definitions(mode PRIVATE MODE_WITH_ZLIB)
      target_link_libraries(mode PUBLIC ZLIB::ZLIB)
    endif()
  else()
    message(STATUS "libcurl not found, the host must give mode_config.transport")
  endif()
endif()

if(MODE_BUILD_TESTS)
  enable_testing()
  add_executable(test_core tests/test_core.c)
  target_include_directories(test_core PRIVATE src)
  target_link_libraries(test_core PRIVATE mode)
  target_compile_definitions(test_core PRIVATE MODE_CONTRACT_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../contract")
  add_test(NAME core COMMAND test_core)
  add_executable(test_app tests/test_app.c)
  target_include_directories(test_app PRIVATE src)
  target_link_libraries(test_app PRIVATE mode)
  target_compile_definitions(test_app PRIVATE MODE_CONTRACT_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../contract")
  add_test(NAME app COMMAND test_app)
  add_executable(example examples/minimal.c)
  target_link_libraries(example PRIVATE mode)
  find_program(PYTHON3 python3)
  if(CURL_FOUND AND PYTHON3 AND UNIX)
    add_test(NAME live_curl COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/tests/live_curl.sh $<TARGET_FILE:example>)
  endif()
endif()
