# Host (PC) build of the hardware-independent firmware modules + Unity tests.
# GebraBit advanced STM32 course, chapter 18 (unit tests and CI).
#
#   cmake -S . -B build/host -G Ninja [-DENABLE_COVERAGE=ON]
#   cmake --build build/host
#   ctest --test-dir build/host --output-on-failure
#   cmake --build build/host --target coverage    (needs ENABLE_COVERAGE=ON + gcovr)
#   cmake --build build/host --target lint        (cppcheck, chapter-3 settings)
#
# The firmware itself (firmware/, arm-none-eabi-gcc) is a separate CMake
# project with its own presets; this file never uses the cross compiler.
cmake_minimum_required(VERSION 3.22)
project(gebrabit_adv18_ci_host LANGUAGES C)

if(CMAKE_CROSSCOMPILING)
  message(FATAL_ERROR "This is the host test build. Build the firmware in firmware/ with its presets.")
endif()

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE Debug)
endif()

option(ENABLE_COVERAGE "Compile and link everything with --coverage (gcov)" OFF)
if(ENABLE_COVERAGE)
  if(NOT CMAKE_C_COMPILER_ID STREQUAL "GNU")
    message(FATAL_ERROR "ENABLE_COVERAGE needs gcc (gcov); found ${CMAKE_C_COMPILER_ID}")
  endif()
  # -O0: line/branch numbers match the source; -fprofile-abs-path: .gcno
  # files hold absolute paths, so gcov finds the sources from any directory.
  add_compile_options(--coverage -O0 -g -fprofile-abs-path)
  add_link_options(--coverage)
endif()

# Warnings for production code and tests (same as the chapters' host tests).
set(STRICT_WARNINGS -Wall -Wextra -Werror)

include(CTest)          # calls enable_testing(), adds BUILD_TESTING option

# ---------------------------------------------------------------------------
# Unity (vendored, v2.7.0, MIT): one static library, built once.
# Default config: float assertions ON, double OFF, 64-bit ON on this host.
# ---------------------------------------------------------------------------
add_library(unity STATIC third_party/unity/unity.c)
target_include_directories(unity PUBLIC third_party/unity)

# ---------------------------------------------------------------------------
# Production code, compiled ONCE per library and linked into the tests.
# Sources are byte-identical copies of chapters 10, 14 and 15 (see
# tools/check_copies.sh); none of them includes a HAL header.
# ---------------------------------------------------------------------------
add_library(proto STATIC
  src/proto/cobs.c src/proto/frame.c src/proto/ringbuf.c src/proto/proto_cmd.c)
target_include_directories(proto PUBLIC src/proto)
target_compile_options(proto PRIVATE ${STRICT_WARNINGS})

add_library(fsm STATIC
  src/fsm/hsm.c src/fsm/event.c src/fsm/fsm_table.c src/fsm/button_fsm.c
  src/fsm/device_hsm.c src/fsm/led_pattern.c)
target_include_directories(fsm PUBLIC src/fsm)
target_compile_options(fsm PRIVATE ${STRICT_WARNINGS})

add_library(flashlog STATIC src/flashlog/log_store.c)
target_include_directories(flashlog PUBLIC src/flashlog)
target_compile_options(flashlog PRIVATE ${STRICT_WARNINGS})

# ---------------------------------------------------------------------------
# Test doubles. fake_hal provides stm32f3xx_hal.h + HAL_GetTick/ReadPin.
# button_port.c (the only HAL user in src/) is built against the fake here
# and against the real HAL in the firmware cross-compile check.
# ---------------------------------------------------------------------------
add_library(fake_hal STATIC tests/fakes/fake_hal.c)
target_include_directories(fake_hal PUBLIC tests/fakes)
target_compile_options(fake_hal PRIVATE ${STRICT_WARNINGS})

add_library(button_port STATIC src/port/button_port.c)
target_include_directories(button_port PUBLIC src/port)
target_link_libraries(button_port PUBLIC fsm fake_hal)
target_compile_options(button_port PRIVATE ${STRICT_WARNINGS})

add_library(fake_nor STATIC tests/fakes/fake_nor_flash.c)
target_include_directories(fake_nor PUBLIC tests/fakes)
target_link_libraries(fake_nor PUBLIC flashlog)
target_compile_options(fake_nor PRIVATE ${STRICT_WARNINGS})

add_library(test_support STATIC tests/support/vectors.c)
target_include_directories(test_support PUBLIC tests/support)
target_compile_options(test_support PRIVATE ${STRICT_WARNINGS})

