MAKEFLAGS += -R -r

prefix   := $(CURDIR)

tooldir   = riscv-gnu-toolchain
binutils  = $(tooldir)/riscv-binutils

# --disable-gdb because the gdb with riscv-gnu-toolchain seems really broken
all_config = --prefix=$(prefix)/gnu --with-system-zlib


z80_config = $(all_config) \
	   --target=z80-none-elf

include ../riscv-opts.mk

riscv_config = $(all_config) \
	    --with-arch=rv32imc --with-abi=ilp32 \
	    --with-target-cflags='$(riscv_target_flags)' \
	    --with-target-cxxflags='$(riscv_target_flags)' \
	    --enable-multilib --with-multilib-generator='rv32imc-ilp32--'

# The tools don't seem to build correctly without buildin rules (sigh)
# There isn't even an option to cancel them, so use this hideousness
# to strip out the r and R option from MAKEFLAGS.
_tail = $(wordlist 2,$(words $(1)),$(1))
_strip_flags = $(if $(1),$(call _strip_flags,$(call _tail,$(1)),$(subst $(word 1,$(1)),,$(2))),$(2))
strip_flags  = $(if $(findstring -,$(word 1,$(2))),$(2),$(call _strip_flags,$(1),$(word 1,$(2))) $(call _tail,$(2)))

RMAKE = +$(MAKE) MAKEFLAGS='$(call strip_flags,r R,$(MAKEFLAGS))'

riscv_target_configargs := --enable-lite-exit \
	--disable-newlib-register-fini --disable-newlib-mb \
	--disable-newlib-reent-check-verify --disable-newlib-wide-orient \
	--disable-newlib-multithread --disable-newlib-supplied-syscalls \
	--enable-newlib-nano-malloc --enable-newlib-io-c99-formats \
	--disable-newlib-fvwrite-in-streamio --disable-shared

riscv_configargs := target_configargs='$(riscv_target_configargs)'

all: gnu

clean:
	rm -rf *.build *~ *.bak \#* .\#* *.deps *.stamp

spotless: clean
	rm -rf gnu

.PHONY: gnu.src
gnu.src:
	if [ -f ../../.gitmodules ] && \
	   git submodule status --recursive | grep -q '^[+-]'; then \
		git submodule update --init --recursive ; \
		rm -rf gnu gnu.*.stamp ; \
	fi

.PHONY: gnu
gnu:
	$(MAKE) gnu.src
	$(MAKE) gnu.bin

.PHONY: gnu.bin
gnu.bin: gnu.riscv.build.stamp gnu.z80.build.stamp

# Note: the riscv-gnu-toolchain repo has bugs when building in
# parallel, so spoon feed it a sequence to avoid dependency problems.
%.build.stamp:
	$(MAKE) $*.build

.PHONY: gnu.riscv.build
gnu.riscv.build:
	mkdir -p $@
	cd $@ && $(riscv_configargs) ../$(tooldir)/configure $(riscv_config)
	$(RMAKE) -C $@ $(riscv_configargs) build-binutils
	$(RMAKE) -C $@ $(riscv_configargs) newlib
	: >$@.stamp

.PHONY: gnu.z80.build
gnu.z80.build:
	mkdir -p $@
	cd $@ && ../$(binutils)/configure $(z80_config)
	$(RMAKE) -C $@
	$(RMAKE) -C $@ install
	: >$@.stamp
