# SPDX-License-Identifier: Apache-2.0
cmake_minimum_required(VERSION 3.13.1)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(blinky)

target_sources(app PRIVATE src/main.c)

# ==============================================================================
# Automatically generate an external Python script and add padding at the end
# Coded by Gemini
# ==============================================================================
set(TARGET_ELF "${APPLICATION_BINARY_DIR}/zephyr/zephyr.elf")
set(PADDED_HEX "${APPLICATION_BINARY_DIR}/zephyr/zephyr_padded.hex")
set(PAD_SCRIPT "${APPLICATION_BINARY_DIR}/zephyr/pad_bin.py")

file(WRITE ${PAD_SCRIPT} "
import sys, os, subprocess

elf_path = sys.argv[1]
hex_out_path = sys.argv[2]
objcopy_path = sys.argv[3]

bin_path = elf_path.replace('.elf', '.bin')
padded_bin_path = bin_path.replace('.bin', '_padded.bin')

# Generate a BIN file from the ELF file once
subprocess.run([objcopy_path, '-O', 'binary', elf_path, bin_path])

# Add 0xFF to the end of the BIN file to ensure it is aligned to a 16-byte boundary
with open(bin_path, 'rb') as f:
    data = f.read()

rem = len(data) % 16
if rem != 0:
    pad_len = 16 - rem
    data += b'\\xff' * pad_len

with open(padded_bin_path, 'wb') as f:
    f.write(data)

# Generate a HEX file usable with west flash from a padded BIN file
subprocess.run([objcopy_path, '-I', 'binary', '-O', 'ihex', '--change-addresses', '0x0', padded_bin_path, hex_out_path])
print('--- Padding process finished successfully! ---')
")

# At the end of the build, register a target that runs the Python script mentioned above
add_custom_target(generate_padded_artifacts ALL
    COMMAND ${PYTHON_EXECUTABLE} ${PAD_SCRIPT} ${TARGET_ELF} ${PADDED_HEX} ${CMAKE_OBJCOPY}
    DEPENDS ${TARGET_ELF}
    COMMENT "--- Running safe Python script to pad binary end to 16-byte boundary ---"
)