#!@@GOODSH@@
# -*- sh -*-

: << =cut

=head1 NAME

samba - Plugin to monitor number of files held open by the CIFS clients

=head1 CONFIGURATION

This plugin uses the following configuration variables:

 [samba]
  user root
  env.smbstatus /usr/bin/smbstatus
  env.ignoreipcshare 1

Usually "smbstatus" requires to be run as root (see "user root" above).

Environment variables:

 * smbstatus: path to "smbstatus" executable
   (default: search PATH and fall back to /usr/bin/smbstatus)
 * ignoreipcshare: set this variable to any non-empty value to ignore IPC$ when counting shares.

=head1 AUTHOR

Unknown author

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

 #%# family=contrib
 #%# capabilities=autoconf

=cut

SMBSTATUS=${smbstatus:-$(command -v smbstatus)}
SMBSTATUS=${SMBSTATUS:-/usr/bin/smbstatus}

if [ "$1" = "autoconf" ]; then
	if [ -x "$SMBSTATUS" ]; then
		if "$SMBSTATUS" -V >/dev/null 2>&1; then
			echo 'yes'
		else
			echo "no (failed to run $SMBSTATUS - maybe need to run as 'root'?)"
		fi
	else
		echo 'no (smbstatus not found)'
	fi
	exit 0
fi

if [ "$1" = "config" ]; then

	echo 'graph_title Samba status'
	echo 'graph_args -l 0'
	echo 'graph_vlabel number'
	echo 'graph_category samba'
	echo 'proc.label processes'
	echo 'lock.label locked files'
	echo 'share.label Open shares'
	# Bug pointed out by kozik: there is no max field.
	# echo 'max.warning 900'
	# echo 'max.critical 960'
	exit 0
fi

$SMBSTATUS -p 2>/dev/null | awk 'BEGIN {lines=0} $1 ~ /^[0-9]+/ {lines++} END {print "proc.value " lines}'
$SMBSTATUS -L 2>/dev/null | awk 'BEGIN {lines=0} $1 ~ /^[0-9]+/ {lines++} END {print "lock.value " lines}'
if [ -n "${ignoreipcshare:-}" ]; then
	# shellcheck disable=SC2016
	IGNORE='$1=="IPC$" {next}'
fi
$SMBSTATUS -S 2>/dev/null | awk '
	BEGIN {lines=0;state=0}
	$1=="Service" && state==0 {state=1; next}
	/^--*$/ && state==1 {state=2; next}
	state < 2 {next}
	/^$/ {next}
	'"$IGNORE"'
	{lines++}
	END {print "share.value " lines}'
