#!/bin/bash

##(c) 2024 Real-Time Technology Solutions, Inc. All Rights Reserved.
##
## Sample QuerySurge(TM) Run Multiple Test Suites Script
## version 0.1

#  *******************************************************************************
#  Setup Notes:
#  a) jq is required to run these samples (https://stedolan.github.io/jq)
#  b) You may need to run with local admin rights to run these samples
#  c) These samples assume the QuerySurge Tutorial data has been installed
#  *******************************************************************************

##  ' *******************************************************************************
##  ' ********************** Setup Connection Details *******************************
##  ' *****  Edit the following configuration variables to work with your       *****
##  ' *****  QuerySurge environment and preferences.                            *****
##  ' *******************************************************************************

##  ' ********************* START OF CONFIGURATION VARIABLES ************************
username="admin"
password="admin"
hostname="127.0.0.1"
port=80
projectId=1
scenarioName="My New Scenario"
suiteIdList="1"
##  ' ********************* END OF CONFIGURATION VARIABLES ************************

suiteIdArray=(${suiteIdList//,/ })

# Login Authentication to obtain a sessionId to run other REST API commands
echo "--- start --------------------------------"
echo "Logging into REST API..."
response=$(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=$(jq -r '.sessionId' <<< "${response}")
# Setup for REST API Endpoint related to executing a new QuerySurge Scenario
for suiteId in "${suiteIdArray[@]}"
do
        formattedSuiteIdList+="id=$suiteId&"
done
formattedSuiteIdList="${formattedSuiteIdList::-1}"
encoded_name=$(jq -sRr @uri <<< "${scenarioName}")

# Executing a QuerySurge Scenario for each of the identified Suites by Suite ID
response=$(curl -s -X POST "http://$hostname:$port/QuerySurge/api/project/$projectId/execute/suite?$formattedSuiteIdList&name=$encoded_name" -H "accept: application/json"  -H "X-QS-AUTH: $sessionId" -H "Content-Type: application/json")        
scenarioExecutionGUID=$(jq -r '.guid' <<< "${response}")
echo "Scenario execution started"
echo "Scenario executionId: $scenarioExecutionGUID"

# Logging out of session
echo "Logging out"
$(curl -s -X POST "http://$hostname:$port/QuerySurge/api/auth/logout" -H "accept: */*" -H "X-QS-AUTH: ${sessionId}" )
echo "--- end --------------------------------"