# !/bin/sh

VMLANG="../../vmlang/vmlang"
VMASM="../../vmasm/vmasm"
VMLINK="../../vmlink/vmlink"
VMTEST="../../libvmrt/vm-test"

ASM_EXTEN="S"
OBJ_EXTEN="vo"
EXEC_EXTEN="v"

ENTRY_POINT="test"

check_executables()
{
	if [ ! -e $VMLANG ] || [ ! -e $VMASM ] || [ ! -e $VMLINK ] || [ ! -e $VMTEST ]; then
		echo "can't find executables"
		exit 1
	fi
}

build_src()
{
	VM_FILES=$(find . -name \*.vm -type f)

	for FILE in $VM_FILES
	do
		LEN=${#FILE}
		NAME=${FILE:0:$LEN-3}

		$VMLANG -o $NAME.$ASM_EXTEN $FILE > /dev/null 2>&1

		if [ $? != 0 ] ; then
			echo failed -- $VMLANG -o $NAME.$ASM_EXTEN $FILE
			exit $?
		fi

		$VMASM -o $NAME.$OBJ_EXTEN $NAME.$ASM_EXTEN > /dev/null 2>&1

		if [ $? != 0 ] ; then
			echo failed -- $VMASM -o $NAME.$OBJ_EXTEN $NAME.$ASM_EXTEN
			exit $?
		fi

		$VMLINK -e $ENTRY_POINT -o $NAME.$EXEC_EXTEN $NAME.$OBJ_EXTEN > /dev/null 2>&1

		if [ $? != 0 ] ; then
			echo failed -- $VMLINK -e $ENTRY_POINT -o $NAME.$EXEC_EXTEN $NAME.$OBJ_EXTEN
			exit $?
		fi
	done
}

run_test()
{
	EXEC_FILES=$(find . -name \*.v -type f)

	for FILE in $EXEC_FILES
	do
		$VMTEST $FILE

		if [ $? != 0 ] ; then
			echo failed -- $FILE
			exit $?
		fi
	done
}

cleanup()
{
	rm *.$ASM_EXTEN *.$OBJ_EXTEN *.$EXEC_EXTEN > /dev/null 2>&1
}

show_help()
{
	echo
	echo Description: simple script to build and run tests
	echo Usage: run-test "{test|clean}"  
	echo
}


case "$1" in
   test)
	check_executables
	build_src
	run_test
	;;
   clean)
	cleanup
	;;
   *)
	show_help
	exit 1
	;;
esac

exit 0
