#!/bin/bash

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
ROOT=$(cd $HERE/../..; pwd)
READIES=$ROOT/deps/readies

(( VERBOSE > 1 )) && { set -x; PS4='$LINENO: '; }

if [[ $1 == --help || $1 == help ]]; then
	cat <<-END
		Invoke QA Automation tests

		[ARGVARS...] run [--help|help]

		Argument variables:
		QA_AUTOMATION_TOKEN=token     QA automation (Opereto) token
		QA_AUTOMATION_EMAIL=addr      Send notification to `addr` (optional)
		TEST=name                     Name of .json parameters file
		MODULE_VERSION=ver            Module version to test. Default: master
		RS_VERSION=ver                Run on specified RS version
		RS_VERSIONS"ver..."           Run on specified RS versions
		NOP=1                         Do not execute automation command
		VERBOSE=N                     Set verbosity level (N=1,2)
		QUICK=1                       Only test one RS version

		Other configuration:
		RS_VERSIONS file includes Redis Enterprive versions for release tests.

	END
	exit 0
fi

export RS_MODULE=RedisTS
export RS_MODULE_FILE_PREFIX=redistimeseries

if [[ -z $QA_AUTOMATION_TOKEN && $NOP != 1 ]]; then
	echo "Variable QA_AUTOMATION_TOKEN is undefined." >&2
	exit 1
fi

export TEST=${TEST:-release}
if [[ ! -f $HERE/$TEST.json ]]; then
	echo "Invalid TEST name: $TEST" >&2
	exit 1
fi

run_test() {
	export RS_VERSION=$1

	if [[ -z $MODULE_VERSION ]]; then
		export MODULE_VERSION=master
	else
		export MODULE_VERSION=$(echo "$MODULE_VERSION" | sed  's/^v\(.*\)/\1/')
	fi

	results() {
		echo "$JSON" | jq "$1" | cut -d\" -f2
	}

	cd $HERE

	if [[ -n $QA_AUTOMATION_EMAIL ]]; then
		export EMAIL_CLAUSE="\"email_recipients\": \"$QA_AUTOMATION_EMAIL\","
	else
		export EMAIL_CLAUSE=""
	fi
	json_in=$(mktemp /tmp/$TEST.json.XXXX)
	$READIES/bin/xtx -e RS_MODULE -e RS_MODULE_FILE_PREFIX -e MODULE_VERSION -e RS_VERSION -e EMAIL_CLAUSE $TEST.json > $json_in
	(( VERBOSE >= 1 )) && cat $json_in

	if [[ $NOP == 1 ]]; then
		echo "Testing RS $RS_VERSION"
		return 0
	fi

 	OPERETO3_URL="opereto.qa.redislabs.com"
	JSON=$(curl -sk \
   		-X POST -H "Content-Type: application/json" \
   		-H "Authorization: Bearer $QA_AUTOMATION_TOKEN" \
   		-d @$json_in \
   		https://$OPERETO3_URL/processes 2>&1)

	rc=$?
	rm $json_in
	status=$(results .status)
	if [[ $rc == 0 && $status == success ]]; then
		id=$(results .data[0])
		echo "Tests running on $MODULE_VERSION for RS $RS_VERSION"
		echo "Results: https://$OPERETO3_URL/ui#dashboard/flow/$id"
		return 0
	else
		err=$(results .message)
		echo "Failed to run tests on $MODULE_VERSION for RS $RS_VERSION: $err"
		return 1
	fi
}

[[ -n $RS_VERSION ]] && RS_VERSIONS="$RS_VERSION"
if [[ -z $RS_VERSIONS ]]; then
	if [[ $QUICK == 1 ]]; then
		RS_VERSIONS=$(cat $HERE/RS_VERSIONS | head -1)
	else
		RS_VERSIONS=$(cat $HERE/RS_VERSIONS)
	fi
fi

rc=0
for RS_VERSION in $RS_VERSIONS; do
	run_test $RS_VERSION
	[[ $? != 0 && $rc == 0 ]] && rc=$?
done
exit $rc
