#!/usr/bin/env bash

# Usage: LANGUAGE TEST | -b SOURCE_FILE

readonly ITERATIONS=1000000 # 1 000 000, one million
readonly STACK_HEIGHT=100

# Build Test Programs:
# Mini-Make: TARGET SOURCE COMMAND ARGS...
mmake() (
	if [ ! -e "$1" -o "$1" -ot "$2" ]; then
		"${@:3}"
	fi
)

build() (
	case "$1" in
	*.cfa)
		# Requires a symbolic link.
		mmake "${1%.cfa}" "$1" ./cfa "$1" -o "${1%.cfa}"
		;;
	*.cpp)
		mmake "${1%.cpp}-cpp" "$1" g++ "$1" -o "${1%.cpp}-cpp"
		;;
	*.java)
		mmake "${1%.java}.class" "$1" javac "$1"
		;;
	*)
		echo "Don't know how to build:" $1 >&2
		exit 2
		;;
	esac
)

if [ "-b" = "$1" ]; then
	for file in "${@:2}"; do
		build $file
	done
	exit 0
elif [ 2 -eq "$#" ]; then
    TEST_LANG="$1"
    TEST_CASE="$2"
else
    echo "Unknown call pattern." >&2
    exit 2
fi

# Run Test Programs:
# Used in place of unsupported language/test combinations.
unsupported() {
	echo "Run-Time: NA"
}

case "$TEST_CASE" in
cond-match-all)
	CFAT="./cond-catch $ITERATIONS 1"
	CFAR="./cond-fixup $ITERATIONS 1"
	CPP="./cond-catch-cpp $ITERATIONS 1"
	JAVA="java CondCatch $ITERATIONS 1"
	;;
cond-match-none)
	CFAT="./cond-catch $ITERATIONS 0"
	CFAR="./cond-fixup $ITERATIONS 0"
	CPP="./cond-catch-cpp $ITERATIONS 0"
	JAVA="java CondCatch $ITERATIONS 0"
	;;
cross-catch)
	CFAT="./cross-catch $ITERATIONS"
	CFAR="./cross-resume $ITERATIONS"
	CPP="./cross-catch-cpp $ITERATIONS"
	JAVA="java CrossCatch $ITERATIONS"
	;;
cross-finally)
	CFAT="./cross-finally $ITERATIONS"
	CFAR=unsupported
	CPP=unsupported
	JAVA="java CrossFinally $ITERATIONS"
	;;
raise-detor)
	CFAT="./throw-detor $ITERATIONS $STACK_HEIGHT"
	CFAR="./resume-detor $ITERATIONS $STACK_HEIGHT"
	CPP="./throw-detor-cpp $ITERATIONS $STACK_HEIGHT"
	JAVA=unsupported
	;;
raise-empty)
	CFAT="./throw-empty $ITERATIONS $STACK_HEIGHT"
	CFAR="./resume-empty $ITERATIONS $STACK_HEIGHT"
	CPP="./throw-empty-cpp $ITERATIONS $STACK_HEIGHT"
	JAVA="java ThrowEmpty $ITERATIONS $STACK_HEIGHT"
	;;
raise-finally)
	CFAT="./throw-finally $ITERATIONS $STACK_HEIGHT"
	CFAR="./resume-finally $ITERATIONS $STACK_HEIGHT"
	CPP=unsupported
	JAVA="java ThrowFinally $ITERATIONS $STACK_HEIGHT"
	;;
raise-other)
	CFAT="./throw-other $ITERATIONS $STACK_HEIGHT"
	CFAR="./resume-other $ITERATIONS $STACK_HEIGHT"
	CPP="./throw-other-cpp $ITERATIONS $STACK_HEIGHT"
	JAVA="java ThrowOther $ITERATIONS $STACK_HEIGHT"
	;;
*)
	echo "No such test: $TEST_CASE" >&2
	exit 2
	;;
esac

case "$TEST_LANG" in
cfa-t) echo $CFAT; $CFAT;;
cfa-r) echo $CFAR; $CFAR;;
cpp) echo $CPP; $CPP;;
java) echo $JAVA; $JAVA;;
*)
	echo "No such language: $TEST_LANG" >&2
	exit 2
esac
