cmake_minimum_required(VERSION 3.13)
project(lezyne-rear-light-firmware C)

# MCU and clock
set(MCU attiny202)
set(F_CPU 5000000UL)

# Toolchain
set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_C_COMPILER avr-gcc)
set(OBJCOPY avr-objcopy)

# Sources
add_executable(main.elf main.c)

# Compiler and linker flags
target_compile_options(main.elf PRIVATE -mmcu=${MCU} -DF_CPU=${F_CPU} -Os -Wall -Werror)
set_target_properties(main.elf PROPERTIES LINK_FLAGS "-mmcu=${MCU}")

# Create HEX and BIN after build
add_custom_command(TARGET main.elf POST_BUILD
    COMMAND ${OBJCOPY} -O ihex -R .eeprom main.elf main.hex
    COMMAND ${OBJCOPY} -O binary -R .eeprom main.elf main.bin
)

# Optional: show size
find_program(SIZE_TOOL avr-size)
if(SIZE_TOOL)
    add_custom_command(TARGET main.elf POST_BUILD
        COMMAND ${SIZE_TOOL} --mcu=${MCU} --format=avr main.elf
    )
endif()

# Flash target using pymcuprog
find_program(PYMCUPROG pymcuprog)
set(UPDI_PORT "/dev/ttyUSB0" CACHE STRING "Serial port for UPDI programming")

if(PYMCUPROG)
    add_custom_target(flash
        COMMAND ${PYMCUPROG} -t uart -u ${UPDI_PORT} -d ${MCU} write -f main.hex
        DEPENDS main.hex
        COMMENT "Flashing ${MCU} with pymcuprog..."
    )
else()
    message(WARNING "pymcuprog not found in PATH. 'make flash' will not be available.")
endif()

# --- SBOM Generation (SPDX JSON) ---
find_package(Git REQUIRED)

# Generate current timestamp in ISO 8601 format (UTC)
string(TIMESTAMP CMAKE_TIMESTAMP "%Y-%m-%dT%H:%M:%SZ" UTC)

# Get current git hash
execute_process(
    COMMAND ${GIT_EXECUTABLE} rev-parse HEAD
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    OUTPUT_VARIABLE GIT_HASH
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

# Get avr-gcc version
execute_process(
    COMMAND ${CMAKE_C_COMPILER} --version
    OUTPUT_VARIABLE AVR_GCC_VERSION
    OUTPUT_STRIP_TRAILING_WHITESPACE
)

# Where to write SBOM
set(SBOM_FILE ${CMAKE_SOURCE_DIR}/sbom.spdx.json)

# Generate from template
configure_file(${CMAKE_SOURCE_DIR}/sbom.template.json ${SBOM_FILE} @ONLY)

# Always regenerate on build
add_custom_target(sbom ALL
    DEPENDS ${SBOM_FILE}
    COMMENT "Generating SPDX SBOM..."
)
