#!/bin/sh /etc/rc.common
# Copyright (C) 2008 OpenWrt.org
START=99

config_cb() {
	local cfg_type="$1"
	local cfg_name="$2"

	case "$cfg_type" in
	        bandwidthd)
	                append cfgs "$cfg_name"
	        ;;
	esac
}

export_bool() {
	local option="$1"
	local section="$2"
	local _loctmp
	config_get_bool _loctmp "$section" "$option"
	if [ -n "$_loctmp" ]; then
		conffile="${conffile}$option "
		if [ 1 -eq "$_loctmp" ]; then
			conffile="${conffile}true"
		else
			conffile="${conffile}false"
		fi
		conffile="${conffile}\n"
	fi
}

export_number() {
	local option="$1"
	local section="$2"
	local _loctmp
	config_get _loctmp "$section" "$option"
	if [ -n "$_loctmp" ]; then
		conffile="${conffile}$option ${_loctmp}\n"
	fi
}

export_string() {
	local option="$1"
	local section="$2"
	local _loctmp
	config_get _loctmp "$section" "$option"
	if [ -n "$_loctmp" ]; then
		conffile="${conffile}$option \"${_loctmp}\"\n"
	fi
}

start() {
	local subnet conffile

	[ -d /tmp/bandwidthd ] || mkdir -p /tmp/bandwidthd && cp /www/legend.gif /tmp/bandwidthd/
	[ -e /htdocs ] || ln -s /tmp/bandwidthd /htdocs
	[ -e /www/bandwidthd ] || ln -s /tmp/bandwidthd /www/bandwidthd
	rm -f /tmp/bandwidthd.conf
	touch /tmp/bandwidthd.conf
	[ -e /etc/bandwidthd.conf ] || ln -s /tmp/bandwidthd.conf /etc/bandwidthd.conf
	
	
	config_load bandwidthd
	for cfg in $cfgs; do
		config_get subnets $cfg subnets
			for subnet in $subnets; do
				conffile="${conffile}subnet ${subnet}\n"
			done
		export_string dev $cfg
		export_number skip_intervals $cfg
		export_number graph_cutoff $cfg
		export_bool promiscuous $cfg
		export_bool output_cdf $cfg
		export_bool recover_cdf $cfg
		export_string filter $cfg
		export_bool graph $cfg
		export_number meta_refresh $cfg
		[ -n "$conffile" ] && echo -e "$conffile" >>/tmp/bandwidthd.conf
		unset conffile
	done
	cd /
	bandwidthd
}

stop() {
	killall bandwidthd
}
