#!/bin/bash
#
# htb_util init script, v0.0.4
#    Copyright (C) 2002  Tarhon-Onu Victor <mituc@ac.tuiasi.ro>
#
# chkconfig: - 99 01
# description: CBQ start script using HTB packet scheduler
#
# README
#
# The configuration files should be placed in /etc/sysconfig/htb and named 
# as it follows:
# name-rootrate-rootlimit-interface.htb
# The following names are valid filenames from a configuration file:
# 	noc-8192-10240-eth0.htb, LeasedAsyncClient-48-64-ppp15.htb,
# 	TunneledClient-128-256-gretuniface.htb


if [ ! -x /sbin/tc ]; then
	echo "Fatal error: /sbin/tc missing. Please verify if you have iproute installed on your system."
	exit 0;
fi;

if [ ! -x /sbin/q_parser ]; then
	echo "htb-util package not installed."
	exit 0;
fi;

. /etc/rc.d/init.d/functions

start() {
	export htstatus=1;
	echo -n "Starting HTB... ";
	for conf in /etc/sysconfig/htb/*.htb; do
		[ -f "$conf" ] &&
		$(echo $conf | 
			perl -e '	my $cfg=<>;
					$cfg=~/^.*?\-(\d+)\-(\d+)\-(.*?)\..*/;
					my ($rrate, $rlimit, $htdev)=($1,$2,$3);
					print "export rrate=$rrate\nexport rlimit=$rlimit\nexport htdev=$htdev\n";
				') || break
		echo -n "$htdev...";
		htb_exec_file=$(mktemp -q /tmp/htdev-XXXXXX)
		/sbin/q_parser "$htdev" "$rrate" "$rlimit" "$conf" > "$htb_exec_file" && chmod 755 "$htb_exec_file";
		if [ "$(head -n1 $htb_exec_file | grep ^#)" = "" ]; then
			htstatus=0;
			echo -ne "failed\t";
			continue;
		fi;
		. $htb_exec_file &>/dev/null && { 
									echo -n "ok   ";
									# rm -f $htb_exec_file; 
								} || { 
									echo -n "failed.   ";
									htstatus=0;
								};
		rm -f $htb_exec_file &>/dev/null;
	done 
	[ "$htstatus" = "1" ] && echo_success || echo_failure;
	echo;
}

stop() {
	echo -n "Stopping HTB... ";
	for conf in /etc/sysconfig/htb/*.htb; do
		interface=$(echo $conf | sed 's/.*\-//g; s/\..*$//g');
		echo -n "$interface ";
		/sbin/tc qdi del root dev $interface 2>/dev/null;
	done;
	echo_success;
	echo;
}

case "$1" in
	start)
		start;
	;;
	stop)
		stop;
	;;
	restart)
		$0 stop;
		$0 start;
	;;
	status)
		interface=$2;
		confs="$(/bin/ls /etc/sysconfig/htb/*$interface.htb 2>/dev/null)";
		for conf in $confs; do
			clear;
			interface=$(echo $conf | sed 's/.*\-//g; s/\..*$//g');
			/sbin/q_show --interface "$interface" --file "$conf" --one;
			echo -e "\v\t\t\tStatus for interface $interface. Press <enter>.";
			read;
		done;
	;;
	*)
	echo "Usage: $0 (start|stop|status [interface]|restart)";
	exit 2
esac
