project ( "IoTManagedIntegrations-End-Device unit test"
          VERSION 1.0.0
          LANGUAGES C )

add_compile_options(-g -O0)



# Allow the project to be organized into folders.
set_property( GLOBAL PROPERTY USE_FOLDERS ON )

# option to build coverity result
option(IOTMI_EMBEDDED_SDK_COVERITY "Build coverity" OFF)

# Use C99 if not specified.
if( NOT DEFINED CMAKE_C_STANDARD )
    set( CMAKE_C_STANDARD 99 )
endif()
if( NOT DEFINED CMAKE_C_STANDARD_REQUIRED )
    set( CMAKE_C_STANDARD_REQUIRED ON )
endif()

# Do not allow in-source build.
if( ${PROJECT_SOURCE_DIR} STREQUAL ${PROJECT_BINARY_DIR} )
    message( FATAL_ERROR "In-source build is not allowed. Please build in a separate directory, such as ${PROJECT_SOURCE_DIR}/build." )
endif()

# Set global path variables.
get_filename_component(__MODULE_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE)
set(MODULE_ROOT_DIR ${__MODULE_ROOT_DIR} CACHE INTERNAL "SDK repository root.")

# Configure options to always show in CMake GUI.
option( BUILD_CLONE_SUBMODULES
        "Set this to ON to automatically clone any required Git submodules. When OFF, submodules must be manually cloned."
        OFF )

# Set output directories.
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )
set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )

#  ====================================  Test Configuration ========================================

# Define a CMock resource path.
set( CMOCK_DIR ${MODULE_ROOT_DIR}/test/unit-test/CMock CACHE INTERNAL "CMock library source directory." )

# Include CMock build configuration.
include( unit-test/cmock_build.cmake )

# Check if the CMock source directory exists, and if not present, clone the submodule
# if BUILD_CLONE_SUBMODULES configuration is enabled.
if( NOT EXISTS ${CMOCK_DIR}/src )
    # Attempt to clone CMock.
    if( ${BUILD_CLONE_SUBMODULES} )
        clone_cmock()
    else()
        message( FATAL_ERROR "The required submodule CMock does not exist. Either clone it manually, or set BUILD_CLONE_SUBMODULES to 1 to automatically clone it during build." )
    endif()
endif()

# Add unit test and coverage configuration.

# Use CTest utility for managing test runs. This has to be added BEFORE
# defining test targets with add_test()
enable_testing()

# Add build targets for CMock and Unit, required for unit testing.
add_cmock_targets()

# Add function to enable CMock based tests and coverage.
include( ${MODULE_ROOT_DIR}/tools/cmock/create_test.cmake )

# Include build configuration for unit tests.
add_subdirectory( unit-test )

# Include build configuration for integration tests.
add_subdirectory( integration-test )

#  ==================================== Coverage Analysis configuration ========================================

# Add a target for running coverage on tests.
add_custom_target( coverage
    COMMAND ${CMAKE_COMMAND} -DCMOCK_DIR=${CMOCK_DIR}
    -P ${MODULE_ROOT_DIR}/tools/cmock/coverage.cmake
    DEPENDS
        cmock
        unity
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
)

#  ==================================== CPPCHECK Analysis configuration ========================================
find_program(CPPCHECK cppcheck)

# Check if CPPCHECK and ${CMAKE_CURRENT_LIST_DIR}/cppcheck-folder-list.txt exist
if(CPPCHECK AND EXISTS "${CMAKE_CURRENT_LIST_DIR}/cppcheck-folder-list.txt")
    file(STRINGS ${CMAKE_CURRENT_LIST_DIR}/cppcheck-folder-list.txt FOLDER_LIST)

    # Append base path to each item
    set(CPPCHECK_FOLDER_LIST "")
    foreach(FOLDER ${FOLDER_LIST})
        list(APPEND CPPCHECK_FOLDER_LIST "${IOTMI_EMBEDDED_C_TOP_DIR}/${FOLDER}")
    endforeach()

    add_custom_target(cppcheck
        COMMAND ${CPPCHECK}
            --enable=all,style,warning,performance,portability,information
            --check-level=exhaustive
            --suppress=unusedFunction
            --suppress=missingInclude
            --suppress=variableScope
            --suppress=missingIncludeSystem
            --suppress=constParameterCallback
            --suppress=constVariablePointer
            --suppress=constParameterPointer
            --error-exitcode=1
            ${CPPCHECK_FOLDER_LIST}
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        COMMENT "Running cppcheck static analysis..."
        DEPENDS "${CMAKE_CURRENT_LIST_DIR}/cppcheck-folder-list.txt"
    )
