#!/bin/bash

# script to do traffic shaping on thinc. It receives the bw you want to
# give it. must run as root. 
# BW is expressed like:
# 200kbit
# 100mbit
#
# options:
# -p: port to use, default 20000
# -d: device, default eth0
# bandwidth

DEFPORT=20000
DEFDEV=eth0

TEMP=`getopt -o p:d: -n '$0' -- "$@"`
if [ $? -ne 0 ]; then
	echo "Usage: $0 [-p port] [-d device] bw"
	exit 1
fi


eval set -- "$TEMP"

PORT=""
DEV=""

while true; do
	case "$1" in
		-p) PORT=$2; echo "using port $PORT"; shift 2;;
		-d) DEV=$2; echo "using device $DEV"; shift 2;;
		--) shift; break;;
		*) echo "Internal error. Help, i don't know what to do!!!"; 
		   exit 1;;
	esac
done

#for arg do echo 'unknown option '"\`$arg'"; done
if [ $# -ne 1 ]; then
	echo "You did not specify the bandwidth!!"
	echo "Usage: $0 [-p port] [-d device] bw"
	exit 1
fi

BW=$1

if [ "$PORT" == "" ]; then
	PORT=$DEFPORT
	echo "using default port $PORT"
fi

if [ "$DEV" == "" ]; then
	DEV=$DEFDEV
	echo "using default device $DEV"
fi

echo "limiting bandwidth on interface $DEV and port $PORT to $BW"

# create qdisc
# TODO: Check if a qdisc exists and reuse it
echo -n -e "creating qdisc..."
tc qdisc add dev $DEV root handle 1: htb
if [ $? -ne 0 ]; then
	echo "Error: I apologize. I could not create the queueing discipline :("
	exit 1
else
	echo "done."
fi

# create class for thinc's traffic
# TODO: What if classid is already taken?
echo -n -e "creating traffic class..."
tc class add dev $DEV parent 1: classid 1:1 htb rate $BW
if [ $? -ne 0 ]; then
	echo "Error: I apologize. I could not create the traffic class :("
	exit 1
else
	echo "done."
fi

# create a filter for thinc's traffic
FILTER="tc filter add dev $DEV protocol ip parent 1:0 prio 1 u32"

echo -n -e "creating traffic filter..."
$FILTER match ip sport $PORT 0xffff flowid 1:1
if [ $? -ne 0 ]; then
	echo "Error: I apologize. I could not create the traffic filter :("
	exit 1
else
	echo "done."
fi

# the end
echo ""
echo "Finished. Bandwidth on port $PORT and device $DEV is now limited to $BW"
echo "c-ya!"
