clr_smart=`echo $1 | cut -d'_' -f2-`
test_department=`echo $clr_smart | awk -F'.' '{print $1}'`
test_region=`echo $clr_smart | awk -F'.' '{print $2}'`
test_environment=`echo $clr_smart | awk -F'.' '{print $3}'`
test_name=`echo $clr_smart | cut -d'.' -f4-` #awk -F'.' '{print $4}'`

responsefile_path=$2
elasticserach_URL=$3
user=$4
password=$5
index_pattern=$6
interval_minutes=$7; [ -z $interval_minutes ] && interval_minutes=17
month_prefix=`date -u +%Y.%m`

execIdsRequest='
{
  "aggs" : {
    "time_range" : {
      "date_range" : {
        "field" : "timestamp",
        "ranges": [
            { "from": "now-'"$interval_minutes"'m/m" }
        ]
      },
      "aggs" : {
        "test_name": { "filter": { "term" : { "test_name.keyword" : "'"$test_name"'" } },
          "aggs": {
            "test_department": { "filter": { "term" : { "test_department.keyword" : "'"$test_department"'" } },
              "aggs": {
                "test_region": { "filter": { "term" : { "test_region.keyword" : "'"$test_region"'" } },
                  "aggs": {
                    "test_environment": { "filter": { "term" : { "test_environment.keyword" : "'"$test_environment"'" } },
                      "aggs": {
                        "step_type": { "filter": { "term" : { "step_type.keyword" : "total" } },
                          "aggs": {
                            "wn_hostname": {
                              "terms": {
                                "field": "wn_hostname.keyword",
                                "size": 100
                              },
                              "aggs": {
                                "latest": {
                                  "top_hits": {
                                    "size": 1,
                                    "sort": { "timestamp": { "order": "desc" } }
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
		            }
                  }
                }
              }
	        }
          }
        }
      }
    }
  }
}'
execIds=(`echo $execIdsRequest | curl -s -XGET -u "$user":"$password" "$elasticserach_URL/$index_pattern-$month_prefix*/_search?size=0" -H 'Content-Type: application/json' -d @- | \
jq -r '.aggregations.time_range.buckets[].test_name.test_department.test_region.test_environment.step_type.wn_hostname.buckets[].latest.hits.hits[]._source.executionId //empty'`)

if [ -z "$execIds" ]
then
  echo "Empty response for the $interval_minutes min timeframe! Assuming no data available"
  exit
fi

for i in ${execIds[@]}
do
stepsPerExecIdRequest='
{
  "query":{
    "bool":{
      "must":[
        { "term":{ "executionId.keyword": "'"$i"'" } },
        { "term":{ "step_type.keyword": "total" } }
      ],
      "filter":{ "range":{ "timestamp":{ "from": "now-'"$interval_minutes"'m/m" } } }
    }
  },
  "sort": { "timestamp": { "order": "desc" } }
}'

stepsPerExecId+=`echo $stepsPerExecIdRequest | curl -s -XGET -u "$user":"$password" "$elasticserach_URL/$index_pattern-$month_prefix*/_search?size=1500&pretty" -H 'Content-Type: application/json' -d @-`
done

###### RESPONSE DEBUG #####
#dt=` date -u +%s`
#echo "${execIds[@]}" > /tmp/SMART_GLI_LOG/"$test_department.$test_region.$test_environment.$test_name.$dt.json"
#echo "$stepsPerExecId" >> /tmp/SMART_GLI_LOG/"$test_department.$test_region.$test_environment.$test_name.$dt.json"
###########################

st=`jq '.hits.hits[] //empty' <<< $stepsPerExecId`

if [ -z "$st" ]
then
  echo "No steps found by executionId(s) ["${execIds[@]}"] for $interval_minutes min timeframe! Assuming GLI issue"
  exit
fi

stepsPerExecId=`jq -s '.' <<< $stepsPerExecId`

for (( i=0; i < `jq 'length' <<< $stepsPerExecId`; i++ )) #for each of last execIds
do
  if [ `jq "[.[$i].hits.hits[]|select(._source.step_status==false)]|length"  <<< $stepsPerExecId` -gt 0 ] #if step_status = false at least once per executionId
  then
    stepsPerExecId=`jq ".[$i].hits.hits[]._source.SMART_executionStatus=false" <<< $stepsPerExecId`
    errors+=`jq "[.[$i].hits.hits[]._source|select(.step_status==false)][0]"  <<< $stepsPerExecId` #pick the latest error per executionId
  else
    stepsPerExecId=`jq ".[$i].hits.hits[]._source.SMART_executionStatus=true" <<< $stepsPerExecId`
  fi
done

healthyInstances=`jq '[.[].hits.hits[]|select(._source.SMART_executionStatus == true)]|length' <<< $stepsPerExecId`

stepPerExecId=`jq '.[].hits.hits[0]._source' <<< $stepsPerExecId`

if [ $healthyInstances -eq 0 ]
then
consecutive_fails=`jq '.[-1].SMART_consecutive_fails //0' "$responsefile_path"`
(( consecutive_fails++ ))

jq -s ". += [{SMART_rollup_status:false, SMART_consecutive_fails:$consecutive_fails}]" <<< $errors > "$responsefile_path"

echo -e "$test_department $test_region $test_environment $test_name test has failed on all watcher nodes simultaneously.
Test URL: `jq -rs .[0].test_targetUrl <<< $errors`
Details:"
length=$(echo `echo $errors | jq -s '.|length'`-1 | bc -l)
resp_arr=`echo $errors | jq -s .`

for (( i=0; i<=$length; i++ ))
do
wn_name=`echo $resp_arr | jq -r .[$i].wn_hostname`
step_name=`echo $resp_arr | jq -r .[$i].step_name`
step_desc=`echo $resp_arr | jq -r .[$i].step_description`
er_mess=`echo $resp_arr | jq -r .[$i].step_exception | sed '/<a href/d'`
er_snapshot=`echo $resp_arr | jq -r .[$i].test_errorSnapshot`
fiddler_log=`echo $resp_arr | jq -r .[$i].test_fiddlerLog`
browser_name=`echo $resp_arr | jq -r .[$i].test_browserName`
browser_version=`echo $resp_arr | jq -r .[$i].test_browserVersion`

echo -e "
Watcher Node name: $wn_name
Step Name: $step_name
Step Description: $step_desc
Error Message: $er_mess
Error Snapshot: $er_snapshot
Fiddler Log: $fiddler_log
Browser Name: $browser_name
Browser Version: $browser_version
" | sed -e 's,`,\\`,g' -e 's,",'"'"',g'
done

else
  echo The "'$test_department $test_region $test_environment $test_name'" test is now in OK state.
  jq -s '. += [{SMART_rollup_status:true}]' <<< $stepPerExecId > "$responsefile_path"
fi
