#!/bin/bash

# Copyright 2008 Anibal Monsalve Salazar <anibal@debian.org>
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#set -x
set -e

dm_history=$( grep "^[^ ]" dm-history | sed "s/ /:/g" )

dm=0
maxdm=0
for dm_entry in $dm_history
do
    dm_number=${dm_entry##*:}
    dm=$(( dm + dm_number ))
    if [ $dm -gt $maxdm ]
    then
        maxdm=$dm
    fi
done

echo $dm

step=43200
start=1186236000
end=$( date +%s )
end=$(( end + 4 * step ))

rm -f dm.rrd
rrdtool create dm.rrd \
    --step $step \
    --start $start \
    DS:dm:GAUGE:$step:0:$maxdm \
    RRA:LAST:0.5:1:1600

count_prev=0
timestamp_prev=$start
for dm_entry in $dm_history
do
    timestamp=${dm_entry%%:*}
    dm_number=${dm_entry##*:}
    timestamp=$( sed "s/^\(....\)\(..\)\(..\)T\(..\)\(..\)\(..\)Z$/\1\/\2\/\3/" <<< $timestamp )
    timestamp=$( date +%s -d "$timestamp" )
    timestamp_filler=$(( timestamp_prev + step ))
    while [ $timestamp_filler -lt $timestamp ]; do
        rrdtool update dm.rrd $timestamp_filler:$count_prev
        timestamp_filler=$(( timestamp_filler + step ))
    done
    count=$(( count + dm_number ))
    rrdtool update dm.rrd $timestamp:$count
    count_prev=$count
    timestamp_prev=$timestamp
done

timestamp_filler=$(( timestamp_prev + step ))
while [ $timestamp_filler -lt $end ]; do
    rrdtool update dm.rrd $timestamp_filler:$count_prev
    timestamp_filler=$(( timestamp_filler + step ))
done

#rrdtool fetch dm.rrd LAST --start $start --end $end

rrdtool graph dm.png \
    --slope-mode \
    --start $start \
    --end $end \
    --title "Debian Maintainers" \
    --imgformat PNG \
    --width 600 --height 300 \
    --color CANVAS#000000 \
    --color BACK#101010 \
    --color FONT#C0C0C0 \
    --color MGRID#80C080 \
    --color GRID#808020 \
    --color FRAME#808080 \
    --color ARROW#FFFFFF \
    --color SHADEA#404040 \
    --color SHADEB#404040 \
    DEF:dm=dm.rrd:dm:LAST \
    LINE2:dm#FF0000

exit $?
