#!/bin/bash

set -eu
# __SILENT=TRUE
. /opt/fox_utils/crab_sys.sh
[ "${1:--help}" = "--help" ] && sys::usage "$@"
### --help Info: обходчик тестов с отчетом в конце
### --help Usage: test [tag1] [tag2] [tag3] [--failstop]
### --help Example: test slow; test fast; test web; test slow_web; test web model inst

sys::arg_parse "$@"

SHORT_NAME="${0##*/}"
DIR="$(readlink -f ${0%/*})"
echo "start test in $DIR"
cd "$DIR"
RETS=0
REPORT=''
do_test(){
	local t ret tmp kwords must_test
	for t in ./* ./*/*; do
		[[ "$t" == *'*'* ]] && continue
		[ -d "$t" ] && continue
		[ "$t" = "./test" ] && continue
		[ ! -x "$t" ] && continue
		if [ -n "${*/--failstop/}" ]; then
			must_test=FALSE
			tmp="${t#*/}"; tmp="${tmp%/*}"
			for kwords in "${@/--failstop/}"; do
				[[ "$tmp" == "$kwords" ]] && must_test=TRUE
				[[ "$tmp" == *"_$kwords" ]] && must_test=TRUE
				[[ "$tmp" == "${kwords}_"* ]] && must_test=TRUE
				[[ "$tmp" == *"_${kwords}_"* ]] && must_test=TRUE
			done
			[ "$must_test" = FALSE ] && continue
		fi
		"$t" && ret=0 || ret=$?
		[ "$ret" != 0 -a "${ARG_FAILSTOP:-}" = TRUE ] && exit $ret
		REPORT="${REPORT}Report test: $t"
		if [ $ret = 0 ]; then
			REPORT="$REPORT - OK"
		else
			REPORT="$REPORT - FAILED ret=$ret"
		fi
		REPORT="$REPORT"$'\n'
		RETS=$((RETS+$ret))
	done
	return 0
}
do_test "$@"
echo "$REPORT"
echo "ERROR=$RETS"
[ "$RETS" != 0 ] && exit 1
exit 0
