#!/bin/bash

E_DIR_EXISTS=1
E_DIR_NOT_EXISTS=1
E_COPY_FAIL=1

TEST_DIR=./test_dir
total_tests=0
failed_tests=0

function prepare_test_env {
	if [ -d "$TEST_DIR" ]; then
		echo "Aborting test '$TEST_DIR' directory exists." ;
		exit $E_DIR_EXISTS ;
	fi
	mkdir "$TEST_DIR" 
	cp -rf "$1" "$TEST_DIR/$(basename $1)"
}

function clear_test_env {
	rm -rf "$TEST_DIR" &> /dev/null
}

function execute_test {
   test_in_execution="$1"
   shift;
   echo -n "Test '$test_in_execution $@' has "
   test_output=`cd "$TEST_DIR" ; ./"$(basename $test_in_execution)" $@`
   error_code=$?
   found_fail=`echo "$test_output" | grep -i 'test.*fail'`
   mem_fail=`echo "$test_output" | grep -i 'memory.*fail'`
   if [ -n  "$found_fail" ] || [ -n "$mem_fail" ] || [ "$error_code" -ne 0 ]; then
      echo -e "'\e[0;31mfailed\e[0m'!"
      let 'failed_tests+=1'
      echo "$test_output"
   else
      echo -e "'\e[0;32mpassed\e[0m'!"
   fi
   let 'total_tests+=1'
}

if [ "$1" = "-l" ]; then
	echo "Executing tests that last longer!"
	TEST_FILES=`find ./ -name 'l_test_*.exe'`
        if [ ! -n "$TEST_FILES" ]; then
                TEST_FILES=`find ./ -name 'l_test_*' -type f -perm -u+x`
        fi
	shift
elif [ "$1" = "-c" ]; then
	echo "Executing client tests!"
	TEST_FILES=`find ./ -name 'c_test_*.exe'`
        if [ ! -n "$TEST_FILES" ]; then
                TEST_FILES=`find ./ -name 'c_test_*' -type f -perm -u+x`
        fi
	shift
else
	echo "Executing tests that does not last long!"
	TEST_FILES=`find ./ -name 'test_*.exe'`
        if [ ! -n "$TEST_FILES" ]; then
                TEST_FILES=`find ./ -name 'test_*' -type f -perm -u+x`
        fi
fi

if [ -n "$TEST_FILES" ]; then
   for test_p in $TEST_FILES
   do
      prepare_test_env $test_p
      execute_test $test_p $@
      clear_test_env 
   done
fi

if [ "$total_tests" -eq 0 ]; then
   echo "I could not find any tests to execute!"
else
   echo "Executed tests: $total_tests"
   echo "Failed tests:   $failed_tests"
fi

