# variables

# SHELL = /bin/bash

PREFIX=riscv-gaisler-elf-
CC = $(PREFIX)gcc
CFLAGS = -g -O2

EXAMPLES         =
EXAMPLES        += hello.elf
EXAMPLES        += mainarg.elf
EXAMPLES        += dhrystone.elf
EXAMPLES        += stanford.elf
EXAMPLES        += whetstone.elf
EXAMPLES        += paranoia.elf
EXAMPLES        += prime.elf
EXAMPLES        += ambapp.elf
EXAMPLES        += lessambapp.elf
EXAMPLES        += exception.elf
EXAMPLES        += cpustart.elf

ifeq ($(BSPS),)
# Try to find BSPS given the examples config directory
BSPS := $(notdir $(wildcard bspopts/*))
endif

ifeq ($(DESTDIR),)
DESTDIR = .
endif
BINDIR = bin

FLAGS_TO_PASS = \
	"CC=$(CC)" \
	"CFLAGS=$(CFLAGS)" \
	"AS=$(AS)" \
	"LD=$(LD)" \
	"DESTDIR=$(DESTDIR)"

MAKEFLAGS=--no-print-directory

# targets
all:
	@$(MAKE) $(FLAGS_TO_PASS) multi-do DO="build"

clean:
	rm -rf $(BINDIR)
	rm -f *.elf

.PHONY: build
build: $(addprefix $(DESTDIR)/,$(EXAMPLES))
	@true

$(DESTDIR):
	@mkdir -p $@

# For each BSP, there are several compiler options/output directory
# descriptions, in the file bspopts/<BSP>/opts_<TOOLCHAIN>.
multi-do:
	@for bsp in $(BSPS); do \
		for i in `cat bspopts/$${bsp}/opts_gcc`; do \
			dir="$${bsp}/"; \
			dir+=`echo $$i | sed -e 's/;.*$$//'`; \
			flags="-qbsp=$${bsp} ";\
			flags+=`echo $$i | sed -e 's/^[^;]*;//' -e 's/@/ -/g'`; \
			printf "BSP:%-10s dir:%-20s flags:$${flags}\n" $${bsp} $${dir} > /dev/null; \
			$(MAKE) $(FLAGS_TO_PASS) \
				CFLAGS="$(CFLAGS) $${flags}" \
				CXXFLAGS="$(CXXFLAGS) $${flags}" \
				LDFLAGS="$(LDFLAGS) $${flags}" \
				DESTDIR="$(BINDIR)/$${dir}" \
				BSP="$${bsp}" \
				$(DO) \
			|| exit 1;  \
		done; \
	done

$(DESTDIR)/hello.elf: hello/hello.c | $(DESTDIR)
	$(CC) $(CFLAGS) $^ -o $@

$(DESTDIR)/mainarg.elf: mainarg/mainarg.c | $(DESTDIR)
	$(CC) $(CFLAGS) $^ -o $@

$(DESTDIR)/dhrystone.elf: dhrystone/dhry_1.c dhrystone/dhry_2.c | $(DESTDIR)
	$(CC) $(CFLAGS) -Wno-implicit-int -Wno-implicit-function-declaration $^ -o $@

$(DESTDIR)/stanford.elf: stanford/stanford.c | $(DESTDIR)
	$(CC) $(CFLAGS) -Wno-implicit-int $^ -o $@

$(DESTDIR)/whetstone.elf: whetstone/whetstone.c | $(DESTDIR)
	$(CC) $(CFLAGS) $^ -o $@ -lm

$(DESTDIR)/paranoia.elf: paranoia/paranoia.c | $(DESTDIR)
	$(CC) $(CFLAGS) $^ -o $@ -lm

$(DESTDIR)/prime.elf: prime/prime.cc | $(DESTDIR)
	$(CC) $(CFLAGS) $^ -o $@ -lstdc++

$(DESTDIR)/ambapp.elf: ambapp/ambapp.c | $(DESTDIR)
	$(CC) $(CFLAGS) -std=c99 $^ -o $@

$(DESTDIR)/lessambapp.elf: lessambapp/lessambapp.c | $(DESTDIR)
	$(CC) $(CFLAGS) -std=c99 $^ -o $@

$(DESTDIR)/exception.elf: exception/exception.c | $(DESTDIR)
	$(CC) $(CFLAGS) -std=c99 $^ -o $@

$(DESTDIR)/cpustart.elf: cpustart/cpustart.c | $(DESTDIR)
	$(CC) $(CFLAGS) -std=c99 $^ -o $@

