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

START=49

EXTRA_COMMANDS="off status "

register_wifi_hwnat() {
    is_reg=$1

    reg_wifi() {
        cfg=$1
        register=$2

        config_get ifname $cfg ifname
        if [ "$2" == "1" ]; then
            iwpriv $ifname set hw_nat_register=1 >/dev/null 2>&1
        else
            iwpriv $ifname set hw_nat_register=0 >/dev/null 2>&1
        fi
    }

    . /lib/functions.sh
    config_load wireless
    config_foreach reg_wifi wifi-iface $is_reg

    return 0
}

start() {
    # make sure hwnat0 dev ready
    ls /dev/hwnat0 >/dev/null 2>&1 || mknod /dev/hwnat0 c 220 0

    # make sure ko loaded
    lsmod | grep hw_nat >/dev/null 2>&1 || insmod "/lib/modules/$(uname -r)/hw_nat.ko"

    # reg wireless interface into hwnat
    register_wifi_hwnat 1

    #make sure hwnat is not work for AP mode
    mode=$(uci get xiaoqiang.common.NETMODE 2>/dev/null)
    if [ "$mode" == "wifiapmode" -o "$mode" == "lanapmode" ]; then
        # switch hwnat off
        echo 0 >/proc/sys/net/hwnat/enable
        return 0
    fi

    ###### Enter Non-AP mode ########

    #put host+guest ip into hwnat
    host_ip=$(uci -q get network.lan.ipaddr)
    guest_ip=$(uci -q get network.guest.ipaddr)

    # set host/guest ip into hwnat
    [ -n "$host_ip" ] && echo $host_ip >/proc/sys/net/hwqos/host_lan
    [ -n "$guest_ip" ] && echo $guest_ip >/proc/sys/net/hwqos/guest_lan
    echo "set host $host_ip and guest $guest_ip into hwqos done."

    # switch hwnat on
    echo 1 >/proc/sys/net/hwnat/enable
    return 0
}

#hwnat enable for mt7621, so dummy stop to make system happy
stop() {
    echo "hwnat dummy stop."
    return 0
}

off() {
    # switch off hnat
    echo 0 >/proc/sys/net/hwnat/enable
    return 0
}

status() {
    st=$(cat /proc/sys/net/hwnat/enable 2>/dev/null)
    if [ "$st" = "1" ]; then
        echo "HWNAT: ON"
        return 0
    else
        echo "HWNAT: OFF"
        return 1
    fi
}

restart() {
    off
    start
    return 0
}
