#!/bin/sh
# Handle queues and their order

. /lib/qos/qos_functions.sh

Q_COUNT=0

# Preliminary configuration of a queue
pre_configure_queue() {
    # Delete queues
    hw_queue_init_all

    for intf in $(jsonfilter -i /etc/board.json -e @.network.lan.ports[*] -e @.network.lan.device -e @.network.wan.device | xargs); do
        hw_intf_init "${intf}"
    done
}

# UCI queue section handler
handle_queue() {
    local qid="$1" #queue section ID
    local intf_name="$2"

    config_get is_enable "$qid" "enable" 1

    # no need to configure disabled queues
    if [ "${is_enable}" = "0" ]; then
        return
    fi

    config_get ifname "$qid" "ifname"
    # if ifname is empty that is good enough to break
    if [ -z "$ifname" ];then
        return
    fi

    config_get sc_alg "$qid" "scheduling"
    config_get wgt "$qid" "weight" 1
    config_get rate "$qid" "rate"
    config_get bs "$qid" "burst_size"
    config_get qsize "$qid" "queue_size" 1024
    config_get precedence "$qid" "precedence"

    rate=$(get_shaper_rate "$rate")
 
    if [ "$rate" -eq -1 ]; then
       return
    fi

    config_get bs "$qid" "burst_size"

    if [ "${bs}" -ge 1000 ] ; then
        bs=$((bs / 1000))
    else
        bs=0
    fi

    hw_queue_set "${ifname}" "${Q_COUNT}" "${precedence}" "$qsize" "$wgt" "$sc_alg" "$rate" "$bs"
    Q_COUNT=$((Q_COUNT + 1))
}

# Configure all queues specified in UCI tree 'qos.queue'
configure_queue() {
    # Load UCI file
    config_load qos
    config_foreach handle_queue queue
}
