#!/usr/bin/env bash
set -e -o pipefail

source hack/validate/.validate

added_tests() {
	validate_diff --diff-filter=ACMR --unified=0 -- 'integration/*_test.go' \
		| grep -E '^(\+func Test)(.*)(\*testing\.T\))' \
		| sed -E 's/^\+func (Test[A-Za-z0-9_]*).*/\1/' \
		|| true
}

changed_tests() {
	validate_diff --diff-filter=ACMR --function-context -- 'integration/*_test.go' \
		| grep -E '^ func Test[A-Za-z0-9_]*\(.*\*testing\.T\)' \
		| sed -E 's/^ func (Test[A-Za-z0-9_]*).*/\1/' \
		|| true
}

run_integration_flaky() {
	tests=$(
		{
			added_tests
			changed_tests
		} | sort -u
	)

	if [ -z "$tests" ]; then
		echo 'No new or modified tests found in integration.'
		return
	fi

	echo
	echo "Found new or modified integration tests:"
	echo "$tests"
	echo "Running stress test for them."

	(
		TESTARRAY=$(echo "$tests" | tr '\n' '|')
		# Note: TEST_REPEAT will make the test suite run 5 times, restarting the daemon
		# and each test will run 5 times in a row under the same daemon.
		# This will make a total of 25 runs for each test in TESTARRAY.
		export TEST_REPEAT=5
		export TESTFLAGS="-test.count ${TEST_REPEAT} -test.run ${TESTARRAY%?}"
		echo "Using test flags: $TESTFLAGS"
		source hack/make/test-integration
	)
}

run_integration_flaky
