#!/bin/sh
# -*- sh -*-

: << =cut

=head1 NAME

jenkins_builds_results - Plugin to measure number of jenkins builds

=head1 AUTHOR

Contributed by Holger Levsen

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

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

=cut

. $MUNIN_LIBDIR/plugins/plugin.sh

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

STATEFILE=$MUNIN_PLUGSTATE/$(basename $0)

# delete statefile if it's older than ${jenkins_update_interval} set in /etc/munin/plugin-conf.d/jenkins
if test $(find $STATEFILE -mmin +${jenkins_update_interval}) ; then
	rm -f $STATEFILE
fi

if [ -f $STATEFILE ] && [ "$1" = "" ] ; then
	cat $STATEFILE
	exit 0
fi

JOB_PREFIXES=$(ls -1 /var/lib/jenkins/jobs/|cut -d "_" -f1|sort -f -u)
if [ "$1" = "config" ]; then
	echo 'graph_title Jenkins Builds results'
	echo 'graph_args --base 1000 -l 0 '
	echo 'graph_scale no'
	echo 'graph_total total'
	echo 'graph_vlabel Jenkins Builds results per category'
	echo 'graph_category jenkins'
	draw=AREA
	for PREFIX in $JOB_PREFIXES ; do
		for STATE in success unstable failure ; do
			echo "jenkins_builds_results_${PREFIX}_${STATE}.label ${PREFIX} ${STATE}"
			echo "jenkins_builds_results_${PREFIX}_${STATE}.draw $draw"
			if [ "$draw" = "AREA" ] ; then draw=STACK ; fi
		done
	done
	exit 0
fi

for PREFIX in $JOB_PREFIXES ; do
	PREFIX_RESULTS=$(for i in /var/lib/jenkins/jobs/${PREFIX}*/builds/*/log ; do tail -1 $i 2>/dev/null; echo " \n"; done )
	for STATE in success unstable failure ; do
		NR=0
		if [ "$STATE" = "failure" ] ; then
			# count aborted as failed
			NR=$(echo -e "$PREFIX_RESULTS" | egrep -i -c "($STATE|aborted)")
		else
			NR=$(echo -e "$PREFIX_RESULTS" | grep -i -c $STATE)
		fi
		echo "jenkins_builds_results_${PREFIX}_${STATE}.value $NR" | tee -a $STATEFILE
	done
done