#!/bin/bash
# CCacheMunin -- plugin to show CCache statistics in Munin
# (C) 2016 Stephane Charette <stephanecharette@gmail.com>
# $Id: ccache-files 1703 2016-03-15 06:49:39Z stephane $
#
# Determine the number of files in ccache.
#
# 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
# for example:     m["bob"]="/home/bob/.ccache"
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_name=$(dirname "${ccache_conf}" | cut -d'/' -f3)
	ccache_dir=$(dirname "${ccache_conf}")
	m["${ccache_name}"]="${ccache_dir}"
done
ccache_tag_names=$(find /home -maxdepth 3 -type f -name CACHEDIR.TAG | sort)
for ccache_tag in ${ccache_tag_names}
do
	ccache_dir=$(dirname "${ccache_tag}")
	ccache_name=$(dirname "${ccache_tag}" | 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 1000 --lower-limit 0
		graph_scale yes
		graph_info CCache files in cache
		graph_title CCache Files In Cache
		graph_vlabel number of files
		graph_printf %.1lf
		EOT

	if [ ${#m[@]} -gt 1 ]; then
		echo "graph_total total"
	fi

	for key in "${!m[@]}"
	do
		echo "ccache_${key}.label ${key}"
		echo "ccache_${key}.draw LINE1"
		echo "ccache_${key}.info number of ccache files in ${m[${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

regex="files in cache +([0-9]+)"
for key in "${!m[@]}"
do
	export CCACHE_DIR="${m[${key}]}"
	ccache_output=$(ccache --show-stats)
	[[ ${ccache_output} =~ ${regex} ]]
	number_of_files="${BASH_REMATCH[1]:-0}"

	echo "ccache_${key}.value ${number_of_files}"
done

exit 0
