#!/bin/sh
# Common shaper library

. /lib/qos/qos_functions.sh

# UCI 'shaper' section handler.
# It will verify shaper configuration sanity and then invoke
# hardware-specific functions
handle_shaper() {
    sid="$1" #queue section ID

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

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

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

    config_get bs "$sid" "burst_size"

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

    hw_shaper_set "$ifname" add "$rate" "$bs"
}

# Configure shaper based on options saved to UCI tree 'qos.shaper'
configure_shaper() {
    # initialize ratelimit params
    /userfs/bin/femgr ratelimit set rx_mode 0 2 0
    /userfs/bin/qdmamgr_lan set general_rx_init enable trtcm 8 125

    # Delete existing shaper
    for intf in $(jsonfilter -i /etc/board.json -e @.network.lan.ports[*] -e @.network.lan.device -e @.network.wan.device | xargs); do
        hw_shaper_set "$intf" del
    done

    # Load UCI file
    config_load qos
    # Processing shaper section(s)
    config_foreach handle_shaper shaper
}
