#!/bin/bash
# ================================================================================
#
# CHECK A SINGLE SYSTEMD SERVICE
#
# (1)
# shows overview of important services - edit check_systemdservices.cfg to define
# them
#
# (2)
# resturns
# - OK      if all systemd servises are running
# - UNKNOWN if systemctl command is not available
# - ERROR   if any systemd service is not running
#
# -------------------------------------------------------------------------------
# 2023-09-05  v01.0  <axel.hahn@unibe.ch>
# ================================================================================

. $( dirname $0 )/inc_pluginfunctions

export self_APPVERSION=1.0

# ----------------------------------------------------------------------
# FUNCTIONS
# ----------------------------------------------------------------------

# show help text
function showHelp(){
    local _self; _self=$(basename $0)
cat <<EOF
$( ph.showImlHelpHeader )

Check a unit using systemctl status.

The status is unknown if the command systemctl is not found.
The status is critical if the service does not exist or is not running.

SYNTAX:
  $_self [-h] UNIT

OPTIONS:
  -h     this help
  UNIT   Name of a unit - see output of 'systemctl' 

EXAMPLES:

  $_self mysql.service
         show status of service mysql

EOF
}

# ----------------------------------------------------------------------
# MAIN
# ----------------------------------------------------------------------

ph.hasParamoption "h" "$@"; bOptHelp=$?

if [ $bOptHelp -eq 0 -o $# -eq 0 ]; then
    showHelp
    exit 0
fi

ph.require "systemctl"

_service="${1}"
_status=$( systemctl --no-pager -l status "${_service}" 2>&1 )

if ! grep "Active: active (running) " <<< "${_status}" >/dev/null; then
    ph.setStatus critical
fi
ph.status "${_status}"

ph.exit

# ----------------------------------------------------------------------