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

START=95

VER=$(uname -r)

ip_to_uint()
{
	local a=$(echo $1 | cut -d '.' -f1)
	local b=$(echo $1 | cut -d '.' -f2)
	local c=$(echo $1 | cut -d '.' -f3)
	local d=$(echo $1 | cut -d '.' -f4)

	local uint=$(expr $a \* 256 \* 256 \* 256 \
		+ $b \* 256 \* 256 \
		+ $c \* 256 \
		+ $d)
	echo $uint
}

start()
{
    local tpmod_exist=$(lsmod | grep -w tp_domain)
    if [ "$tpmod_exist" != "" ]; then
        echo "tp_domain has been insmod" > /dev/console
        return
    fi
    local section=$(uci show vnetwork | grep "system=1" | cut -d'.' -f2)
    local vnet_ip=$(uci get "vnetwork.$section.ipaddr")
    vnet_ip=$(ip_to_uint "$vnet_ip")

    local default_domains=$(uci -c /etc/profile.d get profile.@tp_domain[0].domain)
    if [ -z "$default_domains" ]; then
        default_domains="omadaer.net"
    else
        default_domains=$(echo "$default_domains" | tr ' ' ';' | sed 's/;$//')
    fi

    local ip
    if [ -n "$vnet_ip" ]; then
        ip=$vnet_ip
    else
        echo "get vnetwork config failed" > /dev/console
    fi

    [ -f "/lib/modules/$VER/tp_domain.ko" ] && {
        if [ -z "$ip" ]; then
            insmod /lib/modules/$VER/tp_domain.ko
        else
            insmod /lib/modules/$VER/tp_domain.ko lan_ip=$ip lan_domain=$default_domains
        fi
        if [ $? -eq 0 ]; then
            echo "ip is seted to $ip, domain is seted to $default_domains" > /dev/console
            echo "insmod tp_domain success" > /dev/console
        else
            echo "insmod tp_domain failed" > /dev/console
        fi
    }
}

stop()
{
    echo "rmmod tp_domain success" > /dev/console
    rmmod tp_domain
}

restart()
{
    stop
    start
}