#!/bin/bash

#######
## This simple script uses systemctl to check if services are down
## Author: Sebastian Klee, E-Mail: s.klee@timmehosting.de
## Version: 1.2
## Date: 23.09.2024
#######

# Exceptions for services, which are not that critical for the running system
exceptions="$1";

# Variables for the supervisor check
exec_stop=0
exec_start=0

# The output of the systemctl command(all failed services, excluding the services from the "exceptions" variable) is passed to the variable "failed_services".
failed_services=$(systemctl list-units --state failed --no-legend | grep -Ev "$exceptions")

# Determine if supervisor is installed
service_bin="/usr/bin/supervisord"
if [[ -f $service_bin ]]; then
# The states of the supervisor service that we determine to determine whether the service is running
exec_stop=$(systemctl status supervisor.service | grep 'ExecStop' | awk -F '=|/' '{print $7}' | tr -d '/')
exec_start=$(systemctl status supervisor.service | grep 'ExecStart' | awk -F '=|/|)' '{print $10}')
fi

# Determine the number of characters in the Variable "failed_services" and pass the value to the variable "size_variable".
size_variable=${#failed_services}

# If the number of characters in the Variable "size_variable" is greater than 1, the script exits with the exit code 2(critical), otherwise with the exit code 0(ok).
if [ "$size_variable" -gt "1" ]
  then
    echo "Folgenden Dienste haben den State \"failed\" und sollten geprueft werden:"
    systemctl list-units --state failed | grep -Ev "$exceptions" | grep -Ev 'The|Reflects|units listed'
    # Also check if supervisor is running.
    if [[ $exec_stop -gt "0" ]] || [[ $exec_start -gt "0" ]]; 
     then
      echo -e "!! Supervisor scheint auch nicht zu laufen und sollte geprueft werden: !!"
      systemctl list-units supervisor.service | grep "supervisor.service"
    fi
    exit 2
# If Supervisor is not running exit the script with exit code2(critical).
elif [[ $exec_stop -gt "0" ]] || [[ $exec_start -gt "0" ]];
  then
    echo "Supervisor scheint nicht zu laufen und sollte geprueft werden:"
    systemctl list-units supervisor.service | grep "supervisor.service"
    exit 2
# Exit the script with the exit code 0(ok) if there is no problem with the services.
else
    echo "Kein wichtiger Service \"failed\"!"
    exit 0
fi