# ---------------------------------------------------------------------------
# One executable per test file = one CTest test. Labels select groups:
#   ctest --test-dir build/host -L proto
# ---------------------------------------------------------------------------
function(add_unity_test name label)
  add_executable(${name} tests/${name}.c)
  target_link_libraries(${name} PRIVATE ${ARGN} unity)
  target_compile_options(${name} PRIVATE ${STRICT_WARNINGS})
  add_test(NAME ${name} COMMAND ${name} ${TEST_ARGS_${name}})
  set_tests_properties(${name} PROPERTIES LABELS "${label}" TIMEOUT 30)
  set_property(GLOBAL APPEND PROPERTY UNITY_TEST_TARGETS ${name})
endfunction()

set(TEST_ARGS_test_frame_crc ${CMAKE_CURRENT_SOURCE_DIR}/tests/vectors/vectors.txt)

add_unity_test(test_cobs        "proto"           proto)
add_unity_test(test_frame_crc   "proto;vectors"   proto test_support)
add_unity_test(test_ringbuf     "proto"           proto)
add_unity_test(test_proto_cmd   "proto"           proto)
add_unity_test(test_hsm         "fsm"             fsm)
add_unity_test(test_button_port "fsm;hal-double"  button_port)
add_unity_test(test_log_store   "flashlog"        fake_nor)

# ---------------------------------------------------------------------------
# coverage: fresh counters -> run all tests -> gcovr text + HTML report.
# ---------------------------------------------------------------------------
if(ENABLE_COVERAGE)
  find_program(GCOVR_EXE NAMES gcovr)
  if(GCOVR_EXE)
    set(COV_DIR ${CMAKE_BINARY_DIR}/coverage)
    set(COV_MIN_LINE 0 CACHE STRING "Fail the coverage target below this line coverage in percent (0 = no gate)")
    set(COV_GATE "")
    if(COV_MIN_LINE GREATER 0)
      set(COV_GATE --fail-under-line ${COV_MIN_LINE})
    endif()
    add_custom_target(coverage
      COMMAND ${CMAKE_COMMAND} -DDIR=${CMAKE_BINARY_DIR} -P ${CMAKE_SOURCE_DIR}/cmake/clean_gcda.cmake
      COMMAND ${CMAKE_CTEST_COMMAND} --test-dir ${CMAKE_BINARY_DIR} --output-on-failure
      COMMAND ${CMAKE_COMMAND} -E make_directory ${COV_DIR}
      COMMAND ${GCOVR_EXE}
              --root ${CMAKE_SOURCE_DIR}
              --filter ${CMAKE_SOURCE_DIR}/src/
              --txt ${COV_DIR}/coverage.txt --txt-metric line --txt-metric branch
              --html-details ${COV_DIR}/index.html
              --html-title "GebraBit adv18 host tests"
              --json-summary ${COV_DIR}/summary.json
              --print-summary
              ${COV_GATE}
              ${CMAKE_BINARY_DIR}
      WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
      COMMENT "Running tests and writing ${COV_DIR}/index.html"
      VERBATIM)
    get_property(_tests GLOBAL PROPERTY UNITY_TEST_TARGETS)
    add_dependencies(coverage ${_tests})      # build the tests first
  else()
    message(WARNING "gcovr not found: no 'coverage' target (pip install gcovr)")
  endif()
endif()

# ---------------------------------------------------------------------------
# lint: cppcheck with the chapter-3 options and suppression file, on src/.
# --platform=arm32-wchar_t4 makes cppcheck assume the Cortex-M type sizes
# although the compile database comes from the PC build.
# ---------------------------------------------------------------------------
find_program(CPPCHECK_EXE NAMES cppcheck)
if(CPPCHECK_EXE)
  set(CPPCHECK_COMMON
      --project=${CMAKE_BINARY_DIR}/compile_commands.json
      -D__GNUC__
      --std=c11
      --platform=arm32-wchar_t4
      --enable=warning,style,performance,portability
      --inline-suppr
      --quiet
      -i${CMAKE_SOURCE_DIR}/third_party
      -i${CMAKE_SOURCE_DIR}/tests
      --suppressions-list=${CMAKE_SOURCE_DIR}/tools/cppcheck-suppressions.txt
      --suppressions-list=${CMAKE_SOURCE_DIR}/tools/cppcheck-suppressions-adv18.txt)
  add_custom_target(lint
    COMMAND ${CPPCHECK_EXE} ${CPPCHECK_COMMON} --error-exitcode=1
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    COMMENT "cppcheck on src/ (third_party and tests excluded)"
    VERBATIM)
  add_custom_target(lint-misra
    COMMAND ${CPPCHECK_EXE} ${CPPCHECK_COMMON} --addon=${CMAKE_SOURCE_DIR}/tools/misra.json
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    COMMENT "cppcheck + MISRA C:2012 addon (report only)"
    VERBATIM)
endif()
