ELF        := OS3.out
GDB        := arm-none-eabi-gdb
OPENOCD    := openocd
OPENOCD_CFG := xlmcu_m3.cfg
GDB_HOST   ?= localhost
GDB_PORT   ?= 3333
BOOT_BREAK ?= main

# 默认使用 DAPLink/CMSIS-DAP；也可以通过命令行覆盖：
# make openocd OPENOCD_INTERFACE=interface/xxx.cfg
OPENOCD_INTERFACE ?= interface/cmsis-dap.cfg
OPENOCD_ARGS ?= -f $(OPENOCD_INTERFACE) -f $(OPENOCD_CFG)

.PHONY: all check-elf openocd debug flash attach clean help

all: check-elf

check-elf:
	@test -f "$(ELF)" || { \
		echo "error: $(ELF) not found" >&2; \
		exit 1; \
	}

openocd:
	$(OPENOCD) $(OPENOCD_ARGS)

# 连接、执行 VECTRESET、恢复入口，然后在 main 自动停止。
debug: check-elf
	$(GDB) -q "$(ELF)" \
		-ex "set pagination off" \
		-ex "target extended-remote $(GDB_HOST):$(GDB_PORT)" \
		-ex "monitor xlmcu_reset_halt" \
		-ex "hbreak $(BOOT_BREAK)" \
		-ex "continue"

# 不执行 reset 直接连接，适合目标已经处于期望状态时使用。
attach: check-elf
	$(GDB) -q "$(ELF)" \
		-ex "set pagination off" \
		-ex "target extended-remote $(GDB_HOST):$(GDB_PORT)"

# 先 halt 再 load，避免空白芯片没有有效向量表时 reset-init 读取失败。
flash: check-elf
	$(GDB) -q "$(ELF)" \
		-ex "set pagination off" \
		-ex "target extended-remote $(GDB_HOST):$(GDB_PORT)" \
		-ex "monitor halt" \
		-ex "load" \
		-ex "monitor xlmcu_reset_halt" \
		-ex "continue"

clean:
	@echo "No build products to remove; $(ELF) is treated as an input file."

help:
	@echo "make openocd  - start OpenOCD"
	@echo "make debug    - open $(ELF), reset and stop at $(BOOT_BREAK)"
	@echo "make attach   - connect $(ELF) to port $(GDB_PORT) without reset"
	@echo "make flash    - halt, load $(ELF), reset and run"
