#!/bin/bash

IFB_IFACE="ifblo"
IFACE="lo"

qos_on() {
	modprobe act_mirred

	# add ifb device
	ip link add name $IFB_IFACE type ifb
	tc qdisc add dev $IFACE handle ffff: ingress
	ifconfig $IFB_IFACE up
	
	# redirect ingress to ifb
	tc filter add dev $IFACE parent ffff: protocol all prio 10 u32 match u32 0 0 flowid 1:1 action mirred egress redirect dev ${IFB_IFACE}
	
	# redirect egress to ifb
	tc qdisc add dev $IFACE root handle 1: prio bands 2 priomap 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
	tc filter add dev $IFACE parent 1: protocol all prio 10 u32 match u32 0 0 flowid 1:1 action mirred egress redirect dev ${IFB_IFACE}

	# add cake to ifb
	tc qdisc add dev ${IFB_IFACE} root cake datacentre nonat unlimited
}

qos_off() {
	tc qdisc del dev ${IFB_IFACE} root > /dev/null 2>&1
	ifconfig ${IFB_IFACE} down > /dev/null 2>&1
	tc qdisc del dev ${IFACE} handle ffff: ingress > /dev/null 2>&1
	ip link delete dev ${IFB_IFACE} > /dev/null 2>&1
	tc qdisc del dev $IFACE root > /dev/null 2>&1
}

run() {
	flent rrul_be -l 60 -H localhost -p all_scaled --figure-width=10 --figure-height=7.5 -t $1 -o ${1}.png
}

if [ "$1" == "on" ]; then
	qos_on
elif [ "$1" == "off" ]; then
	qos_off
elif [ "$1" == "run" ]; then
	qos_off
	qos_on
	run "$2"
	flent -i *.gz
else
	qos_off
	run noqueue
	qos_on
	run ifb
	qos_off
	flent -i *.gz
fi
