#!/bin/sh

exec 2>/dev/console

. /etc/init.d/functions.sh
. /etc/conf.d/bandwidth


local IFACES=

IFACES=eth0

tc_add_cmd() {
	[ $# -gt 0 ] || error "tc_add_cmd: missing iface name argument"

	tc qdisc add dev $1 root tbf \
		rate $TC_RATE latency 1 mpu 1000 burst $TC_BURST
}

bandwidth_start() {
	local rate rate_unit iface

	rate=$(echo $TC_RATE | sed -re 's/([0-9]+).*/\1/')
	rate_unit=$(echo $TC_RATE | sed -re 's/[0-9\.]+([KkMm][Bb]it).*/\1/')

	case "$rate_unit" in
		Kbit|kBit|KBit|kbit)
			if [ $rate -ge $LOWER_LIMIT_KBIT ] &&
			   [ $rate -le $UPPER_LIMIT_KBIT ]; then
				for iface in $IFACES; do
					tc_add_cmd $iface
				done
			fi
			;;
		Mbit|mBit|MBit|mbit)
			if [ $rate -ge $LOWER_LIMIT_MBIT ] &&
			   [ $rate -le $UPPER_LIMIT_MBIT ]; then
				for iface in $IFACES; do
					tc_add_cmd $iface
				done
			fi
			;;
		*)
			# No bandwidth limitation.
			;;
	esac
}

bandwidth_stop() {
	local iface

	for iface in $IFACES; do
		tc qdisc del dev $iface root 2>/dev/null || :
	done
}

case "$1" in
	start)
		begin "Starting traffic control"
		bandwidth_start
		end $?
		;;
	stop)
		begin "Stopping traffic control"
		bandwidth_stop
		end $?
		;;
	restart)
		begin "Restarting traffic control"
		bandwidth_stop && bandwidth_start
		end $?
		;;
	*)
		error "Usage: $0 start|stop|restart"
		;;
esac

exit 0
