# SPDX-License-Identifier: MIT
#
# Fully open-source CH32V003 template using ch32fun (MIT).
#
# Toolchain: Arch packages riscv64-elf-gcc + riscv64-elf-newlib
# Flashing:  minichlink (MIT, part of ch32fun) or wchisp
#
# ch32fun is used as an external SDK. Point CH32FUN_ROOT at your checkout:
#   git clone https://github.com/cnlohr/ch32fun ~/code/ch32fun
#
# This build does NOT use the WCH EVT SDK, WCH's GCC, libprintf, or IQmath.

TARGET      ?= firmware
TARGET_MCU  ?= CH32V003

# Root of the ch32fun checkout (the directory containing ch32fun/ and minichlink/).
CH32FUN_ROOT ?= $(HOME)/code/ch32fun
CH32FUN      ?= $(CH32FUN_ROOT)/ch32fun
MINICHLINK   ?= $(CH32FUN_ROOT)/minichlink

# Arch's riscv64-elf-newlib installs its headers here. ch32fun only needs the
# headers; it never links newlib (see -nostdlib below).
NEWLIB ?= /usr/riscv64-elf/include

# Arch's bare-metal RISC-V GCC. ch32fun auto-detects this too, but pinning it
# makes the build reproducible. Override for another toolchain, e.g.
#   make PREFIX=riscv32-unknown-elf
PREFIX ?= riscv64-elf

ifeq ($(wildcard $(CH32FUN)/ch32fun.mk),)
$(error ch32fun not found at $(CH32FUN). Set CH32FUN_ROOT=/path/to/ch32fun)
endif

ifeq ($(wildcard $(NEWLIB)/stdio.h),)
$(error newlib headers not found at $(NEWLIB). Install riscv64-elf-newlib or set NEWLIB=/path/to/include)
endif

ifeq ($(shell command -v $(PREFIX)-gcc 2>/dev/null),)
$(error $(PREFIX)-gcc not found. Install riscv64-elf-gcc or set PREFIX=/path/to/toolchain-prefix)
endif

# ch32fun's build rules:
#   - compiles ch32fun.c and $(TARGET).c
#   - uses ch32fun.ld, -nostdlib and ch32fun/misc/libgcc.a
#   - emits $(TARGET).elf/.bin/.hex/.lst/.map
include $(CH32FUN)/ch32fun.mk

# Build firmware only; never flash implicitly.
all: $(TARGET).bin

flash: cv_flash
clean: cv_clean

size: $(TARGET).elf
	$(PREFIX)-size $<

.PHONY: all flash clean size
