#!/bin/sh
# The road to hell is paved with Makefile generators.
#
# Each test is compiled statically linked with a single collector.
#
# OBJDEPS: Dependencies for an object file.
# DEPS: Dependencies for an executable file.

TEST_TARGETS=""
GENERATED_OBJS=""

gen_test() { # test_name, collector_name, exec_deps, obj_file_deps
	local NAME COLLECTOR TARGET TEST_IMPL DEPS OBJDEPS

	NAME=$1
	COLLECTOR=$2
	TARGET="$NAME"_"$COLLECTOR".test
	TEST_IMPL="$NAME.c"
	DEPS="$1.o uns.o $3"
	OBJDEPS="include/uns.h $1.c $4"

	echo "
$TARGET: $DEPS
	\${CC} \${TEST_LDFLAGS} $DEPS -o $TARGET
	\${TEST_WRAPPER} ./$TARGET
"

	TEST_TARGETS="$TEST_TARGETS $TARGET"
	GENERATED_OBJS="$GENERATED_OBJS $NAME.o"
}

gen_string_test() { # collector_name, exec_deps
	local COLLECTOR DEPS OBJDEPS

	COLLECTOR=$1
	DEPS="$2 examples/test_$COLLECTOR.o examples/string/uns_string.o"
	OBJDEPS="examples/string/uns_string.h"

	gen_test 'examples/string/test_small' "$COLLECTOR" \
	         "$DEPS" "$OBJDEPS"

	gen_test 'examples/string/test_large' "$COLLECTOR" \
	         "$DEPS" "$OBJDEPS"

	gen_test 'examples/string/test_inefficient' "$COLLECTOR" \
	         "$DEPS" "$OBJDEPS"
}

gen_hashtable_test() { # collector_name, exec_deps
	local COLLECTOR DEPS OBJDEPS

	COLLECTOR=$1
	DEPS="$2 examples/test_$COLLECTOR.o examples/hashtable/uns_hashtable.o"
	OBJDEPS="examples/hashtable/uns_hashtable.h examples/hashtable/testnames.h"

	gen_test 'examples/hashtable/test_insert' "$COLLECTOR" \
	         "$DEPS" "$OBJDEPS"

	gen_test 'examples/hashtable/test_insert_delete' "$COLLECTOR" \
	         "$DEPS" "$OBJDEPS"
}

gen_lisp_test() { #collector_name, exec_deps
	local COLLECTOR SHIM_OBJ TARGET DEPS OBJDEPS
	COLLECTOR=$1
	TARGET="examples/lisp/uns_lisp_$COLLECTOR"
	SHIM_OBJ="$TARGET.o"
	OBJDEPS="examples/lisp/uns_lisp_$COLLECTOR.c include/uns.h include/$COLLECTOR.h"
	DEPS="$2 $SHIM_OBJ uns.o "'${UNS_LISP_OBJS}'

	echo "
$SHIM_OBJ: $OBJDEPS

$TARGET: $DEPS
	\${CC} \${TEST_LDFLAGS} $DEPS -o $TARGET
"

	TEST_TARGETS="$TEST_TARGETS $TARGET"
	GENERTATED_OBJS="$GENERATED_OBJS $SHIM_OBJ"
}

gen_tests() {
	echo "examples/test_$1.o: include/uns.h $2"
	GENERATED_OBJS="$GENERATED_OBJS examples/test_$1.o"

	gen_string_test "$1" '${CHENEY_C89_OBJS}'
	gen_hashtable_test "$1" '${CHENEY_C89_OBJS}'
	gen_lisp_test "$1" '${CHENEY_C89_OBJS}'
}

gen_tests cheney_c89 "include/cheney_c89.h"

echo
printf "tests: %s\n" "$TEST_TARGETS"
printf 'clean_tests:\n\t${RM} -f %s %s\n' "$TEST_TARGETS" "$GENERATED_OBJS"