SHELL := /bin/bash

CFLAGS ?= -Wall -g
GDBRUN = gdb --batch --ex run --ex bt --ex q --args
BUILD_TARGETS = $(foreach ex,$(wildcard ex*.c),$(subst .c,,$(ex)))

.PHONY: all
all: build test

.PHONY: echo
echo:
	@echo BUILD_TARGETS=$(BUILD_TARGETS)

.PHONY: clean
clean:
	rm -f $(BUILD_TARGETS)

.PHONY: build
build: $(BUILD_TARGETS)

.PHONY: gtest
gtest: $(BUILD_TARGETS)
	@$(foreach bt, $(BUILD_TARGETS), make .gtest.$(bt) &&) printf '\ngYAY\n'

.gtest.%: %
	@if test -f .$*.argv; then readarray -t test_argv <.$*.argv; fi && \
	printf '\n==> %s\n' "$*" && $(GDBRUN) ./$* "$${test_argv[@]}"

.PHONY: test
test: $(BUILD_TARGETS)
	@$(foreach bt, $(BUILD_TARGETS), make .test.$(bt) &&) printf '\nYAY\n'

.test.%: %
	@if test -f .$*.argv; then readarray -t test_argv <.$*.argv; fi && \
	printf '\n==> %s\n' "$*" && ./$* "$${test_argv[@]}"
