option(LCOV "use lcov for code coverage (not compatible MSVC), if available" OFF)

if (COVERAGE_FLAGS AND LCOV AND (NOT MSVC))
    find_program(LCOV_EXEC "lcov")
    find_program(GENHTML_EXEC "genhtml")
    if(LCOV_EXEC AND GENHTML_EXEC)
        message(STATUS "Using lcov")
        include(${PROJECT_SOURCE_DIR}/cmake/tools/test_helper.cmake)
        execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ./lcov/ WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
        string(REPLACE " " "%20" url_root_path "${CMAKE_BINARY_DIR}")
        if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|Intel")
            add_compile_options(-fprofile-arcs -ftest-coverage)
            add_link_options(-fprofile-arcs -ftest-coverage)
        endif()
        add_custom_command(TARGET run_coverage COMMAND echo && echo "-- Lcov:" && "${LCOV_EXEC}" --capture --no-external --directory "${CMAKE_BINARY_DIR}" --base-directory "${PROJECT_SOURCE_DIR}" --output-file "${CMAKE_BINARY_DIR}/coverage.info" && "${LCOV_EXEC}" --remove "${CMAKE_BINARY_DIR}/coverage.info" "${PROJECT_SOURCE_DIR}/external/*" --output-file "${CMAKE_BINARY_DIR}/coverage.info" && "${GENHTML_EXEC}" "${CMAKE_BINARY_DIR}/coverage.info" --output-directory "${CMAKE_BINARY_DIR}/lcov/" && echo "HTML Summary: file://${url_root_path}/lcov/index.html")
    else()
        if (NOT LCOV_EXEC)
            find_program(HAS_APT "apt")
            if(HAS_APT)
                message(WARNING "Requested lcov, but it was not found. You can install it using:\nsudo apt install lcov\n")
            else()
                message(WARNING "Requested lcov, but it was not found. You can install it from here:\nhttps://github.com/linux-test-project/lcov\n")
            endif()
        else()
            find_program(HAS_APT "apt")
            if(HAS_APT)
                message(WARNING "Requested lcov, but it requires genhtml which was not found. You can install it using:\nsudo apt install lcov\n")
            else()
                message(WARNING "Requested lcov, but it requires genhtml which was not found. You can install it from here:\nhttps://github.com/linux-test-project/lcov\n")
            endif()
        endif()
    endif()
endif()
