#!/bin/sh
#
#    Copyright (c) 1996-2004 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Initialization script to start/stop sshd.
#

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

SSHD=/usr/sbin/sshd
CIPHERS="Ciphers=3des-cbc,aes128-cbc,aes192-cbc,aes256-cbc"
MACS="Macs=hmac-sha1"
IPTABLES="/sbin/iptables"
IP6TABLES="/sbin/ip6tables"
AWK="/bin/awk"
GREP="/bin/grep"
SSHUTIL=/fabos/sbin/sshutil
WC="/usr/bin/wc"
CAT="/bin/cat"
CUT="/usr/bin/cut"

#Check for FIPS mode
checkFipsMode() {
    	# "config get" for fips mode returns value only if called from
   	# default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
    	# revert it back to its original value after "config get"
    	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    	FABOS_SWITCHNO=0
    	retVal1=`/fabos/cliexec/config get fips.mode 2`
    	retVal2=`/fabos/cliexec/config get fips.simulate 2`
    	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	retVal=0

	if [ $retVal1 -eq 1 ]; then
		return $retVal1
	elif [ $retVal2 -eq 1 ];  then
		return $retVal2
	else 
		return $retVal
	fi

}
case "$1" in

'start')
    $ECHO "Secure shell daemon:\c"

	if $CHECK sshd; then
	    ${KILLALL} sshd
	    if test -x $SSHD; then
				checkFipsMode
				fipsmode=$?
				#if [ "$fipsmode" == "1" ]; then
				#	$SSHD -o $CIPHERS -o $MACS `cat ${CONFIGDIR}/sshd.options 2> ${NULL}`
				#else

					# If no host key present on switch and Telnet is blocked, generate 
					# a rsa host key
					totalhostkeys=`$SSHUTIL showhostkey | $WC -l`
					if [ $totalhostkeys -eq 0 ]; then
						ruleAct=`$IPTABLES -L telnet0 | $GREP dpt:telnet | $AWK 'NR==1{print $1}'`
						if [ "$ruleAct" != "ACCEPT" ]; then
							$SSHUTIL genhostkey -rsa
						else
							ruleAct=`$IP6TABLES -L telnet0 | $GREP dpt:telnet | $AWK 'NR==1{print $1}'`
							if [ "$ruleAct" != "ACCEPT" ]; then
								$SSHUTIL genhostkey -rsa
							fi
						fi
					fi

					$SSHD `$CAT ${CONFIGDIR}/sshd.options 2> ${NULL}`
				#fi
				$ECHO " sshd\c"
	    fi
	fi

    $ECHO "."
    ;;

'stop')
    ${KILLALL} sshd
    ;;    

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

esac
