#!/bin/sh
#
# Plots one or two field(s) out of a rrd database.
# Use with -h to list the available fields.

if hash feh 2> /dev/null; then
    IMAGE_VIEWER="$(which feh) -R 1 --auto-zoom"
else
    IMAGE_VIEWER="$(which eog)"
fi

if [ -z "$IMAGE_VIEWER" ]; then
    printf "Error: no valid image viewer found. Install 'feh' or 'eog'.\n"
    exit 1
fi

usage() {
    printf "Usage:\n"
    printf "\t%s [OPTION...] [FIELD1=Flws] [FIELD2]\n\n" "$(basename "$0")"
    printf "Options:\n"
    printf "\t-d name    name of the database to use [default: monitoring.rrd]\n"
    printf "\t-p name    name of the PNG to generate [default: field1[_field2].png]\n"
    printf "\t-r wxh     size of the generated PNG (width x height) [default: 640x480]\n\n"
    printf "\t-s start   start time of the plot [default: end-10m]\n"
    printf "\t-e end     end time of the plot [default: last_update]\n"
    printf "\t-i int     interval to plot [default: 10m (last 10min)]\n\n"
    printf "\t-f         display Holt-Winters confidence bands\n"
    printf "\t-t win     display the 'win' hour trend\n\n"
    printf "\t-x         use logarithmic axis\n"
    printf "\t-u max     crop values to 'max'\n"
    printf "\t-l min     crop values to 'min'\n\n"
    printf "\t-b         do not display the anteater banner\n\n"
    printf "\t-h         display this help and exit\n"
    if [ ! -z "$FIELDS" ]; then
        printf "\n\tFIELD1 and FIELD2 can be one of the following:\n"
        CNT=0
        for i in $FIELDS; do
            printf "\t\t%-10s" $i;
            if [ $CNT -eq 2 ]; then
                CNT=0
                echo
            else
                CNT=$((CNT+1))
            fi
        done
        echo
    fi
}

while getopts ":hd:p:r:e:s:i:ft:xu:l:b" OPT; do
    case $OPT in
        d) DB="$OPTARG";;
        p) PNG="$OPTARG";;
        r)
           WIDTH="$(echo $OPTARG | cut -dx -f1)"
           HEIGHT="$(echo $OPTARG | cut -dx -f2)"
           ;;
        s) START="$OPTARG";;
        e) END="$OPTARG";;
        i) INTERVAL="$OPTARG";;
        f) HW=1;;
        t) WIN=$(($OPTARG*60*60));;
        x) LOG="--logarithmic";;
        u) LIMITS="$LIMITS -u $OPTARG";;
        l) LIMITS="$LIMITS -l $OPTARG";;
        b) NOBANNER=1;;
        h) HELP=1;;
        :) printf "Option '-%s' requires an argument\n\n" "$OPTARG"; usage; exit 1;;
    esac
done
shift $((OPTIND-1))

if [ -z "$DB" ]; then
    DB="monitoring.rrd" # name of the rrd database to use
fi

if [ -f "$DB" ]; then
    FIELDS=$(rrdtool info "$DB" | grep "ds\[" | cut -d[ -f2 | cut -d] -f1 | uniq)
fi

if [ $HELP ]; then
    usage
    exit 0
fi

if [ -z "$FIELDS" ]; then
    printf "%s is not a valid RRD file\n\n" "$DB"
    usage
    exit 1
fi

if [ "$LIMITS" ]; then
    LIMITS="$LIMITS --rigid"
fi

# which field to plot
if [ "$1" ]; then
    FIELD1="$1"
else
    FIELD1="Flws"
fi
FIELD2="$2"

# make sure the field(s) exists
if [ -z "$(echo "$FIELDS" | awk "/\<$FIELD1\>/")" ]; then
    printf "Error: field '%s' does not exist\n\n" "$FIELD1"
    usage
    exit 1
fi
if [ "$FIELD2" ] && [ -z "$(echo "$FIELDS" | awk "/\<$FIELD2\>/")" ]; then
    printf "Error: field '%s' does not exist\n\n" "$FIELD2"
    usage
    exit 1
fi

# name of the output
if [ -z "$PNG" ]; then
    if [ -z "$FIELD2" ]; then
        PNG="${FIELD1}.png"
    else
        PNG="${FIELD1}_${FIELD2}.png"
    fi
fi

# resolution of the png
if [ -z "$WIDTH" ] || [ -z "$HEIGHT" ]; then
    WIDTH=640
    HEIGHT=480
fi

UPDATE_FREQ=1 # update the graph every second

# Time interval to plot
if [ -z "$END" ]; then
    END=$(rrdtool info "$DB" | grep "^last_update = " | cut -d= -f2 | tr -d [[:space:]])
fi
if [ -z "$INTERVAL" ]; then
    INTERVAL="10m"
