#!/bin/sh

# shellcheck disable=SC1090
# shellcheck disable=SC2034
# shellcheck disable=SC2154

# check_azure_microsoft_defender_value
#
# Check Azure Microsoft Defender value
#
# This requires the Azure CLI to be installed and configured
#.

check_azure_microsoft_defender_value () {
  description="${1}"
  parameter_name="${2}"
  correct_value="${3}"
  correct_status="${4}"
  resource_type="${5}"
  print_function "check_azure_microsoft_defender_value"
  if [ "${resource_type}" = "" ]; then
    resource_check="ignore"
  else
    resource_check=$( az resource list --resource-type "${resource_type}" --output tsv )
  fi
  if [ "${resource_check}" = "" ]; then
    if [ "${correct_value}" = "Exists" ]; then
      inc_insecure    "Microsoft Defender \"${description}\" does not exist"
    else
      verbose_message "Azure Resource Type \"${resource_type}\" not found"
    fi
  else
    if [ "${correct_value}" = "Exists" ]; then
      inc_secure    "Microsoft Defender \"${description}\" exists"
    else
      check_message "Azure Microsoft Defender \"${description}\" parameter \"${parameter_name}\" is \"${function}\" to \"${correct_value}\""
      command="az security pricing show --name \"${parameter_name}\" --query \"pricingTier\" --output tsv 2> /dev/null"
      command_message      "${command}"
      actual_value=$( eval "${command}" )
      if [ "${actual_value}" = "${correct_value}" ]; then
        inc_secure    "Microsoft Defender \"${description}\" parameter \"${parameter_name}\" is \"${function}\" to \"${correct_value}\""
      else
        inc_insecure  "Microsoft Defender \"${description}\" parameter \"${parameter_name}\" is not \"${function}\" to \"${correct_value}\""
        if [ "${parameter_name}" = "CloudPosture" ]; then
          fix_message "az security pricing update --name \"${parameter_name}\" --tier \"${correct_value}\" --extensions name=ApiPosture isEnabled=true"
        else
          fix_message "az security pricing update --name \"${parameter_name}\" --tier \"${correct_value}\""
        fi
      fi
      if [ ! "${correct_status}" = "" ]; then
        check_message "Azure Microsoft Defender \"${description}\" Status is \"${function}\" to \"${correct_status}\""
        command="az security pricing show --name \"${parameter_name}\" --query \"[operationStatus]\" --output tsv 2> /dev/null"
        command_message       "${command}"
        actual_status=$( eval "${command}" )
        if [ "${actual_status}" = "${correct_status}" ]; then
          inc_secure   "Microsoft Defender \"${description}\" Status is \"${function}\" to \"${correct_status}\""
        else
          inc_insecure "Microsoft Defender \"${description}\" Status is not \"${function}\" to \"${correct_status}\""
        fi
      fi
    fi
  fi
}
