#!/bin/bash
#
# Telemetry Data Extraction Program
#
# Usage:
#
# 1. Install this file on the web server.
# 2. Setup the parameters file.
# 3. Use the PHP example to make graphs.

# Function:  error()
# Purpose:   Report an error condition
#
# Parameter: String to report to stderr
# Returns:   Never returns
error()
{
	echo $* >&2
	exit 1
}

CONFIG=/etc/telem/config

echo "$*" >> /tmp/telemgraph.log

# Read in the configuration parameters
. "$CONFIG"

# Change to the data directory
cd "$TE_RRD_DIR"

# Setup the timezone
export TZ="$TIMEZONE"

# Default Settings
PARAM=""
TIME_START="yesterday"
TIME_END="now"
TYPE="last"

if [ ! -f "$TELEMETRY_DEFINITION_FILE" ];
then
	error "No telemetry definition file: $TELEMETRY_DEFINITION_FILE"
fi

usage()
{
	echo "TelemData"
	echo
	echo "TelemData [-param <name>] [-ts <start>] [-te <end>]"
}

# Read in the parameters
while [ "$1" != "${1##[-+]}" ]; do
case $1 in
  '')   echo "$0: Fuxor!"
	exit 1
	;;
  -ts)
	TIME_START=$2
	shift 2
	;;
  -te)
	TIME_END=$2
	shift 2
	;;
  -param)
	PARAM="$2"
	shift 2
	;;
  -type)
	TYPE="$2"
	shift 2
	;;
  *)
	usage
	echo Unknown parameter!
	exit 1
	;;
esac
done

if [ "$PARAM"X == "X" ];
then
	error "No parameter selected"
fi

ERROR_STR=""

# Check all the parameters are available.
for param_name in $PARAM;
do
	# Note the 2>&1 is because for some unknown reasons,
	# this cut sometimes produces a pipe closed error.
	cut -f 5 -d ',' "$TELEMETRY_DEFINITION_FILE" 2>&1 | grep -q \"$param_name\"
	if [ $? != "0" ];
	then
		ERROR_STR="$ERROR_STR $param_name"
	fi
done

# Yell if there were any unknown parameters found
if [ "$ERROR_STR"X != ""X ];
then
	error "Unknown parameter(s):$ERROR_STR"
fi

SEL0="LAST";
FILE="$TE_RRD_DIR/$PARAM.rrd"
if [ ! -f $FILE ];
then
    error "No RRD file $FILE($PARAM)"
fi

rrdtool info "$FILE" | grep -q "ds\[$PARAM\]"
if [ $? != 0 ];
then
    error "$PARAM(not in file $FILE)"
fi

case $TYPE in
last)
	SEL0="LAST";
	;;
max)
	SEL0="MAX";
	;;
min)
	SEL0="MIN";
	;;
esac

rrdtool fetch $FILE $SEL0 - \
    --start "$TIME_START" \
    --end   "$TIME_END"

exit $?
