#!/bin/bash
# Script to run a project's unit tests via command line.

. $(dirname "$0")/utils.sh

STES_COUNT=1

# Amount of parameters passed in
PARAMS_COUNT=$#

# The platform to run tests on. Accepted values: EditMode, PlayMode
PLATFORM=$1

print_usage()
{
	echo "Error: Missing some parameters."
	echo ""
	echo "Usage: "
	echo "$ unit_tests.sh [<test_platform>]"
	echo "where:"
	bcho "  <test_platform>" ": The platform to run tests on. Accepted values: "
	bcho "                      EditMode" ": Edit Mode tests. Equivalent to running tests from the EditMode tab of the Test Runner window."
	bcho "                      PlayMode" ": Play Mode tests that run in the Editor. Equivalent to running tests from the PlayMode tab of the Test Runner window."
	echo "                      Any value from the BuildTarget enum: Play Mode tests that run on a player built for the specified platform. Equivalent to using the Run all tests (<target_platform>) dropdown in the PlayMode tab of the Test Runner window."
	echo "                   Note: If no value is specified for this argument, tests run in Edit Mode."
	echo ""
	echo "Unit tests results are stored in <project_root_folder>/UnitTests/<test_platform>.results.xml"
	echo ""
	echo "Example: unit_tests PlayMode"
	echo "More information: https://docs.unity3d.com/Packages/com.unity.test-framework@1.1/manual/reference-command-line.html"
}

customise_params()
{
	PARAMS_COUNT=1
	PLATFORM=PlayMode
	LOG_FILENAME=""
}

validate_input()
{
	#if [ $PARAMS_COUNT -le 0 ]; then
	#    print_usage
	#    exit 1
	#fi

	if [ $PARAMS_COUNT -eq 0  ]; then
		PLATFORM="EditMode"
		echo -e "Using \033[1m${PLATFORM}\033[0m as <test_plaform> since no <test_platform> was passed in."
	fi
}

init_params()
{
	# The path where Unity should save the results file. 
	RESULTS_PATH="UnitTests/${PLATFORM}.results.xml"
}

run_tests()
{
	run_unity_command "-runTests -batchmode -projectPath . -testResults ${RESULTS_PATH} -testPlatform ${PLATFORM}"
}

print_result()
{
	# Pattern to serach: Searches for any failed results
	PATTERN="Failed"

	# Search for pattern
	grep_output="$(grep ${PATTERN} ${RESULTS_PATH})"

	if [ $? -eq 0 ]; then
	    echo "Some unit tests failed!"

	    # Print failed unit tests out
	    echo "$grep_output"

	    # Stop the pipeline
	    exit 1
	else
	    echo "All unit tests passed!"
	fi
}

# Uncomment this line to use custom params
#customise_params
prepare_script
validate_input
init_params
run_tests
print_result