endif()

############################################################
# Coverity Configuration
############################################################
# Enable IOTMI_EMBEDDED_SDK_COVERITY to handle the coverity.

if(IOTMI_EMBEDDED_SDK_COVERITY)

find_program(COV_BUILD cov-build)
find_program(COV_ANALYZE cov-analyze)
find_program(COV_FORMAT cov-format-errors)

# Get number of logical cores using cmake_host_system_information
cmake_host_system_information(RESULT PROCESSOR_COUNT QUERY NUMBER_OF_LOGICAL_CORES)
if(PROCESSOR_COUNT EQUAL 0)
    set(PROCESSOR_COUNT 1)
endif()

if(COV_BUILD AND COV_ANALYZE AND COV_FORMAT)
    if(IOTMI_EMBEDDED_SDK_BUILD_WITH_MQTT_PROXY)
        set(COVERAGE_SOURCE_DIR "${CMAKE_BINARY_DIR}/control/IoTSmartHomeDevice-Embedded-C")
    else ()
        set(COVERAGE_SOURCE_DIR ${CMAKE_BINARY_DIR})
    endif ()
    # Directory for Coverity intermediate files
    set(COVERITY_DIR "${CMAKE_BINARY_DIR}/coverity_report")

    # Clean Coverity directory
    add_custom_target(coverity_clean_dir
        COMMAND ${CMAKE_COMMAND} -E remove_directory ${COVERITY_DIR}
        COMMAND ${CMAKE_COMMAND} -E make_directory ${COVERITY_DIR}
        COMMENT "Cleaning Coverity directory..."
    )

    # Clean build
    add_custom_target(coverity_clean
        COMMAND ${CMAKE_COMMAND} --build ${COVERAGE_SOURCE_DIR} --target clean
        WORKING_DIRECTORY ${COVERAGE_SOURCE_DIR}
        COMMENT "Running Coverity clean..."
        DEPENDS coverity_clean_dir
    )

    # Individual Coverity targets
    add_custom_target(coverity_build
        COMMAND ${COV_BUILD} --dir ${COVERAGE_SOURCE_DIR} ${CMAKE_COMMAND} --build ${COVERAGE_SOURCE_DIR} -j ${PROCESSOR_COUNT}
        WORKING_DIRECTORY ${COVERAGE_SOURCE_DIR}
        COMMENT "Running Coverity build..."
        DEPENDS coverity_clean
    )

    add_custom_target(coverity_analyze
        COMMAND ${COV_ANALYZE}
            --disable-parse-warnings
            --dir ${COVERAGE_SOURCE_DIR}
            --all
            --aggressiveness-level high
            --tu-pattern \"file\(\'./src/iotmi_.*|./components/.*/iotmi_.*c$$|./components/mqtt_adapter/.*\'\)\"
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
        DEPENDS coverity_build
    )

    add_custom_target(coverity_report
        COMMAND ${COV_FORMAT}
            --dir ${COVERAGE_SOURCE_DIR}
            --html-output ${COVERITY_DIR}
        WORKING_DIRECTORY ${COVERAGE_SOURCE_DIR}
        COMMENT "Generating Coverity report..."
        DEPENDS coverity_analyze
    )

    # Meta-target that runs all Coverity steps
    add_custom_target(coverity_scan DEPENDS coverity_report)

    message(STATUS "Coverity targets configured successfully")
else()
    message(WARNING "Coverity tools not found. Coverity targets will not be available.")
endif()

endif()
