#!/bin/sh
#
#    Copyright (c) 1996-2014 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Initialization script to start/stop network services and interfaces.
#

# Source common library
. /etc/init.d/functions

YPCAT=/usr/bin/ypcat
YPSETDOM=/bin/ypdomainname
YPDOMFILE=/var/yp/ypdomain
LOCALHOST=127.0.0.1
IFCONFIG=/sbin/ifconfig
ROUTE=/sbin/route

AUTOMOUNT=/usr/sbin/automount
AUTOFILE=/etc/auto.master
AUTOMAP=auto.master

apply_manual_eth_setting()
{
    # delay invocation of mii-tool until after interface is up
    sleep 2
    if test -s $MIICFG; then
	/fabos/libexec/ifmode_to_ethmode.sh $MIICFG
    fi
}


#
# opts <additional automount options>
#
# Filter automount options
#
opts()
{
    echo "$1" | sed -e 's/--*t\(imeout\)*[ \t]*[0-9][0-9]*//g
		        s/\(^\|[ \t]\)-/\1/g'
}

#
# getmounts
# 
# Check for file- or NIS-based automount maps
#
getmounts()
{
    #
    # Check for local, file-based maps to load.
    #
    if [ -f $AUTOFILE ]; then
	cat $AUTOFILE | sed -e '/^#/d' -e '/^$/d'| (
	    while read dir map options
	    do
		if [ ! -z "$dir" -a ! -z "$map" \
			-a x`echo "$map" | cut -c1` != 'x-' ]; then

		    mountoptions=`cat ${CONFDIR}/automount.options 2> ${NULL}`
		    options=`opts $options`

		    cmd="$AUTOMOUNT $mountoptions $dir"

		    case $map in
		    /*)	
			if [ -x $map ]; then
			    echo "$cmd program $map $options"
			elif [ -f $map ]; then
			    echo "$cmd file $map $options"
			else
			    echo "$cmd `basename $map` $options"
			fi
			;;
		    *)
			if [ -f /etc/$map ] ; then
			    echo "$cmd file /etc/$map $options"
			else
			    echo "$cmd yp $map $options"
			fi
			;;
		    esac
		    unset cmd
		fi
	    done
	)
    fi

    $YPCAT -k $AUTOMAP
    # Check for remote, NIS-based maps to load

    if [ -x $YPCAT ] && [ `$YPCAT -k $AUTOMAP 2> ${NULL} | wc -l` -gt 0 ]; then
	$YPCAT -k $AUTOMAP | (
	while read dir map options
	do
	    if [ ! -z "$dir" -a ! -z "$map" \
			-a x`echo "$map" | cut -c1` != 'x-' ]; then
		map=`echo "$map" | sed -e 's/^auto_/auto./'`
		
		mountoptions=`cat ${CONFDIR}/automount.options 2> ${NULL}`
		options=`opts $options`
		cmd="$AUTOMOUNT $mountoptions $dir"

		echo "$cmd yp $map $options"
	    fi
	done
	)
    fi
}

#
# configif <name> <address> <number> 
#
# Configure a network interface
#
configif()
{
    $IFCONFIG $1 inet $2 `cat ${CONFDIR}/ifconfig-$3.options 2> ${NULL}` \
	2> ${NULL}
}

#
# nfsroot
#
# Determine whether or not this system is running an NFS root
# file system.
#
nfsroot()
{
    grep ' / nfs' /proc/mounts > ${NULL} 2>&1
    return
}
    
SWBD=`sin | swbd 2> ${NULL}`
CPID=`sin | cpid 2> ${NULL}`
SLOT=`sin 2>/dev/null | grep "Slot No:" | cut -d ':' -f 2 | cut -d ' ' -f 2`
PARTITION=1
if [ "`cat /proc/device-tree/label 2>${NULL}`" = "p2-linux" ]; then
	PARTITION=2
fi

COCPU_NETBOOT=0
if test "$SWBD" = "SWBD63"; then
	if test "`bootenv bootcmd 2> ${NULL} | grep dhcp`" != ""; then
		COCPU_NETBOOT=1
	fi
fi


case "$1" in

'start')

    # Try to determine if we should come up in standalone mode or not.

    HOSTNAME=`hostname`
    NETMODE="standalone"

	# Linux 2.6: by default, this is set to 1. No ping to broadcast IP works
	# Changing this to 0
	echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts

	# adding following as default it should act as router
	# managemnt port still act as host so restoring host functionality
	echo 0 > /proc/sys/net/ipv6/conf/eth0/forwarding
	echo 1 > /proc/sys/net/ipv6/conf/eth0/accept_ra
	echo 1 > /proc/sys/net/ipv6/conf/eth0/accept_ra_pinfo
	echo 1 > /proc/sys/net/ipv6/conf/eth0/accept_ra_defrtr

    case ${SWBD##SWBD} in
	'1000' | '1001' | '1002' | '1003')
		echo 0 > /proc/sys/net/ipv6/conf/eth2/forwarding
		echo 1 > /proc/sys/net/ipv6/conf/eth2/accept_ra
		echo 1 > /proc/sys/net/ipv6/conf/eth2/accept_ra_pinfo
		echo 1 > /proc/sys/net/ipv6/conf/eth2/accept_ra_defrtr
		;;
	esac

    if nfsroot; then
	NETMODE="inet"
    elif test -x /usr/bin/hostid; then
	if test "`hostid`" = "0"; then
	    SAREASON="Cannot resolve $HOSTNAME.\n"
	elif test "`hostid`" = "0a000000"; then
	    SAREASON="IP address set to factory default.\n"
	elif $CHECK network; then
	    NETMODE="inet"
	fi
    elif $CHECK network; then
	NETMODE="inet"			# Punt and assume it's OK
    fi

    # Figure out what the correct interface name(s) and address(es) is/are.
    # Here, "name" is the name of the network interface as reported by
    # 'netstat -i' and "address" is an IP address in dot notation.
    #
    # Edit /etc/config/if.options to override values used below.
    #
    # Note: If this host has more than 1 interface1, you must edit
    # /etc/config/if.options to set the IFNAME# and IFADDR# variables
    # as appropriate, and set IFNUM to the number of interfaces if
    # there are more than 2.

    # Setup default best-guesses

    IFADDR1=$HOSTNAME
    IFNUM=2

    # Derive interface names, don't worry about fc# interfaces, those
    # won't come up until after Fabric OS is up.

    if $IFCONFIG eth0 > ${NULL} 2>&1; then
	IFNAME1=eth0
    fi

    # Source any platform-dependent configuration options.

    case ${SWBD##SWBD} in
       "63")
		;;
	*)
    if test -s ${CONFDIR}/if.options; then
	. ${CONFDIR}/if.options
    fi
		;;
    esac

    # Configure the primary network interface.
	# if fabos is configured, then just ifconfig eth0 up with no IP address

	if $CHECK fabos; then
		IFADDR1NET="up"
	else
		IFADDR1NET=$IFADDR1
	fi

    CPID=`sin | cpid 2> ${NULL}`
    MIICFG=${CONFDIR}/fabos/mii.${CPID}.cfg

    if test "$NETMODE" = "inet"; then
	if ! configif $IFNAME1 $IFADDR1NET 1; then
	    SAREASON="Cannot access primary network interface $IFNAME1.\n"
	    NETMODE="standalone"
	fi
    elif test "$NETMODE" != "standalone"; then
	NETMODE="standalone"
    fi

	# Apply any manual configuration (ie done via setifmode) now
	# After allowing a 2 sec sleep to let the interface come up 1st.
	# But do this in the background so as not to impact ha timing

	apply_manual_eth_setting &


    if test $NETMODE = "standalone"; then
	$ECHO "${SAREASON}Using standalone network mode.\n"
	sleep 5

	# At this point, there's not much we can do. Try to program
	# the primary interface and then take it down.

	if test "$IFNAME1" != ""; then
	    $IFCONFIG $IFNAME1 inet $IFADDR1 2> ${NULL}
	    $IFCONFIG $IFNAME1 down          2> ${NULL}
	fi
	
	# Configure the loopback interface

	$IFCONFIG lo $LOCALHOST netmask 255.255.0.0
    else
	# Initialize secondary, tertiary, etc network interfaces.

	num=2
	while test $num -le $IFNUM; do
	    eval ifname='$'IFNAME${num} ifaddr='$'IFADDR${num}
	    if test -n "$ifname"; then
		if $IFCONFIG $ifname > ${NULL} 2>&1; then
		    configif $ifname $ifaddr $num
		fi
	    fi

	    ((num++))
	done

	# Configure the loopback interface

	$IFCONFIG lo $LOCALHOST netmask 255.255.0.0
    fi

	#
	# Defect 400454
	# There is a possiblility that due to power cycle when hosts file
	# is being modified the file may be corrupted or missing. Test and 
	# recover from this situation
	#
	if [ -f /etc/hosts ]; 
	then
		grep "localhost" /etc/hosts > /dev/null 2>&1
		h1=$?
		if [ $h1 -ne 0 ]; then
			echo "ERROR: Hosts file corrupted; Recovering";
			echo "
$LOCALHOST               localhost" >> /etc/hosts
		fi
	else
		echo "ERROR: Hosts file does not exist; Recovering";
		echo "
#
# Internet host table
#
$LOCALHOST               localhost" >> /etc/hosts.tmp
	mv /etc/hosts.tmp /etc/hosts
	fi

    # Configure, if necessary by switching on the numeric portion of
    # the platform ID, the internal system network such that internal
    # services can be started earlier. Arguably, this is a non-ideal
    # place for this code. At some future point, this should be moved
    # out to a platform-specific script (yet ideally generically
    # named, e.g. /etc/init.d/network.internal or /etc/init.d/
    # network.platform) that this one calls.


    case ${SWBD##SWBD} in
	'10' | '21' | '42')
	    # Configure the internal system network such that
	    # internal services can be started earlier. The primary
	    # address and subordinate route are based on the CP slot
	    # number, rooted at slot 5.

	    $IFCONFIG eth1 10.0.0.$((CPID % 2 + 5)) \
		netmask 255.255.255.0 > ${NULL} 2>&1
	    $ROUTE add -host 10.0.0.$((6 - CPID % 2)) dev eth1 > ${NULL} 2>&1
	    ;;

	'62' | '77')
		#
		# Ip address assignment for main-cpu interfaces
		# using Neptune scheme anyway, the IP and slot will be re-configured
		# if fabos is ON
		#
		$IFCONFIG eth1 127.1.1.$((CPID % 2 + 7)) \
			netmask 255.255.255.0 > ${NULL} 2>&1
		$ROUTE add -host 127.1.1.$((8 - CPID % 2)) dev eth1 > ${NULL} 2>&1

		# configure eth2 for neptune, 127.1.16.16, 127.1.17.17
		$IFCONFIG eth2 127.1.$((CPID % 2 + 16)).$((CPID % 2 + 16)) \
			netmask 255.255.255.0 > ${NULL} 2>&1

		# for service port
		$IFCONFIG eth3 up
		echo "loading bonding module"
		insmod /lib/modules/default/kernel/drivers/net/bonding/bonding.ko \
			mode=1 miimon=100
		# bind two ethernet if to bond0
		ifconfig bond0 up
		ifenslave bond0 eth0
		ifenslave bond0 eth3
		ifconfig bond0 inet cp$CPID

		MIICFG=${CONFDIR}/fabos/mii.${CPID}.eth3.cfg
		apply_manual_eth_setting &
	    ;;

	'63')
	    # this is for co-cpu to co-cpu 127.1.2.16 and 127.1.2.17
	    $IFCONFIG eth1 127.1.2.$((CPID % 2 + 16)) \
		netmask 255.255.255.0 > ${NULL} 2>&1
	    $ROUTE add -host 127.1.2.$((17 - CPID % 2)) dev eth1 > ${NULL} 2>&1

	    # this is for co-cpu 127.1.16.60 and 127.1.17.70
	    if test $COCPU_NETBOOT != 1; then
	    $IFCONFIG eth2 127.1.$((CPID % 2 + 16)).$(((CPID % 2 + 6) * 10)) \
		netmask 255.255.255.0 > ${NULL} 2>&1
	    fi
	    ;;  

    '131' | '137' | '151' | '153' | '154' | '155' | '164' | '138')
		$ECHO "IP interface setup on switch $PARTITION"
		ifconfig eth1 127.2.$PARTITION.0 netmask 255.255.0.0 > ${NULL} 2>&1
	    ;;  
	'1000' | '1001' | '1002' | '1003')
		$ECHO "IP interface setup on MM$SLOT"
		ifconfig eth2 127.2.1.$SLOT netmask 255.255.0.0 > ${NULL} 2>&1
		;;

	'1004' | '1005' | '1006' | '1008' | '1009' | '1010' | '1011')
		$ECHO "IP interface setup on LC$SLOT_$PARTITION"
		ifconfig eth0 127.2.$PARTITION.$SLOT netmask 255.255.0.0 > ${NULL} 2>&1
		;;
	*)
	    ;;
    esac

    case ${SWBD##SWBD} in
	 '42')
	    # Configure the eth2 network interface on saturn
	    # CP0 -> 127.1.15.15/255.255.255.0; CP1 -> 127.1.16.16/255.255.255.0

	    $IFCONFIG eth2 127.1.$((CPID % 2 + 15)).$((CPID % 2 + 15)) \
		netmask 255.255.255.0 > ${NULL} 2>&1
#	    /sbin/mii-tool -F 100baseTx-FD eth2
	    /sbin/ethtool -s eth2 autoneg off speed 100 duplex full
	    ;;
    esac

    case ${SWBD##SWBD} in
	 '46' | '67' | '79' | '80')
	    # Configure the eth2 network interface on sprint/spear
	    # CP -> 127.1.10.10/255.255.255.0;
	    $IFCONFIG eth2 127.1.$((CPID % 2 + 10)).$((CPID % 2 + 10)) \
		netmask 255.255.255.0 > ${NULL} 2>&1
#	    /sbin/mii-tool -r eth2
#	    /sbin/mii-tool -F 100baseTx-FD eth2
	    /sbin/ethtool -s eth2 autoneg off speed 100 duplex full
	    ;;
    esac

    case ${SWBD##SWBD} in
	 '95' | '96'  | '97' | '116')
	    # Configure the eth1 network interface on Elara2E 
	    # CP -> 127.1.10.10/255.255.255.0;
	    $IFCONFIG eth1 127.1.$((CPID % 2 + 10)).$((CPID % 2 + 10)) \
		netmask 255.255.255.0 > ${NULL} 2>&1
	    /sbin/ethtool -s eth1 autoneg off speed 100 duplex full
	    ;;
    esac

    case ${SWBD##SWBD} in
	 '83')
	    # change eth1 to eth2 in Spike so that ipfilter won't apply
	    # CP -> 127.1.10.10/255.255.255.0;
	    ip link set dev eth1 name eth2
	    $IFCONFIG eth2 127.1.$((CPID % 2 + 10)).$((CPID % 2 + 10)) \
		netmask 255.255.255.0 > ${NULL} 2>&1
	    ;;
	 
	*)
	    ;;
    esac

    # Configure static route(s), if available.

    if test $NETMODE = "inet" -a -s ${CONFDIR}/static-routes.options; then

	if ! $CHECK fabos; then

	# Check to see if the 0.0.0.0 IP address is set as the gateway
	# If so, then don't do the "route add" since it will just pump
	# out an error message because this value is invalid

    	grep -q 'route add default gw 0\.0\.0\.0$' ${CONFDIR}/static-routes.options

    	if [ $? -ne 0 ]; then
			. ${CONFDIR}/static-routes.options
		else
			echo There is no default Gateway IP Address set.
	fi
	fi
    fi

    # Add a default route to the host itself in case there is no route
    # specified in /etc/static-routes.options

	if ! $CHECK fabos; then
		route | grep -q default
		if [ $? -ne 0 ]; then
			$ROUTE add default gw $IFADDR1	    
			$ECHO "added route $IFADDR1"
		fi
	fi

    $ECHO "Network daemons:\c"

	${KILLALL} gated routed portmap

	if test $NETMODE = "inet"; then

	    # Start either gated or routed if they are installed and
	    # configured.

	    if $CHECK gated && test -x /usr/sbin/gated; then
		/usr/sbin/gated `cat ${CONFDIR}/gated.options 2> ${NULL}` &
						    $ECHO " gated\c"

	    elif $CHECK routed && test -x /usr/sbin/routed; then
		/usr/sbin/routed `cat ${CONFDIR}/routed.options 2> ${NULL}` &
						    $ECHO " routed\c"
	    fi					    
	fi

        # Start the RPC program number mapper (portmap)

        if test -x /sbin/portmap; then
	    /sbin/portmap `cat ${CONFDIR}/portmap.options 2> ${NULL}` &
                                                    $ECHO " portmap\c"
        fi

    $ECHO "."

    # NIS Support

    # Define the NIS domain name.

    if test -x $YPSETDOM; then
        # The domain file is needed only if NIS domain != Internet domain.
        YPDOMAIN=`cat $YPDOMFILE 2> ${NULL}`

        if test -z "$YPDOMAIN"; then
            # Extract the domain from the hostname.
            YPDOMAIN=`echo $HOSTNAME | sed -e 's/[^.]*\.\(.*\)/\1/'`
            if test "$YPDOMAIN" = "$HOSTNAME"; then
                # Hostname doesn't contain domain.
                YPDOMAIN=""
            fi
        fi

        # Set the domain even if "yp" is not "on" so ypbind can be
        # started by hand later.

        if test "$YPDOMAIN"; then
            $YPSETDOM $YPDOMAIN
        fi
    fi

    # Start NIS daemons.

    if test $NETMODE = "inet" && $CHECK nis; then
        if test -z "$YPDOMAIN"; then
            $ECHO "Cannot start NIS -- domain name not defined.\n"
            $ECHO "Edit $YPDOMFILE to contain your domain name and reboot.\n"
            sleep 10
        else
            $YPSETDOM $YPDOMAIN
            ${KILLALL} ypbind ypserv rpc.passwd

            $ECHO "NIS domain: $YPDOMAIN"
            $ECHO "NIS daemons:\c"

            # ypbind allows NIS clients to use NIS services.

            if test -x /sbin/ypbind; then
                /sbin/ypbind `cat ${CONFDIR}/ypbind.options 2> ${NULL}` &
                                                    $ECHO " ypbind\c"

		# wait till ypbind running or time out
		reps=0
		until ypwhich > ${NULL} 2>&1 || [ "$reps" = "10" ]
		do
		    $ECHO ".\c" ;
		    sleep 1
		    reps=$[$reps+1]
		done
            fi

            $ECHO "."
        fi
    fi

    # Start NFS daemons.

    if test $NETMODE = "inet" && $CHECK nfs; then

      # Mount any NFS file systems specified in /etc/fstab

      /bin/mount $VERBOSE -at nfs

      if $CHECK automount || $CHECK lockd; then

        $ECHO "NFS daemons:\c"

	# Linux NFS daemons are kernel-spawned threads. The only thing
	# to start is the automounter and lockd/statd, if so configured.

	# Start the automounter

        if $CHECK automount && test -x $AUTOMOUNT; then
            ${KILLALL} -TERM automount
	    getmounts | sh 2> ${NULL}
                                                    $ECHO " automount\c"
        fi

	# Start lockd/statd

        if $CHECK lockd; then
            if test -x /sbin/rpc.lockd; then
		${KILLALL} -TERM rpc.lockd
		/sbin/rpc.lockd `cat ${CONFDIR}/lockd.options 2> ${NULL}`
						    $ECHO " lockd\c"
            fi

	    if test -x /sbin/rpc.statd; then
		${KILLALL} -TERM rpc.statd
		/sbin/rpc.statd `cat ${CONFDIR}/statd.options 2> ${NULL}`
						    $ECHO " statd\c"
	    fi
        fi

        $ECHO "."

      fi
    fi

    # Start Internet daemons. Just about everything is spawned from inetd.

    $ECHO "Internet daemons:\c"

       ${KILLALL} inetd

       # Start the Internet "super-server"
       if test -x /usr/sbin/inetd; then
           if test -x /fabos/libexec/inetdUpdate; then
               /fabos/libexec/inetdUpdate
               /usr/sbin/inetd `cat ${CONFDIR}/inetd.options 2> ${NULL}` < ${NULL}
               $ECHO " inetd\c"
           fi
       fi

    $ECHO "."
    ;;

'stop')
    $ECHO "Stopping network services...\c"

    #  Servers that might start shells.
    USERS='in.rlogind in.rexecd in.rshd in.ftpd in.telnetd in.sshd'

    #  The following servers should be killed immediately.
    EDAEMONS='inetd bootp tftpd automount rpc.mountd rpc.statd rpc.lockd
                rpc.bootparamd rpc.rexd rpc.rstatd rpc.rusersd
                rpc.rwalld snmpd'

    #  Remote daemons
    RDAEMONS='ypbind gated routed'

    #  These daemons should be kept alive until the last minute.
    LDAEMONS='portmap tcpd'

    #  Kill (probable) shell process groups first
    ${KILLALL} -g $USERS
    ${KILLALL} -TERM $EDAEMONS $USERS
    ${KILLALL} -TERM $RDAEMONS
    ${KILLALL} mount umount $USERS $EDAEMONS $RDAEMONS $LDAEMONS

    # Unmount all nfs filesystems
    for nfs_fs in `mount | grep nfs | cut -f 3 -d ' '`; do
	umount $nfs_fs
    done
    
    # Bring down all interfaces.
    for device in `ifconfig | grep ^[a-z] | grep -v ^vlan | cut -f1 -d ' '`; do
	$IFCONFIG $device down
    done

    $ECHO "done."
    ;;

*)
    echo "usage: $0 {start | stop}"
    ;;
esac
