#!/usr/bin/bash
#
##
## Copyright (c) 2018-2019 Benoit DOLEZ - License MIT
##
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell copies of the Software, and to
## permit persons to whom the Software is furnished to do so, subject to
## the following conditions:
##
## The above copyright notice and this permission notice shall be
## included in all copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
## NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
## LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
## OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
## WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
##
## Author: Benoit DOLEZ <bdolez@ant-computing.com>
## Author: Benoit DOLEZ <bdolez@zenetys.com>
## Version: 1.0
## Description: generic clear-cache wrapper for nagios-cc
##
#

function fatal() {
  echo "RRD-PERFS UNKOWN: $*"
  exit 3
}

function usage() {
  echo "Usage: ${0##*/} -H HOST [-S SERVICE] ..."
  echo "  -h, --help: this help"
}

function onError() {
  echo "${BASH_SOURCE[1]}:${BASH_LINENO[0]} in ${FUNCNAME[1]}: ERROR" >&2
}

function onExit() {
  echo "$OUTPUT"
  exit $EXITSTATUS
}


function computeRRA {
  local step=$1
  local IFS=' '

  REPLY=(
    # 1hour with step precision
    RRA:AVERAGE:0.5:1:$((1*3600/$step))
    # 25hours with 5mn precision
    RRA:{AVERAGE,MIN,MAX}:0.5:$((300/$step)):$((1*3600*25/300))
    # 32days with 15mn precision
    RRA:{AVERAGE,MIN,MAX}:0.5:$((900/$step)):$((3600*24*32/900))
    # 5year with 3h precision
    RRA:{AVERAGE,MIN,MAX}:0.5:$((3*3600/$step)):$((3600*24*367*5/(3*3600)))
  )
  return 0
}

set -e
shopt -s extglob
declare -a ARGS=( )
declare VERBOSE=0
declare HOST=""
declare SVC=""
declare STEP=300

while (( $# > 0 )); do
  case "$1" in
    ## -h, --help: this help
    -h|--help) usage >&2 && exit 0 ;;
    ## --x-debug: enable bash debug mode
    --x-debug) XDEBUG=1 ;;
    ## -v, --verbose: verbose mode
    -v|--verbose) VERBOSE=1 ;;
    ## -H, --host: define hostname
    -H|--host) HOST=$2; shift;;
    ## -S, --service: define service
    -S|--service) SVC=$2; shift;;
    ## --step: update step (default 300sec)
    --step) STEP=$2; shift;;
    ## ignore others arguments
    --) shift; break ;;
    ## store unknown args
    -*) fatal "unknown parameter '$1'" && usage >&2 && exit 1 ;;
    *)  ARGS[${#ARGS[@]}]=$1 ;;
  esac
  shift
done

ARGS+=( "$@" )

[[ $XDEBUG ]] && set -x

[[ $HOST ]] || fatal "undefined hostname (-H)"
[[ $SVC ]] || fatal "undefined service (-S)"
[[ -n $STEP && -z ${STEP//[0-9]} ]] || fatal "bad value for --step parameter : $STEP"

declare RRDBASE="${RRDBASE:-/var/lib/rrd/${0##*/}/}"
declare RRDFILE="${RRDBASE}/${HOST}/${SVC}.rrd"

trap onExit EXIT

set +e

OUTPUT=$( "${ARGS[@]}" )
EXITSTATUS=$?

set -e
trap onError ERR

IFS=' '
PERFDATA=( ${OUTPUT#*|} )
DS=( ${PERFDATA[@]%%=*} )

if [[ ! -e "$RRDFILE" ]]; then
  mkdir -p "${RRDFILE%/*}"
  echo "${DS[*]}" > ${RRDFILE%.rrd}.ds
  computeRRA $STEP
  DS=( ${DS[@]/#$'\x27'/} )  # \x27 => "'"
  DS=( ${DS[@]/%$'\x27'/} )  # \x27 => "'"
  DS=( ${DS[@]/#/DS:} )
  DS=( ${DS[@]/%/:GAUGE:$((STEP*2)):U:U} )
  rrdcreate "$RRDFILE" --step $STEP "${DS[@]}" "${REPLY[@]}"
elif [[ "${DS[*]}" != "$(<${RRDFILE%.rrd}.ds)" ]]; then
  echo "ignore update with invalid DS" >&2
  exit 3
fi

VALUES=( ${PERFDATA[@]#*=} )
VALUES=( ${VALUES[@]%%$'\x3b'*} ) # \x3b => ";"

IFS=':'
rrdupdate "$RRDFILE" "N:${VALUES[*]}"

echo "$(date +%s):${PERFDATA[*]}" >> "${RRDFILE%.rrd}.txt"

