#!/bin/bash
##########################
# googlecode_
##########################
# Munin Plugin to display the number of downloads
# from a google code repository
# Copyright 2009 (C) Kaare Hartvig Jensen (hartvig.de)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of    
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Usage:
# Create symbolic link from /etc/munin/plugins/googlecode_projectname to
# /usr/share/munin/plugins/googlecode_
#
# Here, projectname is the name of the project you wish to monitor.
# googlecode_ will look at the downloads list, and list the number
# of downloads for a given file. googlecode_ assumes, that the file
# names take the form "projectname_" or "projectname-", such as
# "sinthgunt_2.0.2_all.deb" for the sinthgunt project hosted at
# www.sinthgunt.org

# Get project name
PROJECTNAME=`basename $0 | sed 's/^googlecode_//g'`

# Get list of files and the number of downloads
declare -a files
files=( $(lynx -source http://code.google.com/p/$PROJECTNAME/downloads/list | html2text -nobs -ascii -width 100 | grep $PROJECTNAME[-_] | sed 's/  */ /g' | tac | sed 's/Featured*/ /g') )
Nfiles=${#files[@]}
if [ "$1" = "autoconf" ]; then
    echo yes
    exit 0
fi

# Config. 
if [ "$1" = "config" ]; then
    echo "graph_title Number of downloads of $PROJECTNAME from Google Code "
    echo "graph_args --base 1000 --lower-limit 0"
    echo "graph_vlabel number of downloads"
    echo "graph_category other"
    echo "graph_info This graph shows the number of downloads of $PROJECTNAME from Google Code."
    j=0
    for (( i = 1 ; i < $Nfiles ; i=i+5 ))
    do
        if [ $i = 1 ]; then # first one must be area.
		    name="site_${j}"
            echo "${name}.label ${files[$i-1]}"
	        echo "${name}.draw AREA"
#        	echo "${name}.type COUNTER"
            echo "${name}.info The number of downloads of $PROJECTNAME from google code."
            j=$((j+1))
		else # the rest is stacked on top of the area.
			name="site_${j}"
            echo "${name}.label ${files[$i-1]}"
	        echo "${name}.draw STACK"
#			echo "${name}.type COUNTER"
        	echo "${name}.info The number of downloads of $PROJECTNAME from google code."
	        j=$((j+1))
		fi
        done
        exit 0
fi

# Pring number of downloads.

j=0
for (( i = 1 ; i < $Nfiles ; i=i+5 ))
do
    name="site_${j}"
    value=${files[$i+3]}
    echo "${name}.value ${value}"
    j=$((j+1))
done
