#!/bin/bash

. /usr/lib/nagios/plugins/utils.sh

check_return() {
   if [[ $1 -ne 0 ]]; then
      echo "CRITICAL - Service FAIL"
      exit $STATE_CRITICAL
   fi
}

exec_status=$(curl -s https://api.swedenconnect.se/testid/qa/execution-status | jq --raw-output .)

exec_status_result=$?
check_return "$exec_status_result"

calculate_time() {
     md_date=$(date -d "$1" +%s)
     now=$(date +%s)
     diff=$(("$md_date"-"$now"))

     if ((diff < 0)); then ((diff*=-1)); fi
     echo $diff
}


###Check if the exection is too old

exec_time=$(echo "$exec_status" | jq --raw-output '."last execution result".executiontimestamp')

exec_time_result=$?
check_return "$exec_time_result"

diff_exec_time=$(calculate_time "$exec_time")

day=$(( 24 * 3600))

if [ "$diff_exec_time" -gt "$day" ]; then
   echo "CRITICAL - tests are too old!!"
   exit $STATE_CRITICAL

fi

###Check if XA, XB are not executed

raw_not_executed_test=$(echo "$exec_status" | jq --raw-output '."last execution result".notExecutedTests[]')

declare -a not_executed_test=($(echo "$raw_not_executed_test" | tr "\n" " "))

if [[ "${not_executed_test[*]}" == *"XA"* ]] ||  [[ "${not_executed_test[*]}" == *"XB"* ]]
then
   echo "XA, XB or both not executed"
   exit $STATE_CRITICAL
fi

###Exit critical if no tests have passed

raw_passed_tests=$(echo "$exec_status" | jq --raw-output '."last execution result".passed[0].result')

declare -a passed_tests=($(echo "$raw_passed_tests" | tr "\n" " "))

echo $passed_tests

if [ "$passed_tests" == null ]
then
   echo "No tests have passed"
   exit $STATE_CRITICAL
fi

#Check if any of the failed tests are XA, XB

raw_lands=$(curl -s https://api.swedenconnect.se/testid/qa/execution-status | jq --raw-output '."last execution result".failed[].result')

raw_lands_result=$?
check_return "$raw_lands_result"

declare -a lands=($(echo $raw_lands | tr "\n" " "))

exit_status=0
output=""

for land in "${lands[@]}"
do
 if [[ "$land" == XA* ]]
 then
     exit_status=1
     output="$output $land test country failing"
 fi
 if [[ "$land" == XB* ]]
 then
     exit_status=1
     output="$output $land test country failing"
 fi
done

if [ "$exit_status" -gt 0 ]
then
    echo "$output"
    exit $STATE_CRITICAL
else
   echo "Tests on test lands are error free"
   exit $STATE_OK
fi