#!/bin/bash
#
#ident	"@(#)sysidtool-net.sh 1.23     05/05/10 SMI"
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# /lib/svc/method/sysidtool-net
#
# Script to invoke sysidnet, which completes configuration of basic
# network parameters.
#
# Copyright 2005 Nexenta Systems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# $Id: elatte-sysidtool-net 112552 2006-08-16 22:29:10Z erast $
#

. /lib/svc/share/smf_include.sh

SYSIDSTATE=/etc/.sysIDtool.state

config_interfaces() {

	#
	# Get the complete list of network devices
	# so that we can revarp them individually
	# since the -ad option seems to stop after
	# the first failure (unconnected net device)
	# that it encounters
	#
	net_device_list=`dladm show-link | nawk '
	BEGIN {
		lcount=0
		acount=0
	}
	{
		if ($2 == "phys")  {
			flag = 0;
			for (j=0;j<acount;j++) {
				if (aggr[j] == $1) {
					flag = 1
					break
				}
			}
			if (flag == 0) {
				link[lcount++]=$1
			}
		} else if ($2 == "aggr") {
			for(k=6;k<=NF;k++) {
				for (j=0; j<lcount; j++) {
					if ($k == link[j]) {
						delete link[j]
					}
				}
				aggr[acount++] = $k
			}
		}
	}
	END {
		for(j=0;j<lcount;j++) {
			if (link[j] != "") print link[j]
		}
	}'`

	echo `gettext "Configuring network interface addresses:"`"\\c" \
	    > /dev/sysmsg

	set -- $net_device_list
	for i 
	do
		echo " ${i}\c" > /dev/sysmsg

		#
		# try DHCP first then reverse ARP
		#
		/sbin/ifconfig $i auto-dhcp >/dev/null 2>&1
		ipaddr=`/sbin/ifconfig $i |grep inet |awk '{print $2;}'`
		if [ "X$ipaddr" = "X0.0.0.0" ] ; then
			/sbin/ifconfig $i auto-revarp netmask + broadcast + \
			    >/dev/null 2>&1
			ipaddr=`/sbin/ifconfig $i |grep inet |awk '{print $2;}'`
			if [ "X$ipaddr" != "X0.0.0.0" ] ; then
				# The interface configured itself correctly
				/sbin/ifconfig $i up
			fi
		fi
	done
	echo `gettext "."` > /dev/sysmsg

	set -- $net_device_list
	for i 
	do
		#
		# don't print loopback address
		#
		if [ "$i" = "lo0" ]; then
			continue
		fi

		#
		# print out interface addresses
		#
		ipaddr=`/sbin/ifconfig $i |grep inet |awk '{print $2;}'`
		if [ "X$ipaddr" != "X0.0.0.0" ] ; then
			echo "${i} configured as ${ipaddr}" > /dev/sysmsg
		fi
	done
	#/sbin/hostconfig -p bootparams > /dev/null 2>&1
}

if [ -f /etc/.UNCONFIGURED ] ; then

 	#
 	# set the _INIT_NET_IF and _INIT_NET_STRATEGY variables.
 	#
 	smf_netstrategy

	#
	# TODO: do equivalent of sysidnet
	#

 	if [ "${_INIT_ZONENAME:=`/sbin/zonename`}" = "global" -a \
 		"X$_INIT_NET_STRATEGY" != "Xdhcp" ] ; then
 		config_interfaces
 	fi
fi

exit 0
