#!/bin/bash

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
ROOT=$(cd $HERE/../.. && pwd)
READIES=$ROOT/opt/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
		TEST=name                     Name of .json parameters file
		MODULE_VERSION=ver            Module version to test. Default: master
		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=RedisAI
export RS_MODULE_LC=${RS_MODULE,,}
export RS_MODULE_FILE_PREFIX=redisai-cpu
export VARIANT=${VARIANT}  # for variants such as RedisAILite. We append -lite (see circleci for an example)

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() {
    set -x
	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

	json_in=$(mktemp /tmp/$TEST.json.XXXX)
	$READIES/bin/xtx -e VARIANT -e RS_MODULE -e RS_MODULE_LC -e RS_MODULE_FILE_PREFIX -e MODULE_VERSION -e RS_VERSION $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
}

rc=0
# By default we use RS_VERSIONS, but with variants they may need to specify their own redis verisons, hence this file
VERSIONFILE=${HERE}/RS_VERSIONS${VARIANT}
if [[ $QUICK == 1 ]]; then
	RS_VERSIONS=$(cat $VERSIONFILE | head -1)
else
    RS_VERSIONS=$(cat $VERSIONFILE)
fi
for RS_VERSION in $RS_VERSIONS; do
	run_test $RS_VERSION
	[[ $? != 0 && $rc == 0 ]] && rc=$?
done
exit $rc
