
elf = $(test).elf
map = $(test).map

ALT_LIBRARY_ROOT_DIR := $(bsp_root_dir)
ABS_BSP_ROOT_DIR := $(shell realpath $(bsp_root_dir))
BSP_INCLUDE_FILE := $(bsp_root_dir)/public.mk
include $(BSP_INCLUDE_FILE)

libbsp = $(bsp_root_dir)/${BSP_LIB}

cross_compile := nios2-elf-
ECHO = echo
LD := $(cross_compile)g++
CC := $(cross_compile)gcc
CXX := $(cross_compile)g++

ldflags += -T$(BSP_LINKER_SCRIPT)
ldflags += -msys-crt0=$(BSP_CRT0)
ldflags += -msys-lib=$(BSP_SYS_LIB)
ldflags += $(addprefix -L,$(ALT_LIBRARY_DIRS))
ldflags += -O2
ldflags += -Wall
ldflags += $(ALT_CFLAGS)

cflags += -O2
cflags += -Wall
cflags += $(ALT_CFLAGS)

include_dirs += $(addprefix -I, $(ALT_INCLUDE_DIRS))

c_objects = $(patsubst %.c,%.o, ${c_sources})
cc_objects = $(patsubst %.cc,%.oo, $(cc_sources))

objects = ${c_objects} ${cc_objects}

execute_on_device_and_read_output = ${scripts}/execute_on_device_and_read_output.sh
check_test_results = ${scripts}/check_test_results.sh
execute_and_highlight = ${scripts}/execute_and_highlight.sh
device_output=device.out

artifacts += ${device_output}

.PHONY: all
all: test remove_device_output

.PHONY: remove_device_output
remove_device_output:
	@${RM} -rf ${device_output}

ifdef plot_data
.PHONY: _plot
_plot: ${plot_data} remove_device_output

${plot_data}: ${device_output}
	@cat $< | ${extract_python_data} > $@
endif

.PHONY: test
test: ${device_output}
	@$(ECHO) Checking test results
	@${check_test_results} $<

${device_output}: ${elf} ${execute_on_device_and_read_output}
	@$(ECHO) Executing $<
	@${execute_and_highlight} ${execute_on_device_and_read_output} ${elf} ${device_output}

${elf}: ${objects} ${linker_script} ${libbsp}
	@$(ECHO) Linking $@
	@${LD} ${ldflags} ${objects} -o $@

%.oo:%.cc
	@$(ECHO) Compiling $<
	@${CXX} --std=c++14 ${include_dirs} -c $< -o $@

%.o:%.c
	@$(ECHO) Compiling $<
	@${CC} $(cflags) ${include_dirs} -c $< -o $@

${libbsp}:
	@$(ECHO) Building $(bsp_root_dir)
	@$(MAKE) --no-print-directory -C $(bsp_root_dir)

.PHONY: clean
clean:
	@$(ECHO) Cleaning test
	@${RM} -rf ${objects} ${elf} ${artifacts}

.PHONY: download
download: $(elf)
	@nios2-download -r -g $(elf)

