##(c) 2024 Real-Time Technology Solutions, Inc. All Rights Reserved.
##
## Sample QuerySurge(TM) Run Multiple Test Suites Script in order
## version 0.1

#!/bin/bash

##  ' *******************************************************************************
##  ' ********************** Setup Connection Details *******************************
##  ' *****  Edit the following configuration variables to work with your       *****
##  ' *****  QuerySurge environment and preferences.                            *****
##  ' *******************************************************************************

##  ' ********************* START OF CONFIGURATION VARIABLES ************************

hostname="127.0.0.1"
port=80
username="admin"
password="admin"
projectId=1

# Scenario Name for the collection of Test Suites to run
scenarioName="My New Scenario"

# List of Test Suite IDs (Bash Array) to run the scenario, i.e. suiteIdList=(1 5 62)
suiteIdList=(1)

# Jenkins log parse tags - must match error filter in parsing rules file
# ie. error /QSJenkinsFail/
# requires set fail=QSJenkinsFail
failToken="QSJenkinsFail"

##  ' ********************* END OF CONFIGURATION VARIABLES ************************

# Login Authentication to obtain a sessionId to run other REST API commands
echo "Logging into REST API..."

loginReponse=$(curl -s -X POST "http://$hostname:$port/QuerySurge/api/auth/login" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"username\":\"$username\",\"password\":\"$password\",\"globalLogin\":false}")

sessionId=$(echo "$loginReponse" | grep -oP '(?<="sessionId":")[^"]*')

# Setup for REST API Endpoint related to executing a new QuerySurge Scenario
suiteIdListLength=${#suiteIdList[@]}

for (( i=0; i<$suiteIdListLength; i++ )); do
    formattedSuiteIdList="${formattedSuiteIdList}id=${suiteIdList[$i]}"
	
	if [ $i -lt $((${#suiteIdList[@]} - 1)) ]; then
		formattedSuiteIdList="${formattedSuiteIdList}&"
	fi
done

encodedScenarioName=""
for (( i=0; i<${#scenarioName}; i++ )); do
  c="${scenarioName:i:1}"
  case "$c" in
    [a-zA-Z0-9.~_-]) encodedScenarioName+="$c" ;;
    *) printf -v encodedScenarioName "%s%%%02X" "$encodedScenarioName" "'$c" ;;
  esac
done

# Executing a QuerySurge Scenario for each of the identified Suites by Suite ID
echo "Running Scenario '${scenarioName}'..."

executeScenarioResponse=$(curl -s -X POST "http://${hostname}:${port}/QuerySurge/api/project/${projectId}/execute/suite?${formattedSuiteIdList}&name=${encodedScenarioName}&inherit=false&appendtime=false" -H "accept: application/json" -H "X-QS-AUTH: ${sessionId}")

scenarioExecutionGUID=$(echo "$executeScenarioResponse" | grep -oP '(?<="guid":")[^"]*')

# Loop execution status request until the Scenario has completed
executeScenarioStatusResponse=$(curl -s -X GET "http://${hostname}:${port}/QuerySurge/api/project/${projectId}/status/scenario/${scenarioExecutionGUID}" -H "accept: application/json" -H "X-QS-AUTH: ${sessionId}")

scenarioExecutionOutcome=$(echo "$executeScenarioStatusResponse" | grep -oP '(?<="message":")[^"]*' | head -n1 | tail -1)

while [[ "$scenarioExecutionOutcome" == "Not Run" ]] || [[ "$scenarioExecutionOutcome" == "Running" ]] || [[ "$scenarioExecutionOutcome" == "Queued" ]]; do
	sleep 2.5
	executeScenarioStatusResponse=$(curl -s -X GET "http://${hostname}:${port}/QuerySurge/api/project/${projectId}/status/scenario/${scenarioExecutionGUID}" -H "accept: application/json" -H "X-QS-AUTH: ${sessionId}")

	scenarioExecutionOutcome=$(echo "$executeScenarioStatusResponse" | grep -oP '(?<="message":")[^"]*' | head -n1 | tail -1)
done

# Output if a failure occured while running the Scenario
if [[ "$scenarioExecutionOutcome" == "Failed" ]]; then
	echo "${failToken}: Scenario '${scenarioName}' failed!"
fi

# Logging out of session
echo "Logging out of REST API..."

logoutResponse=$(curl -s -X POST "http://${hostname}:${port}/QuerySurge/api/auth/logout" -H "accept: */*" -H "X-QS-AUTH: ${sessionId}")

echo "Done!"
read -n 1 -s -r -p ""
