#!/bin/bash
# CCacheMunin -- plugin to show CCache statistics in Munin
# (C) 2016 Stephane Charette <stephanecharette@gmail.com>
# $Id: ccache-size 1692 2016-03-14 08:59:35Z stephane $
#
# Determine the size of ccache on disk.
#
# Munin magic markers for automated installation
# - http://munin-monitoring.org/wiki/HowToWritePlugins
# - http://guide.munin-monitoring.org/en/latest/architecture/syntax.html
#%# family=auto
#%# capabilities=autoconf


if [ "$1" = "autoconf" ]; then
	# tell Munin this plugin supports automatic configuration
	echo "yes"
	exit 0
fi


# create a map of the ccache directories and the usernames to which they belong
ccache_conf_names=$(find /home -maxdepth 3 -type f -name ccache.conf | sort)
declare -A m
for ccache_conf in ${ccache_conf_names}
do
	ccache_dir=$(dirname "${ccache_conf}")
	ccache_name=$(dirname "${ccache_conf}" | cut -d'/' -f3)
	m["${ccache_name}"]="${ccache_dir}"
done


if [ "$1" = "config" ]; then
	# Munin auto-configuration (http://munin.readthedocs.org/en/latest/reference/plugin.html)
	cat <<-EOT
		graph_category ccache
		graph_args --base 1024 --lower-limit 0
		graph_scale yes
		graph_info CCache size on disk
		graph_title CCache Size On Disk
		graph_vlabel size (bytes)
		graph_printf %.1lf
		EOT

	for key in "${!m[@]}"
	do
		echo "ccache_${key}.label ${key}"
		echo "ccache_${key}.draw LINE1"
		echo "ccache_${key}.info size of ccache directory for ${key}"
		echo "ccache_${key}.type GAUGE"
	done

	exit 0
fi


# this next part is called every 5 minutes by Munin to generate the values stored in the rrd

for key in "${!m[@]}"
do
	echo "ccache_${key}.value $(du --bytes --summarize ${m[${key}]} | cut -f1)"
done

exit 0
