cmake_minimum_required(VERSION 3.20)

# 包含项目配置
include(${CMAKE_SOURCE_DIR}/cmake/project_config.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/project.cmake)

project(${PROJECT_NAME} LANGUAGES C CXX ASM)

# 添加SDK库
add_subdirectory(SDK/CMSIS)
add_subdirectory(SDK/GD32E23x_standard_peripheral)

# 业务代码源文件
set(TARGET_SRC
    # Core
    Src/gd32e23x_it.c
    Src/main.c
    Src/systick.c
    Src/system_gd32e23x.c

    # Startup
    SDK/CMSIS/startup/startup_gd32e23x.S
    
    # User
    Src/syscalls.c

    # Add new source files here
    Src/uart.c
    Src/led.c
    Src/uart_ring_buffer.c
    Src/command.c
    Src/i2c.c
    Src/ultrasonic_analog.c
)

# 设置输出目录
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/Application)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/Application)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/Application)

add_executable(${PROJECT_NAME} ${TARGET_SRC})
set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME Application)
project_add_target_properties(${PROJECT_NAME})

# 头文件路径
target_include_directories(${PROJECT_NAME} PRIVATE
    ${CMAKE_SOURCE_DIR}/Inc

    # Add new include directories here, e.g. ${CMAKE_SOURCE_DIR}/Application/User/Inc
    
)

# 链接脚本
target_link_options(${PROJECT_NAME} PRIVATE
    -T${CMAKE_SOURCE_DIR}/LD/gd32e23x_flash.ld -Xlinker
    -L${CMAKE_SOURCE_DIR}/LD
)

# 生成 map 文件等
target_link_options(${PROJECT_NAME} PRIVATE
    -Wl,-Map=${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Application.map
)

# 链接SDK库
target_link_libraries(${PROJECT_NAME} PRIVATE CMSIS)
target_link_libraries(${PROJECT_NAME} PRIVATE GD32E23x_standard_peripheral)

# 生成 bin/hex/list 文件名格式：[工程名_版本号_编译条件_编译日期]
set(OUTPUT_PREFIX "${PROJECT_NAME}_${VERSION}_${IIC_TYPE}_${BUILD_DATE}")

add_custom_command(TARGET ${PROJECT_NAME}
    POST_BUILD
    COMMAND echo -- Running Post Build Commands
    COMMAND ${CMAKE_OBJCOPY} -O ihex $<TARGET_FILE:${PROJECT_NAME}> ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_PREFIX}.hex
    COMMAND ${CMAKE_OBJCOPY} -O binary $<TARGET_FILE:${PROJECT_NAME}> ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_PREFIX}.bin
    COMMAND ${CMAKE_SIZE} $<TARGET_FILE:${PROJECT_NAME}>
    COMMAND ${CMAKE_OBJDUMP} -h -S $<TARGET_FILE:${PROJECT_NAME}> > ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_PREFIX}.list
    COMMAND ${CMAKE_SIZE} --format=berkeley $<TARGET_FILE:${PROJECT_NAME}> > ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_PREFIX}.bsz
    COMMAND ${CMAKE_SIZE} --format=sysv -x $<TARGET_FILE:${PROJECT_NAME}> > ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_PREFIX}.ssz
)

# =========================
# Tips for project maintainers:
# 1. If you add new source files (e.g. Src/my_module.c), add them to TARGET_SRC above.
# 2. If you add new header files or directories, add them to target_include_directories above.
# 3. If you add new SDK modules, use add_subdirectory(SDK/YourModule) and link with target_link_libraries.
# =========================