#!/bin/bash -e
#
# Run all rkt tests
# ./test
# ./test -v
#
# Run tests for one package
#
# PKG=./store ./test
# PKG=store ./test

# Invoke ./cover for HTML output
COVER=${COVER:-"-cover"}

source ./build

function find_dirs_with_suffixed_files
{
    # File suffix, can contain dots, asterisks and question marks -
    # they will be escaped. Use of other metacharacters is at your own
    # risk.
    local suffix="$1"
    # Escape question mark and asterisk metacharacters from suffix, so
    # they are matched literally in find command.
    local find_escaped_suffix=$(echo "${suffix}" | sed -e 's/\([?*]\)/\\\1/g')
    # Escape dot and asterisk metacharacters from suffix, so they are
    # matched literally in sed 's' command.
    local sed_escaped_suffix=$(echo "${suffix}" | sed -e 's/\([.*]\)/\\\1/g')
    # Variable 'exclude' is an POSIX ERE fragment to be put between
    # '^(' and ')$'.
    local exclude="$2"
    # Find all files ending with given suffix, ...
    find . -name '*'"${find_escaped_suffix}" |
	# ... remove files with given suffix together with preceding slash, ...
	sed -e 's/\/[[:alnum:]_]\+'"${sed_escaped_suffix}"'//g' |
	# ... remove leading './', ...
	sed -e 's/^\.\///g' |
	# ... sort alphabetically, ...
	sort |
	# ... remove repeated directories, ...
	uniq |
	# ... and filter out given directories.
	grep -vEe '^('"${exclude}"')$'
}

TESTABLE_AND_FORMATTABLE=$(find_dirs_with_suffixed_files '_test.go' 'Godeps/.*|tests')
FORMATTABLE=$(find_dirs_with_suffixed_files '.go' 'Godeps/.*')

# user has not provided PKG override
if [ -z "$PKG" ]; then
	TEST=$TESTABLE_AND_FORMATTABLE
	FMT=$FORMATTABLE

# user has provided PKG override
else
	# strip out leading dotslashes and trailing slashes from PKG=./foo/
	TEST=${PKG/#./}
	TEST=${TEST/#\//}
	TEST=${TEST/%\//}

	# only run gofmt on packages provided by user
	FMT="$TEST"
fi

# split TEST into an array and prepend REPO_PATH to each local package
split=(${TEST// / })
TEST=${split[@]/#/${REPO_PATH}/}

echo "Running tests..."
go test -timeout 60s ${COVER} $@ ${TEST} --race

echo "Checking gofmt..."
fmtRes=$(gofmt -l $FMT)
if [ -n "${fmtRes}" ]; then
	echo -e "gofmt checking failed:\n${fmtRes}"
	exit 255
fi

# split FMT into an array and prepend REPO_PATH to each local package for go vet
split_vet=(${FMT// / })
VET_TEST=${split_vet[@]/#/${REPO_PATH}/}

echo "Checking govet..."
vetRes=$(go vet $VET_TEST)
if [ -n "${vetRes}" ]; then
	echo -e "govet checking failed:\n${vetRes}"
	exit 255
fi

# Functional tests use 'sudo' to run as root - it's more dangerous
# than unit tests and may require typing a password. Only run them
# inside well-known CI systems.
if [ "$CI" == true -a -e bin/stage1.aci ] ; then
	if [ "${CIRCLECI}" == true -o "${SEMAPHORE}" == true ] ; then
		echo "Checking functional tests..."
		(cd tests && ./test)
	else
		echo "Functional tests disabled."
	fi
else
	echo "Functional tests disabled."
fi

echo "Success"
