#!/bin/sh
# -*- sh -*-

# Copyright (C) 2015 Pirx Developers - https://pirx.dev/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

: << =cut

=head1 NAME

hq_ps_ - Munin wildcard plugin to monitor processes.

=head1 APPLICABLE SYSTEMS

Linux systems with ps command available.

=head1 CONFIGURATION

This is a wildcard plugin. To monitor process link this file to
hq_ps_<process name>. For example to monitor http process run:

  ln -s /usr/share/munin/plugins/hq_ps_ \
      /etc/munin/plugins/hq_df_httpd

To be able to see all processes it may be required to run this
plugin as root or as special group (note: group name may vary
depending on your system configuration). Add following to your
munin node configuration if values on your graphs are zero:

[hq_ps_*]
  user root

or:

[hq_ps_*]
  group proc
      
=head1 VERSION

  20151017

=head1 MAGIC MARKERS

  #%# family=manual
  #%# capabilities=autoconf

=head1 BUGS

  None.

=head1 AUTHOR

  Pirx Developers - https://pirx.dev/

=head1 LICENSE

GPLv3

=cut

procname=`basename ${0} | sed 's/^hq_ps_//g' 2>/dev/null`

if [ "x${1}" = "xautoconf" ]; then
  echo "yes"
  exit 0
fi

if [ "x${1}" = "xconfig" ]; then
  cat <<EOF;
graph_title ${procname} processes
graph_args --base 1000 --lower-limit 0
graph_scale no
graph_vlabel processes
graph_category processes

procs.label ${procname} processes
procs.type GAUGE
procs.min 0
procs.draw AREA
procs.colour 0000ff
EOF
  exit 0
fi

procnum=$(ps axc 2>/dev/null | grep " "${procname}"$" 2>/dev/null | wc -l 2>/dev/null)
if [ $? -ne 0 ]; then
  echo "Error running ps command. Exiting."
  exit 1
fi
echo "procs.value ${procnum}"
exit 0
