MAKEFLAGS += -R -r

prefix   := $(CURDIR)/gnu

tooldir   = gnusrc
binutils  = $(tooldir)/binutils

all_config = --prefix=$(prefix)

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

include ../riscv-opts.mk
export riscv_target_flags

multilibs= rv32imc-ilp32--zicsr;rv32im-ilp32--zicsr;rv32i-ilp32--zicsr;rv32imc_zbb-ilp32--zicsr

riscv_tuple=riscv32-unknown-elf

riscv_config = $(all_config) \
	   --target=riscv32-unknown-elf \
	   --enable-languages=c,c++ \
	   --with-arch=rv32imc_zicsr --with-abi=ilp32 \
	   --with-newlib \
	   --with-sysroot=$(prefix)/$(riscv_tuple) \
	   --disable-shared --disable-threads \
	   --disable-libmudflap --disable-libssp \
	   --disable-libquadmath --disable-libgomp --disable-nls \
	   --disable-tm-clone-registry \
	   --enable-multilib --with-multilib-generator=$(multilibs)
export riscv_config

riscv_binutils_configargs := \
	--disable-gold --disable-gprof --disable-sim
export riscv_binutils_configargs

# 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)))

gnu_makeflags = $(call strip_flags,r R,$(MAKEFLAGS))

RMAKE = +$(MAKE) MAKEFLAGS='$(gnu_makeflags)'

riscv_newlib_configargs := \
	--disable-newlib-fseek-optimization \
	--disable-newlib-fvwrite-in-streamio \
	--disable-newlib-mb \
	--disable-newlib-multithread \
	--disable-newlib-reent-check-verify \
	--disable-newlib-register-fini \
	--disable-newlib-supplied-syscalls \
	--disable-newlib-unbuf-stream-opt \
	--disable-newlib-wide-orient \
	--enable-lite-exit \
	--enable-newlib-global-atexit \
	--enable-newlib-nano-formatted-io \
	--enable-newlib-io-c99-formats \
	--enable-newlib-nano-malloc \
	--enable-newlib-reent-small
export riscv_newlib_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 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:
	MAKE='$(MAKE)' MAKEFLAGS='$(gnu_makeflags)' ./riscvbuild.sh

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