#!/bin/sh
#
#    Copyright (c) 1996-2002 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Initialization script to start/stop network services based on
#    chassis configuration.

# Commands
GREP=/bin/grep
SED=/bin/sed
CAT=/bin/cat
CUT=/usr/bin/cut
PS=/bin/ps
NETSTAT=/bin/netstat
KILL=/bin/kill
KILLALL=/usr/bin/killall
INETD_PROC=/usr/sbin/inetd

RESTART_INETD="0"

# No arguments, then show Telnet status
#if [ $# == 0 ]; then
	CHASSIS_FILE="/etc/fabos/fabos.chassis.conf"
#else
#	CHASSIS_FILE=$1
#fi

# Only accept 1 argument
#if [ $# > 1 ]; then
#  echo Too many arguments
#  echo Usage: $0 [config file]
#  exit 1
#fi


# Does file exist?
if [ ! -r $CHASSIS_FILE ]; then
	echo File does not exist: $CHASSIS_FILE
	exit 0;
fi


# Which services should be enabled based on chassis configuration?
SHALL_TELNET_ENABLE=1
SHALL_RSTAT_ENABLE=`$GREP "^rpc.rstatd:" $CHASSIS_FILE | $CUT -d':' -f2`
SHALL_RUSERS_ENABLE=`$GREP "^rpc.rusersd:" $CHASSIS_FILE | $CUT -d':' -f2`

# Edit /etc/inetd.conf, looking for lines which refer to the first parameter
# and update them according to the second parameter
update_inetd_conf(){
	umask 022
	WS=$'[ \t]'   		# WhiteSpace
	ARG=${1//\//\\/}	# Replace / with \/ in $1 and assign to ARG
	# if the service (telnet or rstat or rusers) is ON (uncommented)
	# AND we want it off ($2 == 0) then comment it out.
	if $GREP "^$1${WS}" /etc/inetd.conf >/dev/null ; then
		if [ "$2" == 0 ] ; then
			$SED -e "s/^$ARG${WS}/#&/" /etc/inetd.conf > /etc/inetd.conf.tmp &&
			mv -f /etc/inetd.conf.tmp /etc/inetd.conf
			echo "Updated inetd.conf to Disable $1 in inetdUpdate.sh"
			RESTART_INETD=1
		fi
	else
		if [ "$2" == 1 ] ; then
			$SED -e "/^#$ARG${WS}/s/#//" /etc/inetd.conf > /etc/inetd.conf.tmp &&
			mv -f /etc/inetd.conf.tmp /etc/inetd.conf
			echo "Updated inetd.conf to Enable $1 in inetdUpdate.sh"
			RESTART_INETD=1
		fi
	fi
}

# Update Telnet in inetd.conf as neccessary
update_inetd_conf telnet $SHALL_TELNET_ENABLE

# Update rstatd in inetd.conf as neccessary
update_inetd_conf rstatd/1-3 $SHALL_RSTAT_ENABLE

# Update rusersd in inetd.conf as neccessary
update_inetd_conf rusersd/1 $SHALL_RUSERS_ENABLE

# inetd.conf has been changed. Restart the daemon.
if [ "$RESTART_INETD" == "1" ]; then
	$KILLALL -q -HUP $INETD_PROC >/dev/null 2>&1

	if [ "$SHALL_TELNET_ENABLE" == "0" ]; then
		# Kill all existing telnet sessions
		for telpid in `$NETSTAT -tp | $GREP "telnet" | $GREP "ESTAB" | $SED -e 's/	+/ /g' |
                       $SED -e 's/  */ /g' | $CUT -d' ' -f7 | $CUT -d'/' -f1`
		do
			logpid=`$PS -ef | $GREP $telpid | $GREP login | $SED -e 's/	+/ /g' |
			        $SED -e 's/  */ /g' | $CUT -d' ' -f2`
			$KILL $logpid
		done
	fi
fi
