#! /bin/bash

#
# Copyright (c) 2002 Compaq Computer Corporation.  All Rights Reserved.
#
# Permission to use, copy, and modify this software and its documentation
# is hereby granted under the following terms and conditions.  The above
# copyright notice, this permission notice, and the following disclaimer
# must appear in all copies of the software, derivative works or modified
# versions.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND COMPAQ COMPUTER CORP. DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL COMPAQ COMPUTER
# CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
# PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE.
#

# default libexecdir used to bootstrap scripts
libexecdir=${GLOBUS_LOCATION}/libexec

# load GRIS common code and initialization
. ${libexecdir}/grid-info-net-common

#########################################################################

probe_resource_net ()
{
    ${GLOBUS_SH_NETSTAT-netstat} -in | \
    {
	i=0
	read header
	while read iface mtu netaddr ipaddr rest
	do
	    #
	    # If CIDR format, set $netbits to network part, else set 0.
	    netbits=0
	    eval `echo "$netaddr" | \
		sed -e 's,^,addr=",' -e 's,/," netbits=",' -e 's,$,",'`

	    #
	    # If $addr valid, append zeroed quads for IPv4 and
	    # ensure that $netbits is set to something reasonable.
	    # Else if not valid, just ignore it.
	    case "$addr" in
		*.*.*.*)
		    :
		    ;;
		*.*.*)
		    addr="${addr}.0"
		    ;;
		*.*)
		    addr="${addr}.0.0"
		    ;;
		[12][0-9][0-9]|[0-9][0-9]|[0-9])
		    addr="${addr}.0.0.0"
		    ;;
		*)
		    # IPv6, link identifiers, etc... just ignore.
		    continue
		    ;;
	    esac

	    #
	    # IPv4: if network part unknown, just cobble up something.
	    if [ "$netbits" -eq 0 ]; then
		case "$addr" in
		    *.0.0.0)
			netbits=8
			;;
		    *.0.0)
			netbits=16
			;;
		    *.0)
			netbits=24
			;;
		    *)
			netbits=32
			;;
		esac
	    fi

	    #
	    # Generate IPv4 hex netmask with $netbits leading 1s.
	    # (commented out, since no one asks for this).
#	    netmask=`dc <<EOF_dc
#16o 4294967295 2 32 ${netbits} - ^ 1 - - p s.
#EOF_dc
#`
	    eval "_net_${i}_name=${iface}"
	    eval "_net_${i}_mtu=${mtu}"
	    eval "_net_${i}_netaddr=\"${addr}\""
	    eval "_net_${i}_netbits=\"${netbits}\""
	    eval "_net_${i}_ipaddr=\"${ipaddr}\""
	    case "$ipaddr" in
		none) : ;;
		*) i=`$EXPR $i + 1` ; ;;
	    esac
	done
	_net_count=$i

	# run this in initialized subshell environment
	emit_resource_net_descriptions
    }
}

#############
# do the work
probe_resource_net

