# original version: ERATHRH <thorsten.rhau@ericsson.se>,    2012-06-26  
# slightly improved version: <canton@op5.com>,              2013-03-28 
# 
# This script is to be used to remove traffic spikes from RRD files 
# 
# Please _make sure_ to only run it on .rrd files. 
# 
# important notice:
# the "BANDWIDTH" argument should contain the maximum bandwidth the RRD database should
# accept as measurement value.
#
# op5 Monitor by default measures bandwidth in percent so that "100" or "120" is a reasonable value
#
# if you have bandwidth measurement set up to report in "bps" instead, you have to supply the 
# max bandwdith parameter accordingly: in case of a 2Mbit line a max of 2.2Mbit would make sense
# and had o be entered as "2200000"

# Checking if needed tools are available on system 
hash rrdtool 2>&- || { echo >&2 "I require rrdtool but it's not installed. Aborting."; exit 1; }
hash mktemp 2>&- || { echo >&2 "I require mktemp but it's not installed. Aborting."; exit 1; }
hash chown 2>&- || { echo >&2 "I require chown but it's not installed. Aborting."; exit 1; }

if [ $# -ne 2 ]; then
  echo "usage: $0 <filename> <bandwidth_in_bps_or_percent>" 
  exit 1
fi

BWLIMIT=$2
if [ ! $BWLIMIT -gt 0  ]; then
        echo "no valid bandwidth limit entered"
        echo "usage: $0 <filename> <bandwidth_in_bps_or_percent>"
        exit 1
fi



if [ -f $1 ]; then
  # Please check the data sources in your rrd datafile 
  # You can do this with 'rrdtool info <file.rrd> | less' 
  # look for lines beginning with 'ds'. The name of the 
  # data source is within the square brackets. 
  rrdtool tune $1 -a 1:$BWLIMIT # Data source 1 
  rrdtool tune $1 -a 2:$BWLIMIT # Data source 2 
  TEMPFILE=`mktemp`
  rrdtool dump $1 > $TEMPFILE
  service rrdcached stop
  rm -f "$1"
  rrdtool restore $TEMPFILE $1 -r
  chown monitor.apache $1
  service rrdcached start
  rm -f "$TEMPFILE"
else
  echo "usage: $0 <filename>" 
  exit 1
fi
