#!/bin/bash
set -e

RED=$'\033[31m'
GREEN=$'\033[32m'
TEXTRESET=$'\033[0m' # reset the foreground colour

# This helper function walks the current directory looking for directories
# holding certain files ($1 parameter), and prints their paths on standard
# output, one per line.
find_dirs() {
    find . -not \( \
         \( \
         -path './integration/*' \
         -o -path './.git/*' \
         -o -path './vendor/*' \
         -o -path './bundles/*' \
         \) \
         -prune \
         \) -name "$1" -print0 | xargs -0n1 dirname | sort -u
}

TESTFLAGS="-cover -coverprofile=cover.out ${TESTFLAGS}"

if [ -z "$TESTDIRS" ]; then
    TESTDIRS=$(find_dirs '*_test.go')
fi

TESTS_FAILED=()

set +e
for dir in $TESTDIRS; do
    echo '+ go test -race' $TESTFLAGS "${LIBCOMPOSE_PKG}/${dir#./}"
    go test -race ${TESTFLAGS} "${LIBCOMPOSE_PKG}/${dir#./}"
    if [ $? != 0 ]; then
        TESTS_FAILED+=("$dir")
        echo
        echo "${RED}Tests failed: ${LIBCOMPOSE_PKG}${TEXTRESET}"
        sleep 1 # give it a second, so observers watching can take note
    fi
done

echo
echo "Run non-race test (if any)"
for dir in $TESTDIRS; do
    if [ -n "$(grep --include '*_test.go' -l -ri '!race' ${dir})" ]; then
        echo '+ go test ' $TESTFLAGS "${LIBCOMPOSE_PKG}/${dir#./}"
        go test ${TESTFLAGS} "${LIBCOMPOSE_PKG}/${dir#./}"
        if [ $? != 0 ]; then
            TESTS_FAILED+=("$dir")
            echo
            echo "${RED}Tests failed: ${LIBCOMPOSE_PKG}${TEXTRESET}"
            sleep 1 # give it a second, so observers watching can take note
        fi
    fi
done
set -e

echo

# if some tests fail, we want the bundlescript to fail, but we want to
# try running ALL the tests first, hence TESTS_FAILED
if [ "${#TESTS_FAILED[@]}" -gt 0 ]; then
    echo "${RED}Test failures in: ${TESTS_FAILED[@]}${TEXTRESET}"
    echo
    false
else
    echo "${GREEN}Test success${TEXTRESET}"
    echo
    true
fi
