#!/bin/sh
. /tmp/loader

# rrdtool fetch /tmp/datafile.rrd AVERAGE

setup()
{
	local file="/tmp/datafile.rrd"
	local interval=60			# [sec]
	local maxwait=$(( $interval * 2 ))	# [sec] writes 'unknown' into database after this time
	local context="traffic"
	local countertype="COUNTER"		# or ABSOLUTE (each update new values)
	local minmax="U:U"			# allow all values, do not limit min or max

	if [ -e "$file" ]; then
		rm "$file"
	else
		_log do setup daemon info "initial setup of $file"
	fi

	rrdtool create "$file" \
		DS:${context}:${countertype}:${maxwait}:${minmax} \
		--step $interval \
		RRA:AVERAGE:0.5:1:1440
#		RRA:AVERAGE:0.5:4:3600 \
#		RRA:AVERAGE:0.5:24:3600

#	iptables -I FORWARD -i $WANDEV		# upload
#	iptables -I FORWARD -o $WANDEV		# download
}

update()
{
	local funcname="rrd_update"
	local file="/tmp/datafile.rrd"
	local value

	[ -e "$file" ] || setup

#	set -- $(iptables -nxvL FORWARD 1 )
#	value="$2"
	set -- $(iptables -nxvL FORWARD 2 )
	value=$(( (${value:-0} + $2) / 1024 ))	# [kilobyte]
logger -s "value: $value"
	rrdtool update "$file" N:${value} || {
		_log do rrd_update daemon info "error $?"
	}
}

show()
{
	local duration="${1:-15min}"	# 1h, 4h, 1d
	local webfile="/www/1.png"
	local output="/tmp/graph.png"
	local file="${2:-/tmp/datafile.rrd}"
	local context="traffic"
	local legend="Traffic \$WANDEV - $( _system date humanreadable nice | sed 's/:/./')"
	local label="Kilobytes"
	local color="#ff0000"
	local varname="v1"
	local size="-w 900 -h 600"

	logger -s "duration= $duration"

	rrdtool >/dev/null graph $size \
		--start -${duration} "$output" \
		--vertical-label "${label}" \
		DEF:${varname}=${file}:${context}:AVERAGE \
		LINE1:${varname}${color}:"${legend}"

	[ -s "$webfile" ] || ln -s "$output" "$webfile"
	logger -s "wrote: $output, look at http://$LANADR/$( basename "$webfile" )"
}

ARG1="$1"
shift

$ARG1 "$@"
