# Common sources / PIO / defines / libs (extracted so we don't repeat)
set(APP_COMMON_SOURCES
    ${pZ80_common_src}
    ${pZ80_drivers_sharp_src}
    ${model_common_src}
    main.c
)

if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/version.txt")
    file(STRINGS "${CMAKE_CURRENT_LIST_DIR}/version.txt" PROJECT_VER)
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_LIST_DIR}/version.txt")
endif()

string(TIMESTAMP PROJECT_DATE "%d/%m/%Y")

set(APP_COMMON_DEFINES
    ${model_common_defines}
    USE_STDIO
    INCLUDE_SHARP_DRIVERS
    DEBUG
    PROJECT_VER=${PROJECT_VER}
    PROJECT_DATE="${PROJECT_DATE}"
)

# Partition 1 — normal / default slot (0x10020000 = +128 KiB offset due to Bootloader)

add_executable(BaseZ80_0x10020000 ${APP_COMMON_SOURCES})

# PIO header generation — do it here, now that BaseZ80_0x10020000 exists
pico_generate_pio_header(BaseZ80_0x10020000 ${z80_pio})
#    ↑ attached to _a — but the generated header is visible/usable by both

target_compile_definitions(BaseZ80_0x10020000 PRIVATE
    ${APP_COMMON_DEFINES}
)

target_link_libraries(BaseZ80_0x10020000
    ${pZ80_common_libs}
    hardware_pio          # usually needed if using PIO
)

target_link_options(BaseZ80_0x10020000 PRIVATE
    -Wl,--no-gc-sections,--print-memory-usage
)

pico_enable_stdio_usb(BaseZ80_0x10020000 0)
pico_enable_stdio_uart(BaseZ80_0x10020000 0)

pico_set_linker_script(BaseZ80_0x10020000 ${CMAKE_CURRENT_SOURCE_DIR}/main_memmap_partition_1.ld)

pico_add_hex_output(BaseZ80_0x10020000)
pico_add_bin_output(BaseZ80_0x10020000)
pico_add_map_output(BaseZ80_0x10020000)

# Partition 2 — second slot (0x10520000 = +5 MiB + 128 KiB)

add_executable(BaseZ80_0x10520000 ${APP_COMMON_SOURCES})

# PIO header generation — do it here, now that BaseZ80_0x10520000 exists
pico_generate_pio_header(BaseZ80_0x10520000 ${z80_pio})
#    ↑ attached to _a — but the generated header is visible/usable by both

target_compile_definitions(BaseZ80_0x10520000 PRIVATE
    ${APP_COMMON_DEFINES}
    # Optional: FLASH_SLOT=B
)

target_link_libraries(BaseZ80_0x10520000
    ${pZ80_common_libs}
    hardware_pio
)

target_link_options(BaseZ80_0x10520000 PRIVATE
    -Wl,--no-gc-sections,--print-memory-usage
)

pico_enable_stdio_usb(BaseZ80_0x10520000 0)
pico_enable_stdio_uart(BaseZ80_0x10520000 0)

pico_set_linker_script(BaseZ80_0x10520000 ${CMAKE_CURRENT_SOURCE_DIR}/main_memmap_partition_2.ld)

pico_add_hex_output(BaseZ80_0x10520000)
pico_add_bin_output(BaseZ80_0x10520000)
pico_add_map_output(BaseZ80_0x10520000)

# Fake target to always increment the version number on each build.
add_custom_target(basez80_version ALL DEPENDS version.txt)
#add_custom_target(default ALL DEPENDS version.txt)
add_custom_command(
    OUTPUT version.txt
    COMMAND bash -c "${CMAKE_CURRENT_LIST_DIR}/update_version.sh"
) 
add_custom_command(
    POST_BUILD
    TARGET basez80_version
    COMMAND bash -c "${CMAKE_CURRENT_LIST_DIR}/update_version.sh"
)
