cmake_minimum_required(VERSION 3.22)
project(bootloader)

set(SRC_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../src/)
set(COMMON ${SRC_ROOT}/common)
set(CRYPTO ${SRC_ROOT}/cyclone_crypto)
set(BOOT ${SRC_ROOT}/cyclone_boot)
set(THIRD_PARTY ${CMAKE_SOURCE_DIR}/../../../../../third_party)

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

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

# Enable compile command to ease indexing with e.g. clangd
set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE)
message("Build type: " ${CMAKE_BUILD_TYPE})

add_executable(bootloader)

target_sources(bootloader PRIVATE
        ${COMMON}/cpu_endian.c
        ${COMMON}/os_port_none.c
        ${COMMON}/date_time.c
        ${BOOT}/core/crc32.c
        ${BOOT}/core/mailbox.c
        ${BOOT}/drivers/mcu_core/sam_ed_5x_mcu_driver.c
        ${BOOT}/drivers/flash/internal/sam_ed_5x_flash_driver.c
        ${BOOT}/modules/image/image.c
        ${BOOT}/modules/memory/memory.c
        ${BOOT}/modules/security/cipher.c
        ${BOOT}/bootloader/second_stage/boot.c
        ${BOOT}/bootloader/second_stage/boot_fallback.c
        ${BOOT}/bootloader/second_stage/boot_common.c

        ${CRYPTO}/hash/sha256.c
        ${CRYPTO}/cipher/aes.c

        ${CMAKE_SOURCE_DIR}/cmake/startup_same54.c
        ${CMAKE_SOURCE_DIR}/cmake/syscalls.c
        ${CMAKE_SOURCE_DIR}/src/system_same54.c
        ${CMAKE_SOURCE_DIR}/src/main.c
        ${CMAKE_SOURCE_DIR}/src/debug.c
)

target_include_directories(bootloader PRIVATE
        ${CMAKE_SOURCE_DIR}/src
        ${THIRD_PARTY}/cmsis/include
        ${THIRD_PARTY}/microchip/devices/same54
        ${THIRD_PARTY}/microchip/boards/same54_xplained_pro
        ${COMMON}
        ${CRYPTO}
        ${BOOT}
        ${BOOT}/modules
        ${BOOT}/bootloader
)

target_compile_definitions(bootloader PRIVATE
    __SAME54P20A__
    USE_CMSIS_INIT
    USE_SAME54_XPLAINED_PRO
    __USE_C99_MATH

    $<$<CONFIG:Debug>:DEBUG>
)

# Add the map file to the list of files to be removed with 'clean' target
set_target_properties(bootloader PROPERTIES ADDITIONAL_CLEAN_FILES ${CMAKE_PROJECT_NAME}.map)

# Convert .elf to .bin
add_custom_command(TARGET bootloader POST_BUILD
        COMMAND ${CMAKE_OBJCOPY} -O binary
        ${CMAKE_CURRENT_BINARY_DIR}/bootloader.elf
        ${CMAKE_CURRENT_BINARY_DIR}/bootloader.bin
        COMMENT "Generating binary file from ELF"
)

# Copy the generated .bin file to ../
add_custom_command(TARGET bootloader POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy
            ${CMAKE_CURRENT_BINARY_DIR}/bootloader.bin
            ${CMAKE_CURRENT_SOURCE_DIR}/../
    COMMENT "Copying bootloader.bin to parent directory"
)
