#!/bin/sh
. /lib/functions/gl_util.sh

get_modem_iface()
{
    node=$(uci -q get glmodem.global.usbnode)
    if [ -z "$node" ]; then
        build_in="$(cat /proc/gl-hw-info/build-in-modem 2>/dev/null)"
        [ -z "$build_in" ] && build_in="$(cat /proc/gl-hw-info/usb-port 2>/dev/null)"
    else
        build_in=$node
    fi
    if [ "$(echo $build_in | grep -q ',';echo $?)" = "0" ]; then
        build_in_array="${build_in/,/ }"
        for modem in $build_in_array; do
            ls /tmp/usbnode/* | grep -q "$modem"
            [ "$(echo $?)" = "0" ] && bus=$modem
        done
    elif [ -z "$(echo $build_in | grep '-')" ]; then
        ls /sys/bus/pci/devices/* |grep -q "$build_in"
        [ "$(echo $?)" = "0" ] && bus=$build_in
    else
        ls /tmp/usbnode/* | grep -q "$build_in"
        [ "$(echo $?)" = "0" ] && bus=$build_in
    fi
    if [ -n "$bus" ]; then
        if [ -n "$(echo $bus | grep '-')" ]; then
            modem_iface="modem_$(echo $bus | sed 's/-/_/g' | sed 's/\./_/g')"
        else
            modem_iface="modem_$(echo ${bus%%:*})"
        fi
    fi
    echo $modem_iface
}

[ "$(uci -q get glconfig.general.inited)" = "1" ] || exit 0
if [ -z "$(uci -q get network.wan6)" -o -z "$(uci -q get network.tethering6)" -o -z "$(uci -q get network.wwan6)" ]; then
	uci set network.wan6.ifname='@wan'
	[ -n "$(uci -q get network.wan6.device)" ] && uci delete network.wan6.device
	[ -z "$(uci -q get network.wan.ipv6)" ] && uci set network.wan.ipv6='0'
	[ -z "$(uci -q get network.wan6.disabled)" ] && uci set network.wan6.disabled='1'

	uci set network.tethering6='interface'
	uci set network.tethering6.ifname='@tethering'
	uci set network.tethering6.proto='dhcpv6'
	[ -z "$(uci -q get network.tethering6.disabled)" ] && uci set network.tethering6.disabled='1'

	uci set network.wwan6='interface'
	uci set network.wwan6.ifname='@wwan'
	uci set network.wwan6.proto='dhcpv6'
	[ -z "$(uci -q get network.wwan6.disabled)" ] && uci set network.wwan6.disabled='1'
	uci commit network

	# add modem config
	modem_iface=$(get_modem_iface)
	if [ -n "$modem_iface" ]; then
		uci set network.${modem_iface}_6='interface'
		uci set network.${modem_iface}_6.ifname="@${modem_iface}"
		uci set network.${modem_iface}_6.proto='dhcpv6'
		[ -z "$(uci -q get network.${modem_iface}_6.disabled)" ] && uci set network.${modem_iface}_6.disabled='1'
	fi
fi