#!/bin/bash

RRDTOOLDB="/data/rrdtool_db"
HISTORY="daily" # daily, weekly, yearly
WIDTH="750"
HEIGHT="360"

PUPLIC="/data/public_html"

VARS=(\
	'zustand:1:0' \
	'kesseltemp:2:C°:#00FF99' \
	'abgastemp:3:C°:#00D600' \
	'kesselstrg:4:%:#0000FF' \
	'saugzug:10:U/min'
	'pufferoben:20:C°:#990099'
	'pufferunten:21:C°:#99004D' \
	'pufferpumpe:22:%:#4169E1' \
	'boiler:23:C°:#D600D6' \
	'vorlauf:24:C°:#FF1A00' \
	'hkpumpe:26:1' \
	'aussentemp:28:C°:#CCFF00'\
	'betriebsstunden:30:h' \
	'fehler:99:1' \
     )

case $HISTORY in
   d*) hist="-24h"; trend="32200"; trendstart="-2 days" ;;
   w*) hist="-144h"; trend="86400"; trendstart="-8 days" ;;
   y*) hist="-8760h"; trend="1724000"; trendstart="-365 days" ;;
    *) hist="-24h"; trend="12h"; trendstart="-2 days" ;;
esac

for x in "${VARS[@]}" ; do
    IFS=":" y=( $x )
    IFS=";" z=( $(grep -m1 -ai ";${y[1]};[0-9]" /tmp/logfile) )
    if [ -z "${y[2]/[0-9]/}" ] ; then
	value="${z[${y[2]}]/000}"
    else
	value=$(echo ${z[1]} ${z[3]} | awk '{ print $1 / $2 }')
    fi
    export ${y[0]}="$value"
    unset IFS
    if [ "${y[3]}" ] ; then
	m=${y[2]/\%/%%}
	s=$s" DEF:$y=$RRDTOOLDB/$y.rrd:$y:MAX "
	s=$s" LINE1.5:${y}${y[3]}:\"$y	\" "
	s=$s" GPRINT:$y:LAST:\"cur\: %2.1lf $m	\" "
	s=$s" GPRINT:$y:MIN:\"min\: %2.1lf $m	\" "
	s=$s" GPRINT:$y:MAX:\"max\: %2.1lf $m	\n\" "
    fi
done

cat <<EOF >/tmp/dmp
rrdtool graph "$PUPLIC/total.png" \
--start $hist --end now \
--title="Fröling Charts ($hist)" \
--font 'TITLE:13:DejaVuSans Bold' \
--width $WIDTH \
--alt-y-grid \
--rigid \
--height $HEIGHT \
--grid-dash 1:0 \
--slope-mod \
--watermark "$(date)" \
--disable-rrdtool-tag \
-c "BACK#000000" -c "SHADEA#000000" -c "SHADEB#000000" \
-c "FONT#DDDDDD" -c "CANVAS#202020" -c "GRID#666666" \
-c "MGRID#AAAAAA" -c "FRAME#202020" -c "ARROW#FFFFFF" $s
rm /tmp/dmp
EOF

sh /tmp/dmp
