#!/bin/bash

: << =cut

=head1 NAME

df - Plugin to monitor disk usage (measuring byte usage in percent)

=head1 CONFIGURATION

This shows the default configuration

  [df*]
    env.df /usr/sbin/df
    env.warning 92
    env.critical 98

A device specific warning/critical level is also supported.  Append
the munin label (shown in the plugin display page) and append _warning
or _critical respectively to get the (environment variable) name.

To limit the monitored filesystems, configure the "only" environment variable.
For example, to only monitor /, one would add to plugin-conf.d:

  [df*]
    env.only /

=back

=head1 AUTHOR

Unknown author

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

 #%# family=auto
 #%# capabilities=autoconf

=cut

. "$MUNIN_LIBDIR/plugins/plugin.sh"

DF=${df:-/usr/sbin/df}
TAIL=/usr/bin/tail
warning=${warning:-92}
critical=${critical:-98}

if [ "$1" = 'autoconf' ]; then
    echo yes
    exit 0
fi

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

    echo 'graph_title Disk usage in percent'
    echo 'graph_args --upper-limit 100'
    echo 'graph_category disk'
    echo 'graph_scale no'

    # Using the mount point as name is silly as / becomes '' after
    # the needed substitutions.  So in this incarnation we use the
    # device name.  Since the plugin already changed names this
    # should be ok.

    # shellcheck disable=SC2086
    $DF -k -l ${only:-} | $TAIL +2 | while read -r dev size used avail pct mnt; do

	case $dev:$mnt in
	    /usr/lib*|ctfs:*|objfs:*|mnttab:*|sharefs:*|*:/cdrom/*|*:/media/*) continue;;
	    /devices*|/platform*|*:/var/run*|*:/etc/svc*|proc:*|fd:*) continue;;
	    swap:*) name=$(clean_fieldname "$mnt");;
	    *:*)    name=$(clean_fieldname "$dev");;
	esac
        echo "$name.label $mnt"
	print_warning "$name"
	print_critical "$name"
    done
    exit 0
fi

# shellcheck disable=SC2034,SC2086
$DF -k -l ${only:-} | $TAIL +2 | while read -r dev size used avail pct mnt; do
	case $dev:$mnt in
	    /usr/lib*|ctfs:*|objfs:*|mnttab:*|sharefs:*|*:/cdrom/*|*:/media/*) continue;;
	    /devices*|/platform*|*:/var/run*|*:/etc/svc*|proc:*|fd:*) continue;;
	    swap:*) name=$(clean_fieldname "$mnt");;
	    *:*)    name=$(clean_fieldname "$dev");;
	esac
        echo "$name.value $pct" | cut -f1 -d%
done
