#!/bin/bash

# jwbensley@gmail.com
# Calculate a 95th percentile value for an RRD graph, sorting the values with an external
# Perl script. Assume the data streams are "traffic_in" and "traffic_out", which is typicall
# of Cacti. For Ovservium this would be "INOCTECTS" and "OUTOCTECTS".

# args;
# 1 = start datetime (epoch time)
# 2 = end date/time (epoch time)
# 3 = rrdfile

datestart=$1
dateend=$2

  # Blank out a file and dump a given time range of values from rrd file
  echo "" > rrd_values
  rrdtool fetch -s $datestart -e $dateend $3 MAX > rrd_values
  # Remove the titles
  sed -i 1,+1d rrd_values
  # Blank out a new file
  echo "" > rrd_values_max
  # Parse out the sorting of to a perl script
  ./rrd_organise.pl

  # Now we have filled ./rrd_values_max with the MAX value from each
  # time period, sorted then in desending order
  sort -g -r rrd_values_max > rrd_values_max_sorted
  # Remove any blank lines (typically one on the end)
  sed '/^$/d' rrd_values_max_sorted > rrd_values_max_sorted_trim
  # Count the number of lines of rrd values
  count=`grep -c ^ rrd_values_max_sorted_trim`
  # Get 5 percent of the line count value
  NUM=$(echo "scale=4; ($count/100)*5" | bc)
  # Round it off
  NUM=$(awk -v n1=$NUM 'BEGIN {print int(n1)}')
  # Now read the value from the line, 5% down from the top
  # of the line count of the file
  NUM=`awk -v n1=$NUM 'NR==n1' rrd_values_max_sorted_trim`
  # Again, round that off
  NUM=$(awk -v n1=$NUM 'BEGIN {print int(n1)}')
  # Converts to Kbps
  traffic=$(echo "($NUM*8)/1000" | bc)

  echo -e "$traffic"

  # Clean up
  rm rrd_values
  rm rrd_values_max
  rm rrd_values_max_sorted
  rm rrd_values_max_sorted_trim
