#!/bin/bash -e

# Includes
PATH="${PATH}:/usr/share/con-dev" . con-lib.bash
con::include opt conf

DEFAULT_GROUPLIST="lib libopt libconf "
DEFAULT_GROUPLIST+="vc:git,svn "
DEFAULT_GROUPLIST+="bs:autotools,cmake "
#DEFAULT_GROUPLIST+="release:autotools@git,cmake@git,autotools@svn,cmake@svn"

# Global configs for test run
export CON_LOG_LEVEL="info"
export CON_AUTO_MODE=true
export CON_KEEP_MODE=false

# Set testsuite git author
export GIT_COMMITTER_NAME="con-dev testsuite"
export GIT_COMMITTER_EMAIL="con-dev@testsuite.invalid"

testsuite_usage="con-dev test suite

-g <grouplist>: Test suite groups to run; syntax GROUPNAME:i0,i1,...,in ...
 default=${DEFAULT_GROUPLIST}
-n            : No action mode"

testsuite()
{
	# Iterate over all given groups
	for TS_GROUP_ID in ${main_opt_g}; do
		TS_GROUP=$(cut -d: -f1 <<< "${TS_GROUP_ID}")
		TS_ITERS=$(cut -d: -f2- <<< "${TS_GROUP_ID}" | tr ',' ' ')

		# Iterate over all given TS_ITER values
		con::trap:reset
		for TS_ITER in ${TS_ITERS}; do
			# Run test group in a sbshell, so we don't influence this script
			(
				con::trap:init
				con::term:printf "bold" "\n%s\n" "==> Running testsuite group: ${TS_GROUP}[${TS_ITER}]:"

				# Source the actual testsuite group cases
				. $(dirname "${0}")/testsuite.${TS_GROUP}.bash

				TS_DIR="$(pwd)/testsuite.tmp/${TS_GROUP}/${TS_ITER}"
				printf "%s\n" "Purging/entering dir: ${TS_DIR}"
				${main_opt_n} || { rm -rf "${TS_DIR}" && mkdir -p "${TS_DIR}" && cd "${TS_DIR}"; }

				# Run all test cases
				for TS_CASE in $(declare -F | cut -d" " -f3- | grep "^con::testcase_"); do
					con::term:printf "underline" "=> Running test case %s:\n" "${TS_CASE}"
					if ${main_opt_n}; then
						printf "%s\n" "Skipping, no action mode"
					else
						${TS_CASE}
					fi
				done
			)
		done
	done

	con::term:printf "bold,green" "\nTestsuite succeeded: %s\n" "${main_opt_g}"
}

con_opt::run "${@}"
