#!/bin/sh /etc/rc.common
. /lib/functions.sh

START=99
SERVICE_DAEMONIZE=1
SERVICE_WRITE_PID=1
TCPERUSERD_DAEMON=/usr/bin/sntcd
TCPERUSERD_CONF=/tmp/etc/sntcd/sntcd.conf

_generateTrafficControlConf() {
    local cfg="$1"
    config_get disabled "$cfg" disabled

    if [ "$disabled" = "1" ]
    then
        return
    fi

    config_get tc_enabled "$cfg" tc_enabled
    config_get ifname "$cfg" ifname

    # Yolin: support peruser traffic control
    if [ "$tc_enabled" = "1" ];then
        config_get downlimit "$cfg" tc_downlimit 0
        config_get uplimit "$cfg" tc_uplimit 0
        config_get downperuser "$cfg" tc_downperuser 0
        config_get upperuser "$cfg" tc_upperuser 0
        config_get guestmode "$cfg" guest_network "Disable"
        config_get downmaxlimit "$cfg" tc_downmaxlimit -1
        config_get upmaxlimit "$cfg" tc_upmaxlimit -1

        if [ $downmaxlimit -eq -1 ];then
            if [ $downperuser -eq 1 ];then
                downmaxlimit=0
            else
                downmaxlimit=$downlimit
                downlimit=0
            fi
        fi

        if [ $upmaxlimit -eq -1 ];then
            if [ $upperuser -eq 1 ];then
                upmaxlimit=0
            else
                upmaxlimit=$uplimit
                uplimit=0
            fi
        fi


        [ -f $TCPERUSERD_CONF ] || echo "# ifname downmaxlimit downlimit upmaxlimit uplimit [ w/l hookIF]" > $TCPERUSERD_CONF
        if [ "$guestmode" = "Disable" -a $ifname != "ath27" -a "$ifname" != "ath57" ];then
            #### for legacy firmware use ethx for traffic controll ################
            # Disable will bridge to br-lan
            echo "$ifname $downmaxlimit $downlimit $upmaxlimit $uplimit w $(uci get /rom/etc/config/network.lan.ifname | awk '{print $1}')" >> $TCPERUSERD_CONF
            lan2name=`uci get /rom/etc/config/network.lan.ifname | awk '{print $2}'`
            if [ "$lan2name" != "" ];then
                echo "$ifname $downmaxlimit $downlimit $upmaxlimit $uplimit w $lan2name" >> $TCPERUSERD_CONF
            fi
        else
            #### use athx for traffic controll  ##############################
            ifconfig $ifname txqueuelen 1000 > /dev/null
            echo "$ifname $downmaxlimit $downlimit $upmaxlimit $uplimit l $ifname" >> $TCPERUSERD_CONF
        fi
        return
    else
        test -d /sys/class/net/$ifname && ifconfig $ifname txqueuelen 0
    fi
}

generateTrafficControlConf() {
    config_load wireless
    config_foreach _generateTrafficControlConf wifi-iface
}

start() {
    mkdir -p $(dirname $TCPERUSERD_CONF)
    [ -f $TCPERUSERD_CONF ] && rm -f $TCPERUSERD_CONF

    generateTrafficControlConf

    if [ -e $TCPERUSERD_DAEMON ]; then
        if [ -f $TCPERUSERD_CONF ]; then
            service_start $TCPERUSERD_DAEMON -c$TCPERUSERD_CONF
        fi
    fi
}

stop() {
    if [ -e $TCPERUSERD_DAEMON ]; then
        service_stop $TCPERUSERD_DAEMON
    fi
}

reload() {
    stop
    start
}
