cmake_minimum_required(VERSION 3.20)

set(ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../..)
set(SYSTEM_DIR ${ROOT_DIR}/devices/eliot1)
set(ARM_GCC_DIR ${ROOT_DIR}/devices/eliot1/gcc)
set(DRIVERS_DIR ${ROOT_DIR}/devices/eliot1/drivers)
set(BOARD_CFG_DIR ${ROOT_DIR}/boards/eliot1m_mo_cfg)
set(BOARD_BSP_DIR ${BOARD_CFG_DIR}/armgcc/bsp_core0/build)

PROJECT(qspi)

set(SOURCES 
    ${CMAKE_CURRENT_SOURCE_DIR}/../main.c
    ${DRIVERS_DIR}/hal_qspi.c
    ${DRIVERS_DIR}/hal_qspi_nor_flash.c
    ${DRIVERS_DIR}/hal_dma.c
    ${DRIVERS_DIR}/hal_qspi_dma.c
)

add_compile_definitions("QSPI_USE_DMAC=1")

set_source_files_properties(${SOURCES} PROPERTIES LANGUAGE C)

function (add_post_build_actions target_name)
  add_custom_command(TARGET ${target_name} POST_BUILD
    COMMAND ${CMAKE_OBJCOPY} -O binary "$<TARGET_FILE:${target_name}>" ${target_name}.bin
    COMMENT "[post] Create Flash Image ${target_name}.bin"
    )

  add_custom_command(TARGET ${target_name} POST_BUILD
    COMMAND ${CMAKE_OBJDUMP} -D "$<TARGET_FILE:${target_name}>" > ${target_name}.dis
    COMMENT "[post] Create disassemble file ${target_name}.dis"
    )

  add_custom_command(TARGET ${target_name} POST_BUILD
    COMMAND ${CMAKE_READELF} -S "$<TARGET_FILE:${target_name}>"
    COMMENT "[post] Show sections of file ${target_name}.elf"
    )
endfunction()

add_executable(${PROJECT_NAME}.elf
    ${SOURCES}
)

include_directories(
    ${ROOT_DIR}/CMSIS/Include
    ${ROOT_DIR}/devices/eliot1
    ${DRIVERS_DIR}
    ${DRIVERS_DIR}/private
    ${BOARD_CFG_DIR}
)

target_link_directories(${PROJECT_NAME}.elf PUBLIC ${BOARD_BSP_DIR})
target_link_libraries(${PROJECT_NAME}.elf bsp_core0)
SET (CMAKE_EXE_LINKER_FLAGS "-fdata-sections -ffunction-sections -Wl,--gc-sections -T../armgcc/eliot1_cm33_core0_ram_custom.ld")
SET (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DBOARD -DELIOT1M -DCPU_ELIOT1M_cm33_core0 -Os -g -fdata-sections -ffunction-sections")

add_post_build_actions(${PROJECT_NAME}.elf)
