set(LIBOPENCM3_DIR ${CMAKE_SOURCE_DIR}/libopencm3)

# Make sure that git submodule is initialized and updated
if (NOT EXISTS ${LIBOPENCM3_DIR}/Makefile)
    message(FATAL_ERROR "libopencm3 submodule not found. Initialize with 'git submodule update --init' in the source directory")
endif()

add_custom_target(
    libopencm3
    COMMAND make -C "${LIBOPENCM3_DIR}" "TARGETS=stm32/f2" "lib/stm32/f2"
)

execute_process(
    COMMAND scripts/genlink.py ld/devices.data stm32f207vet6 DEFS
    WORKING_DIRECTORY ${LIBOPENCM3_DIR}
    OUTPUT_VARIABLE GENLINK_DEFS
)
separate_arguments(GENLINK_DEFS)

add_custom_target(
    linker_script
    COMMAND gcc ${GENLINK_DEFS} -P -E ${LIBOPENCM3_DIR}/ld/linker.ld.S -o ${CMAKE_CURRENT_BINARY_DIR}/f2/src/generated.linker.ld
    COMMENT "Generate linker script"
    VERBATIM
)