cmake_minimum_required(VERSION 3.18...3.26 FATAL_ERROR)
project(Starter VERSION 8.3 LANGUAGES CXX)

get_property(IS_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)

if(NOT DEFINED CMAKE_CXX_STANDARD)
    set(CMAKE_CXX_STANDARD 17)
endif()

set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

if(NOT CMAKE_BUILD_TYPE AND NOT IS_MULTI_CONFIG)
    message(STATUS "No build type specified - default is DEBUG")
    set(CMAKE_BUILD_TYPE DEBUG)
endif()

list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/TangoCMakeModules)
find_package(Tango REQUIRED)

set(SOURCES CheckProcessUtil.cpp
            ClassFactory.cpp
            main.cpp
            PingThread.cpp
            Starter.cpp
            StarterClass.cpp
            StarterService.cpp
            StarterStateMachine.cpp
            StarterUtil.cpp
            StartProcessThread.cpp)

set(HEADER CheckProcessUtil.h
           Logging.h
           PingThread.h
           Starter.h
           StarterClass.h
           StarterService.h
           StarterUtil.h)

add_executable(Starter ${SOURCES} ${HEADER})
target_link_libraries(Starter PRIVATE Tango::Tango)

if (WIN32 AND (Tango_IS_STATIC OR Tango_FORCE_STATIC))
    set_target_properties(${PROJECT_NAME} PROPERTIES
        MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>"
    )
endif()

if (WIN32)
    # Starter requires WIN32 UNICODE string support see
    # https://learn.microsoft.com/en-us/cpp/text/unicode-programming-summary?view=msvc-170
    # and https://learn.microsoft.com/en-us/windows/win32/learnwin32/working-with-strings
    target_compile_definitions(Starter PUBLIC _UNICODE UNICODE)
endif()

if (MSVC)
    target_compile_options(Starter PUBLIC /W3)
else()
    target_compile_options(Starter PUBLIC -Wall -Wextra -D_FORTIFY_SOURCE=2 -O1)

    if(NOT (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang"))
        target_compile_options(Starter PUBLIC -fpie)
        set_target_properties(Starter PROPERTIES LINK_FLAGS "-Wl,-z,now -pie")
    else()
        set_target_properties(Starter PROPERTIES LINK_FLAGS "-bind_at_load")
    endif()
endif()

install(TARGETS Starter
        RUNTIME DESTINATION "${CMAKE_INSTALL_FULL_BINDIR}")

option(TANGO_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF)

if(TANGO_WARNINGS_AS_ERRORS)
    if (MSVC)
      target_compile_options(Starter PUBLIC /WX)
    else()
      target_compile_options(Starter PUBLIC -Werror -Wformat -Werror=format-security -pedantic)
    endif()
endif()
