#!/bin/sh

: << =cut

=head1 NAME

file_length_ - Plugin to monitor the length of specified files

Useful for things such as lists (white, black, user, ...).

The type of metric defaults to GAUGE, but it can be configured to, say, DERIVE,
which is useful for monitoring the rate of message in error logs.

=head1 CONFIGURATION

    [file_length_IDENTIFIER]
    env.files FILEPATHGLOB1 FILEPATHGLOB2 ...
    env.category system
    env.title OPTIONAL_TITLE
    env.logarithmic 1
    env.type GAUGE

=head1 AUTHOR

Olivier Mehani <shtrom+munin@ssji.net> (based on disk/log_sizes)

=head1 LICENSE

SPDX-License-Identifier: GPL-2.0-only

=head1 MAGIC MARKERS

  #%# family=manual

=cut

# needs shellcheck -x /usr/share/munin/plugins/plugin.sh
# shellcheck source=/usr/share/munin/plugins/plugin.sh
. "${MUNIN_LIBDIR}/plugins/plugin.sh"

NAME=$(echo "${0}" | sed 's/.*_//')
TITLE=${title:-File lengths for ${NAME}}
CATEGORY=${category:-system}

FILES=${files:-/var/log/messages}
# we want globbing to happen here
# shellcheck disable=SC2116 disable=SC2086
FILES=$(echo ${FILES})

TYPE=${type:-GAUGE}

if [ "${1}" = "config" ] ; then
	# shellcheck disable=SC2154
	if [ "${logarithmic}" = "1" ]; then
		graph_args="-o"
	else
		graph_args="-l 0"
	fi
	cat <<EOF
graph_title ${TITLE}
graph_args ${graph_args} --base 1000
graph_category ${CATEGORY}
EOF
if [ "${TYPE}" = "GAUGE" ]; then
	echo "graph_info This graph shows the length of ${FILES}"
	echo "graph_vlabel length (lines)"
else
	echo "graph_info This graph shows the addition of new lines in ${FILES}"
	# ${graph_period} is not a shell variable
	# shellcheck disable=SC2016
	echo 'graph_vlabel new lines per ${graph_period}'
fi

	for F in ${FILES}; do
		MF=$(clean_fieldname "${F}")
		BF=$(basename "${F}")
		echo "${MF}.label ${BF}"
		echo "${MF}.type ${TYPE}"
		echo "${MF}.info ${F}"
		echo "${MF}.min 0"
	done

else
	HAS_GNU_STAT=$(stat --help 2>&1| grep GNU)
	for F in ${FILES}; do
		MF=$(echo "${F}" | sed 's/[-\/\.]/_/g')
		echo "${MF}.value $(wc -l < "${F}")"
		if [ -n "${HAS_GNU_STAT}" ]; then
			echo "${MF}.extinfo $(stat --printf="%sB\n" "${F}")"
		fi
	done
fi
