# Use bash for advanced scripting
SHELL := /bin/bash

# ==== Toolchain Base Paths ====
TOOLS_BASE := $(HOME)/.arduino15/packages/WCH/tools

# GCC toolchain
GCC_BASE := $(TOOLS_BASE)/riscv-none-embed-gcc/8.2.0/bin
GCC := $(GCC_BASE)/riscv-none-embed-gcc

# OpenOCD tools
OPENOCD_BASE := $(TOOLS_BASE)/openocd/1.0.0/bin
OPENOCD_BIN := $(OPENOCD_BASE)/openocd
CFG_FILE := $(OPENOCD_BASE)/wch-riscv.cfg

# ==== Project Sources ====
# List your assembly and C source files here
ASM_SRCS := blink.s
C_SRCS   :=

# ==== Output Files ====
ELF := blink.elf
MAP := blink.map

# ==== GCC Flags ====
GCCFLAGS := -Ttext=0 -e Coldstart -nostartfiles -Wl,-Map,$(MAP)

# ==== Default Target ====
.PHONY: all
all: $(ELF)

# ==== Build ELF directly from sources ====
$(ELF): $(ASM_SRCS) $(C_SRCS)
	@echo "Building $@ from sources..."
	$(GCC) $(ASM_SRCS) $(C_SRCS) $(GCCFLAGS) -o $@

# ==== Clean up build artifacts ====
.PHONY: clean
clean:
	rm -f $(ELF) $(MAP) *.o *.d erase_output.log

# ==== Erase chip (optional, but recommended) ====
.PHONY: erase
erase:
	@echo "Attempting to erase chip (this will fail if write protected)..."
	$(OPENOCD_BIN) -f $(CFG_FILE) -c init -c halt -c "flash erase_address 0x0 0x400" -c exit 2>&1 | tee erase_output.log
	@if grep -q "write protected" erase_output.log; then \
		echo "Chip is write protected. Aborting flash."; \
		exit 1; \
	else \
		echo "No write protection detected, or unable to determine."; \
	fi

# ==== Flash ELF directly ====
.PHONY: flash
flash: $(ELF) erase
	@echo "Flashing $(ELF) to the microcontroller..."
	$(OPENOCD_BIN) -f $(CFG_FILE) -c init -c halt -c "program $(ELF) verify reset exit"
	@echo "Done."


