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_app)

# Chapter 17: which firmware and which slot this build is for.
#   cmake --preset Release -DAPP_VERSION=2 -DAPP_SLOT=B
set(APP_VERSION "1" CACHE STRING "Application version 1 or 2 (major number)")
set_property(CACHE APP_VERSION PROPERTY STRINGS 1 2)
set(APP_SLOT "A" CACHE STRING "Slot the image is linked for: A (0x08008000) or B (0x08014000)")
set_property(CACHE APP_SLOT PROPERTY STRINGS A B)
option(APP_BAD "Broken test image: never confirms, resets after 3 s (rollback demo)" OFF)

if(APP_SLOT STREQUAL "A")
    set(APP_SLOT_BASE 0x08008000)    # FL_SLOT_A_BASE in Core/Inc/flash_layout.h
elseif(APP_SLOT STREQUAL "B")
    set(APP_SLOT_BASE 0x08014000)    # FL_SLOT_B_BASE
else()
    message(FATAL_ERROR "APP_SLOT must be A or B")
endif()
if(NOT APP_VERSION MATCHES "^[12]$")
    message(FATAL_ERROR "APP_VERSION must be 1 or 2")
endif()
set(APP_SLOT_SIZE 0xC000)            # FL_SLOT_SIZE (48 KB)

# 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)

# Chapter 17: slot memory regions for the linker script (INCLUDE gb_slot_memory.ld).
math(EXPR _flash_org "${APP_SLOT_BASE} + 0x200" OUTPUT_FORMAT HEXADECIMAL)
math(EXPR _flash_len "${APP_SLOT_SIZE} - 0x200 - 32" OUTPUT_FORMAT HEXADECIMAL)
math(EXPR _trl_org "${APP_SLOT_BASE} + ${APP_SLOT_SIZE} - 32" OUTPUT_FORMAT HEXADECIMAL)
file(WRITE ${CMAKE_BINARY_DIR}/gb_slot_memory.ld
"/* Generated by CMakeLists.txt: APP_SLOT=${APP_SLOT} */
HDR (r)        : ORIGIN = ${APP_SLOT_BASE}, LENGTH = 0x200
FLASH (rx)     : ORIGIN = ${_flash_org}, LENGTH = ${_flash_len}
TRAILER (r)    : ORIGIN = ${_trl_org}, LENGTH = 32
")
set_property(TARGET ${CMAKE_PROJECT_NAME} APPEND PROPERTY LINK_DEPENDS
    ${CMAKE_BINARY_DIR}/gb_slot_memory.ld ${CMAKE_SOURCE_DIR}/STM32F303XX_FLASH.ld)

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

# Add sources to executable
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
    # Add user sources here
    Core/Src/dbg_trace.c
    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/app_image.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
    # USART1 carries the binary protocol: printf must NOT go to USART1.
    DBG_OUTPUTS=DBG_OUT_ITM
    # chapter 17
    PROTO_TRACE=0
    APP_VER_MAJOR=${APP_VERSION}
    APP_VER_MINOR=0
    APP_VER_PATCH=0
    APP_SLOT_BASE=${APP_SLOT_BASE}UL
    APP_SLOT_NAME="${APP_SLOT}"
    APP_BAD=$<IF:$<BOOL:${APP_BAD}>,1,0>
)

# Chapter 17: fill size + CRC into the header (ELF updated in place), then
# write <name>_v<ver>_<slot>.bin/.hex for the update tool and for SWD.
find_package(Python3 REQUIRED COMPONENTS Interpreter)
if(APP_BAD)
    set(_sfx "_bad")
endif()
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
    COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/sign_image.py
            --elf $<TARGET_FILE:${CMAKE_PROJECT_NAME}>
            --objcopy ${CMAKE_OBJCOPY}
            --slot-base ${APP_SLOT_BASE}
            --out ${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}_v${APP_VERSION}_${APP_SLOT}${_sfx}
    COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${CMAKE_PROJECT_NAME}>
    VERBATIM)

# Add linked libraries
target_link_libraries(${CMAKE_PROJECT_NAME}
    stm32cubemx

    # Add user defined libraries
)
