#!/bin/sh
#
# Copyright (c) 1995, by Sun Microsystems, Inc.
# All Rights Reserved
#
#ident  "$Header: /net/projects/S2.6/cvs/os_net/src_ws/usr/src/tadcmd/locations/init.d/inetsvc,v 1.2 1997/12/08 13:56:36 ang Exp $"
#
#LocINFO Internet Daemon secondary services.
#
# This is third phase of TCP/IP startup/configuration.  This script
# runs after the NIS/NIS+ startup script.
#

killproc() {		# kill the named process(es)
	pid=`/usr/bin/ps -e |
	     /usr/bin/grep " ${1}$" |
	     /usr/bin/sed -e 's/^  *//' -e 's/ .*//'`
	[ "$pid" != "" ] && kill $pid
}

procexist() {
    pid=`/usr/bin/ps -e | /usr/bin/grep " ${1}$" |
	     /usr/bin/sed -e 's/^  *//' -e 's/ .*//'`
    if [ -z "$pid" ]
    then
	return 1
    fi
    return 0
}

case "$1" in
'start')
    if [ -f $LOCDB/etc/mcastif ]
    then
	cp -p $LOCDB/etc/mcastif /etc
    fi

    #
    # XXX - We need to give ypbind time to bind to a server.
    #
    sleep 5
    # 
    # Re-set the netmask and broadcast addr for all IP interfaces.  This
    # ifconfig is run here, after NIS has been started, so that "netmask
    # +" will find the netmask if it lives in a NIS map.
    # The 'D' in -auD tells ifconfig NOT to mess with the interface
    # if it is under DHCP control
    #
    
    /usr/sbin/ifconfig -auD netmask + broadcast +
    
    # This is a good time to verify that all of the interfaces were
    # correctly configured.  But this is too noisy to run every time we
    # boot.
    #
    # echo "network interface configuration:"
    # /usr/sbin/ifconfig -a
    
    #
    # Add a static route for multicast packets out our default interface.
    # The interface is specified in /etc/mcastif
    #
    mcastif=`/sbin/dhcpinfo Yiaddr 2>/dev/null`
    
    if [ $? -ne 0 -a -f /etc/mcastif ]; then
	    mcastif=`cat /etc/mcastif`
    fi
    
    if [ -n "$mcastif" ]
    then
	echo "Setting \"$mcastif\"interface for multicast: \c"
	/usr/sbin/route add -interface -netmask "240.0.0.0" "224.0.0.0" "$mcastif"
    fi
    
    ;;

'stop')
    nawk '{if (substr($1,0,1) == "#" || length($1) == 0 || length($7) == 0)
	    next;
	print substr($7,match($7,"[^/]*$"),8)}' </etc/inetd.conf | while read P
    do
	killproc $P
    done

    mcastif=`/sbin/dhcpinfo Yiaddr 2>/dev/null`
    
    if [ $? -ne 0 -a -f /etc/mcastif ]; then
	mcastif=`cat /etc/mcastif`
    fi
    
    if [ -n "$mcastif" ]
    then
	route delete "224.0.0.0" "$mcastif" 0
    fi
    rm -f /etc/mcastif
    ;;

'create')
    # Pick an interface for M-Cast
    if [ ! -s /etc/mcastif ]
    then
	MCA=`netstat -rn | awk '{if ($1 == "224.0.0.0" && $2 != "127.0.0.1") print $2}'`
	if [ -n "$MCA" ]
	then
	    echo $MCA >/etc/mcastif
	else
	    set `echo /etc/hostname\.*[0-9]`
	    if [ -f "$1" ]
	    then
		cp $1 /etc/mcastif
	    fi
	fi
    fi
    if [ -f /etc/mcastif ]
    then
	cp -p /etc/mcastif $LOCDB/etc 2>/dev/null
    fi
    ;;

*)
    echo "Usage: $0 { start | stop | create }" 1>&2
    ;;
esac

exit 0
