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

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

SRC := ch32fun.c main.c rsa.c rand.c

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: $(SRC) libgcc.a | ch32v003.ld ch32fun.h ch32v003hw.h
	@echo CC $@
	@$(CC) $(CFLAGS) $(LDFLAGS) $(EXTFLAGS) -o $@ $^

ch32v003.ld: ch32fun.ld
	@$(CC) -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)/ch32fun/$@

libgcc.a:
	@echo "Fetching $@"
	@curl $(CURL_FLAGS) $(BASE)/misc/$@

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

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

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

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

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

link:
	minichlink -T

clean:
	rm -f *.{hex,bin,map,lst,elf}

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

.PHONY: clean flash deps default distclean link