cmake_minimum_required(VERSION 3.22)

#
# This file is generated only once,
# and is not re-generated if converter is called multiple times.
#
# User is free to modify the file as much as necessary
#

# Setup compiler settings
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS ON)


# Define the build type
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE "Debug")
endif()

# Set the project name
set(CMAKE_PROJECT_NAME gebrabit_adv17_boot)

# Chapter 17: CubeMX regenerates STM32F303XX_FLASH.ld and drops the
# chapter's regions and ASSERTs; the result would still link. Stop here.
file(READ ${CMAKE_SOURCE_DIR}/STM32F303XX_FLASH.ld _gb_ld)
if(NOT _gb_ld MATCHES "Chapter 17: layout checks")
    message(FATAL_ERROR "STM32F303XX_FLASH.ld is not the chapter-17 version "
            "(regenerated by CubeMX?). Restore it from STM32F303XX_FLASH.ld.ch17")
endif()

# Include toolchain file
include("cmake/gcc-arm-none-eabi.cmake")

# Enable compile command to ease indexing with e.g. clangd
set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE)

# Core project settings
project(${CMAKE_PROJECT_NAME})
message("Build type: " ${CMAKE_BUILD_TYPE})

# Enable CMake support for ASM and C languages
enable_language(C ASM)

# Create an executable object type
add_executable(${CMAKE_PROJECT_NAME})

# Add STM32CubeMX generated sources
add_subdirectory(cmake/stm32cubemx)

# Link directories setup
target_link_directories(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user defined library search paths
)

# Add sources to executable
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user sources here
    Core/Src/cobs.c
    Core/Src/frame.c
    Core/Src/ringbuf.c
    Core/Src/proto_cmd.c
    Core/Src/proto_port.c
    # chapter 17
    Core/Src/image.c
    Core/Src/boot_cmd.c
    Core/Src/boot_port.c
)

# Add include paths
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user defined include paths
)

# Add project symbols (macros)
target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user defined symbols
    # Chapter 17: no printf in the bootloader (size); no per-frame ITM trace.
    PROTO_TRACE=0
)

# Chapter 17: binary and Intel-HEX next to the ELF, plus the size report.
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
    COMMAND ${CMAKE_OBJCOPY} -O ihex $<TARGET_FILE:${CMAKE_PROJECT_NAME}> ${CMAKE_PROJECT_NAME}.hex
    COMMAND ${CMAKE_OBJCOPY} -O binary $<TARGET_FILE:${CMAKE_PROJECT_NAME}> ${CMAKE_PROJECT_NAME}.bin
    COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${CMAKE_PROJECT_NAME}>
    VERBATIM)

# Add linked libraries
target_link_libraries(${CMAKE_PROJECT_NAME}
    stm32cubemx

    # Add user defined libraries
)

# Chapter 17: in Debug the bootloader's own code stays at -O0, but the HAL
# library is compiled with -Os (last -O wins). Debug image: about 30 KB with
# everything at -O0 (93 % of the 32 KB region), about 21 KB with this line.
target_compile_options(STM32_Drivers PRIVATE $<$<CONFIG:Debug>:-Os>)
