#!/bin/sh

readonly WANPORT="$(jsonfilter -i /etc/board.json -e @.network.wan.device)"
readonly LINKSPEED_FILE="/tmp/qos/wan_link_speed"
readonly LINKSHAPE_FILE="/tmp/qos/wan_link_shape_rate"

[ -z "${PORT}" -o "${WANPORT}" = "${PORT}" ] || exit 0
[ -f "${LINKSHAPE_FILE}" ] && exit 0

LINKSPEED="$(devstatus "${WANPORT}" | jsonfilter -e '@["speed"]' | tr -d 'A-Z')"
PREV_LINKSPEED=$(cat ${LINKSPEED_FILE} 2>/dev/null)

[ "${WANPORT}" = "pon" -a $((LINKSPEED)) -eq 2500 ] && LINKSPEED=1250 #GPON asymmetrical uplink
[ -z "${PREV_LINKSPEED}" ] && PREV_LINKSPEED=0

if [ $((LINKSPEED)) -ne $((PREV_LINKSPEED)) -a $((LINKSPEED)) -ne 0 ]; then
	if [ $((LINKSPEED)) -ge 100 ]; then
		/userfs/bin/qosrule discpline Rate uplink-bandwidth $((LINKSPEED*1000*999/1000))
	else
		/userfs/bin/qosrule discpline Rate uplink-bandwidth $((LINKSPEED*1000*990/1000))
	fi
	mkdir -p "/tmp/qos"
	echo ${LINKSPEED} > ${LINKSPEED_FILE}

	hw_nat -! > /dev/null 2>&1
fi
