# see CMakeLists.txt for the first exercise for more on CMake

# Here, we require newer CMake so we can use FetchContents
cmake_minimum_required(VERSION 3.12..3.18)

project(Exercise02
    VERSION 1.0
    LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# get Catch2
Include(FetchContent)

FetchContent_Declare(
    Catch2
    GIT_REPOSITORY https://github.com/catchorg/Catch2.git
    GIT_TAG        v2.13.1)
FetchContent_GetProperties(Catch2)
# IMPORTANT NONE: the name of the dependency is lowercase in cmake variables,
# even if it was declared otherwise
if(NOT catch2_POPULATED)
	FetchContent_Populate(Catch2)
    add_subdirectory(${catch2_SOURCE_DIR} ${catch2_BINARY_DIR})
endif()

# Explcitly enable colors in GCC/Clang – this is mainly important for the Ninja
# builds (with makefiles the compiler is able to autodetect if it runs on
# terminal)
set(COLORS "")
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
	set(COLORS "-fdiagnostics-color=always")
endif()



# We have two exercises with same structure, just define a function that
# instatiates a parametric and then invoke it twice. CMake is a code and we
# should write it like that – including avoiding code duplication
function( add_exercise name )

    add_executable(${name}-test ${name}.cpp)
    target_compile_options(${name}-test PRIVATE -Wall -Wextra -pedantic ${COLORS})

    if(EXAMPLE_SOLUTION)
        target_compile_definitions(${name}-test PRIVATE EXAMPLE_SOLUTION)
    endif()
    if(NOT EXISTS ${CMAKE_SOURCE_DIR}/${name}.h)
        message(WARNING "Compiling with the teacher's solution")
        target_compile_definitions(${name}-test PRIVATE EXAMPLE_SOLUTION)
    endif()

    target_link_libraries(${name}-test Catch2::Catch2)

    # add a target that acutually runs the tests, include it in ALL so it runs by default
    add_custom_target(${name}-run-test ALL ./${name}-test --use-colour yes
                      DEPENDS ${name}-test
                      COMMENT "Running tests for [${name}]"
                      WORKING_DIRECTORY ${CMAKE_BUILD_DIR}
                      VERBATIM)
endfunction()

add_exercise(arrayset)
add_exercise(rpn)
