REV := master
BASE := https://raw.githubusercontent.com/cnlohr/ch32v003fun/$(REV)/ch32fun
CURL_FLAGS := -O -\# --fail --location --tlsv1.3 --proto =https --max-time 300

TARGET = blink
TARGET_MCU?=CH32V003
NEWLIB=/usr/arm-none-eabi/include
TOOL_PREFIX := riscv64-linux-gnu
CC := $(TOOL_PREFIX)-gcc
OBJDUMP := $(TOOL_PREFIX)-objdump
OBJCOPY := $(TOOL_PREFIX)-objcopy

CFLAGS = -g \
		 -Os \
		 -flto \
		 -ffunction-sections \
		 -fdata-sections \
		 -fmessage-length=0 \
		 -msmall-data-limit=8

LDFLAGS = -Wl,--print-memory-usage \
		  -Wl,-Map=$(TARGET).map,--build-id=none

EXTFLAGS := -march=rv32ec \
			-mabi=ilp32e \
			-DCH32V003=1 \
			-static-libgcc \
			-I$(NEWLIB) \
			-nostdlib \
			-I. \
			-Wall \
			-L. \
			-lgcc \
			-T ch32v003.ld \
			-Wl,--gc-sections

default: $(TARGET).bin

$(TARGET).elf: ch32fun.c blink.c | ch32v003.ld ch32fun.h ch32v003hw.h
	@echo CC $@
	@$(CC) $(CFLAGS) $(LDFLAGS) $(EXTFLAGS) -o $@ $^

ch32v003.ld: ch32fun.ld
	@riscv64-linux-gnu-gcc -E -P -x c -DTARGET_MCU=$(TARGET_MCU) -DMCU_PACKAGE= -DTARGET_MCU_LD=0 -DTARGET_MCU_MEMORY_SPLIT= $< > $@

# Rule to use curl to fetch all files beginning with ch32
ch32%:
	@echo "Fetching $@"
	@curl $(CURL_FLAGS) $(BASE)/$@

$(TARGET).bin : $(TARGET).elf
	@$(OBJCOPY) -O binary $< $(TARGET).bin

$(TARGET).lst : $(TARGET).elf
	@$(OBJDUMP) -S $^ > $(TARGET).lst

$(TARGET).hex : $(TARGET).elf
	@$(OBJCOPY) -O ihex $< $(TARGET).hex

flash: $(TARGET).bin
	minichlink -w $(TARGET).bin flash -b

flash2: $(TARGET).bin
	wlink flash $(TARGET).bin

clean:
	rm -f ch32*.[ch]
	rm -f *.{ld,hex,bin,map,lst,elf}

.PHONY: clean flash deps default