#!/bin/sh

. /lib/qos/qos.sh
. /usr/share/libubox/jshn.sh


queue_num=8

populate_no_of_queue(){
	# writing no. of queue per port into file and read on classify generate
	if [ ! -d "/tmp/qos" ]; then
		mkdir -p "/tmp/qos"
	fi
	no_queue_file="/tmp/qos/no_queue_per_port"
	touch "$no_queue_file"
	echo $1 >"$no_queue_file"
}

generate_queue(){
	local ifname="$1"
	local no_of_q="$2"

	local i=0
	local total_q=$((${no_of_q##* } + 1))
        for i in $no_of_q; do
		local order=$((total_q - i))
		uci add qos queue
		sec_name="q_${i}_${ifname}"
		sec_name="$(echo $sec_name | sed -r 's/[.]+/_/g')"
		uci rename qos.@queue[-1]="$sec_name"
		uci set qos.@queue[-1].enable="1"
		uci set qos.@queue[-1].ifname="$ifname"
		uci set qos.@queue[-1].precedence="$order"
		uci set qos.@queue[-1].scheduling="SP"
		uci set qos.@queue[-1].rate="0"
		uci set qos.@queue[-1].burst_size="0"
		uci set qos.@queue[-1].weight="1"
	done
}

generate_wan_queues() {
	local ifname="$1"
	local no_of_q="0 1 2 3 4 5 6 7"

	generate_queue "$ifname" "$no_of_q"
}

generate_lan_queues() {
	local ifname="$1"
	local no_of_q="0 1 2 3 4 5 6 7"

	queue_num=$(qosmngr -q $ifname)

	populate_no_of_queue $queue_num

	if [ $queue_num -eq 4 ]; then
		no_of_q="0 1 2 3"
	fi

	generate_queue "$ifname" "$no_of_q"
}

if uci -q get qos.@queue[0] >/dev/null; then
	# return if there is any valid content
	exit
else
	rm -f /etc/config/qos
fi
touch /etc/config/qos

lan_ports=""
wan_port=""

json_init
json_load_file /etc/board.json
json_select network
json_select lan
if json_is_a ports array; then
	json_for_each_item "generate_lan_queues" "ports"
else
	json_get_var lan_device device
	[ -n "$lan_device" ] && generate_lan_queues "$lan_device"
fi

json_select ..
json_select wan 2>/dev/null
json_get_var wan_port device
[ -n "$wan_port" ] && generate_wan_queues "$wan_port"
json_cleanup
