#!/bin/bash
# Script to check if the important wazuh services are running
# Author: Sebastian Klee, E-Mail: s.klee@timmehosting.de
# Version: 1.2
# Date: 14.10.2025

# Variables
counter_running=0
wazuh_server=$1
# The variable "pattern_exceptions" receives wazuh services from the monitoring, whose status should be ignored by the check.
pattern_exceptions=$2

# API request to get an access token
token_wazuh_request=$(curl -s --netrc-file /etc/icinga2/scripts/api_u/wazuh_ic2.cnf -k -X POST https://"$wazuh_server":55000/security/user/authenticate | jq | tr -d '" ' | awk -F ':' ' /token/ {print$2}')
# API request to determine the status of the wazuh services
wazuh_services=$(curl -s -H "Authorization: Bearer $token_wazuh_request" -k -X GET https://"$wazuh_server":55000/cluster/waz-se1/status | jq | tr -d '", ' | awk -F ':' ' /wazuh/ {print}')

# Repeat the for-loop for each wazuh service
for i in $wazuh_services; do
# Write the stopped services, unless they belong to the exceptions, into the array "stopped_services" and increment the variable "counter_running" by one.
if [[ ! $i =~ 'running' ]] && [[ ! $i =~ $pattern_exceptions ]]; then
stopped_services[counter_running]=$i
((counter_running++))
fi
done

# If the variable counter_running is greater than 0, we know that at least on important wazuh service is stopped.
if [[ counter_running -gt 0 ]]; then
  index=0
  size=${#stopped_services[@]}
  echo "Important Wazuh Services are stopped:"
  for ((index = 0 ; index < size ; index++ )); do
  echo "${stopped_services[index]}"
  done
  exit 2
else
  echo "All important Wazuh Services are running:"
  for i in $wazuh_services; do
   echo "$i" | awk '$0 ~ /running/ { print$0 }'
  done
  exit 0
fi
