#!/bin/sh

get_max_linkspeed() {
    local ifname="$1"
    local modes="10000 5000 2500 1000 100 10"
    local speed=""
    local phycap="$(ethtool $ifname | sed -ne '/Supported link modes:/,/:/p' | sed -e 's/.*://' -e 's/^[[:space:]]*//' -e '$d')"

    for i in $modes; do
        if echo "${phycap}" | grep -qe "$i\\D"; then
            speed=$i
            break
        fi
    done

    echo "$speed"
}

get_shaper_rate() {
	rate="$1"

	if [ -z "${rate}" ]; then
		echo "-1"
		return
	fi

	if [ "${rate}" -eq -1 ]; then
		#No shaping
		echo "-1"
		return
	fi

	# Convert the rate from bps to kbps.
	if [ "${rate}" -ge 0 -a "${rate}" -le 100 ];then
		# set as per percentage
		speed=$(get_max_linkspeed "$ifname")
		if [ -z "${speed}" ]; then
			echo "-1"
			return
		fi

		rate=$((speed * rate * 1000 / 100))
	else
		rate=$(($rate / 1000))
	fi

	echo "$rate"
}