fi
if [ -z "$START" ]; then
    START="$END-$INTERVAL"
fi

# Standard colors (0: light, 1: dark)
RED0="#EA644A"
RED1="#CC3118"
ORANGE0="#EC9D48"
ORANGE1="#CC7016"
YELLOW0="#ECD748"
YELLOW1="#C9B215"
GREEN0="#54EC48"
GREEN1="#24BC14"
BLUE0="#48C4EC"
BLUE1="#1598C3"
PINK0="#DE48EC"
PINK1="#B415C7"
PURPLE0="#7648EC"
PURPLE1="#4D18E4"
BLACK="#000000"

CMD="rrdtool graph "$PNG" \
    --start "$START" \
    --end "$END" \
    --font DEFAULT:9: \
    --font TITLE:14: \
    --title "$FIELD1" \
    --vertical-label \"# $FIELD1\" \
    -D -w $WIDTH -h $HEIGHT -a PNG \
    $LIMITS $LOG \
    DEF:obs=$DB:$FIELD1:AVERAGE \
    AREA:obs$BLUE0:\"$FIELD1\" \
    GPRINT:obs:LAST:\"Last\:%6.0lf%s\" \
    GPRINT:obs:AVERAGE:\"Avg\:%6.2lf%s\" \
    GPRINT:obs:MIN:\"Min\:%6.0lf%s\" \
    GPRINT:obs:MAX:\"Max\:%6.0lf%s\l\""

if [ "$FIELD2" ]; then
    CMD="$CMD \
        --title "$FIELD1/$FIELD2" \
        --vertical-label \"# $FIELD2/$FIELD1\" \
        DEF:obs2=$DB:$FIELD2:AVERAGE \
        CDEF:nobs2=obs2,-1,* \
        AREA:nobs2$RED0:\"$FIELD2\" \
        GPRINT:obs2:LAST:\"Last\:%6.0lf%s\" \
        GPRINT:obs2:AVERAGE:\"Avg\:%6.2lf%s\" \
        GPRINT:obs2:MIN:\"Min\:%6.0lf%s\" \
        GPRINT:obs2:MAX:\"Max\:%6.0lf%s\l\""
fi

# Holt-Winters
if [ $HW ]; then
    CMD="$CMD \
        DEF:pred=$DB:$FIELD1:HWPREDICT \
        DEF:dev=$DB:$FIELD1:DEVPREDICT \
        DEF:fail=$DB:$FIELD1:FAILURES \
        TICK:fail$YELLOW0:1.0 \
        AREA:obs$BLUE0 \
        CDEF:upper=pred,dev,2,*,+ \
        LINE1:upper$BLACK:\"Holt-Winters Upper Bound\l\""

        if [ ! -z "$FIELD2" ]; then
            CMD="$CMD \
                DEF:pred2=$DB:$FIELD2:HWPREDICT \
                DEF:dev2=$DB:$FIELD2:DEVPREDICT \
                DEF:fail2=$DB:$FIELD2:FAILURES \
                CDEF:nfail2=fail2,-1,* \
                TICK:nfail2$YELLOW0:1.0 \
                AREA:nobs2$RED0 \
                CDEF:upper2=pred2,dev2,2,*,+ \
                CDEF:nupper2=upper2,-1,* \
                LINE1:nupper2$BLACK"
        fi
fi

# Trend
if [ "$WIN" ]; then
    CMD="$CMD \
        CDEF:trend=obs,$WIN,TREND \
        LINE2:trend$RED1:\"Trend\""

    if [ "$FIELD2" ]; then
        CMD="$CMD \
            CDEF:trend2=nobs2,$WIN,TREND \
            LINE2:trend2$RED1:\"Trend\""
    fi
fi

if [ "$FIELD2" ]; then
    CMD="$CMD COMMENT:\"\\u\""
fi
if [ $HW ]; then
    CMD="$CMD COMMENT:\"\\u\""
fi
if [ "$WIN" ]; then
    CMD="$CMD COMMENT:\"\\u\""
fi
CMD="$CMD COMMENT:\"\r\""
if [ -z "$NOBANNER" ]; then
    CMD="$CMD \
        COMMENT:\"         @      @         \r\" \
        COMMENT:\"          |    |          \r\" \
        COMMENT:\"====vVv==(a    a)==vVv====\r\" \
        COMMENT:\"==========\    /==========\r\" \
        COMMENT:\"===========\  /===========\r\" \
        COMMENT:\"            oo            \r\" \
        COMMENT:\"\r\" \
        COMMENT:\"No ants were (h)armed in the making of this chart\r\""
else
    CMD="$CMD COMMENT:\"\r\""
fi

sleep 1 && $IMAGE_VIEWER "$PNG" 2> /dev/null &
watch -n "$UPDATE_FREQ" "$CMD"
