#!/bin/sh
#
# $Id: munin-plugin,v 1.6 2008-02-25 11:10:00 finnarne-guest Exp $
#
# Author: Finn-Arne Johansen 
# Date:   2008-02-25

LOGNAME=/var/log/slbackup/slbackup.log

CLIENTS="$(perl -e 'use SLBackup  ; 
           $config=slbackup_readconfig () ; 
           for $key (keys %{$config->{client}}) { 
               printf ("%s\n", $key) ; 
           } ')"

if [ "$1" = "config" ] ; then 
  echo "graph_title slbackup status"
  echo "graph_args --base 1000 -l 0"
  echo "graph_vlabel count"
  echo "graph_scale no"
  echo "graph_category disk"
  echo "lastrun.label last run"
  echo "lastrun.warning 1.1"
  echo "lastrun.critical 1.25"
  for CLIENT in $CLIENTS ; do 
      echo "client_$CLIENT.label $CLIENT"
      echo "client_$CLIENT.critical 1:"
  done
  echo "graph_info Show the status of failed and successfull backup set from the last run"
  exit 0
fi

# Fetch log that is not empty (prevent broken plugin when logfile
# is rotated)
if [ -s $LOGNAME ] ; then 
  CAT=cat
elif [ -r $LOGNAME.1.gz ] ; then 
  CAT=zcat
  LOGNAME=$LOGNAME.1.gz
fi

# Fetch were last backup was started
LAST=$($CAT $LOGNAME | grep -n "Starting slbackup:" | tail -1 | cut -f1 -d:)

for CLIENT in $CLIENTS ; do 
  # count failed and successfull backups during last backup
  if [ "$LAST" ] ; then 
    if $CAT $LOGNAME | tail -n +$LAST | \
      grep -q "Successfully finished backing up client ${CLIENT}$" ; then 
        echo "client_$CLIENT.value 1"
    else
        echo "client_$CLIENT.value 0"
    fi
  else
    # or trigger an error if last backup is not found
    echo "client_$CLIENT.value 0"
  fi
done


# Find when last backup ended
LASTRUN="$($CAT $LOGNAME | sed -ne "s/- Finished slbackup.//p" | tail -1 )" 

if [ -z "$LASTRUN" ] ; then   
  echo lastrun.value 0
else   
  # report number of hours since last backup
  echo -n "lastrun.value ";   
  cat << EOF | bc 
scale=2
($(date +%s) - $(date -d "$LASTRUN" +%s)) / 86400
EOF
fi

