#!/sbin/sh
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"@(#)sshd	1.2	05/11/07 SMI"
#
# If sshd is configured (/etc/ssh/sshd_config exists and is readable),
# the start it up.
# Checks to see if RSA, and DSA host keys are available
# if any of these keys are not present, the respective keys are created.

SSHDIR=/etc/ssh
KEYGEN="/usr/bin/ssh-keygen -q"
PIDFILE=/var/run/sshd.pid

create_key()
{
	keypath=$1
	keytype=$2
 
	if [ ! -f $keypath ]; then
		grep "^HostKey $keypath" $SSHDIR/sshd_config > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo Creating new $keytype public/private host key pair
			$KEYGEN -f $keypath -t $keytype -N ''
		fi
 	fi
}

case $1 in 
'start')
	create_key $SSHDIR/ssh_host_rsa_key rsa
	create_key $SSHDIR/ssh_host_dsa_key dsa

	/usr/lib/ssh/sshd &
	;;
'stop')
	#
	# If we are switching Run level downwards then we disconnect
	# all connections.
	#
	# Otherwise we just kill the master daemon that is listening
	# and leave the connections active
	if [ -z "$_INIT_RUN_LEVEL" ]; then
		set -- `/usr/bin/who -r`
		_INIT_RUN_LEVEL="$7"
		_INIT_PREV_LEVEL="$9"
	fi
	
	if [ $_INIT_RUN_LEVEL -lt $_INIT_PREV_LEVEL ]; then
		/usr/bin/pkill -u 0 -x sshd
	elif [ -f "$PIDFILE" ]; then
		/usr/bin/kill -TERM `/usr/bin/cat $PIDFILE`
	fi
	;;

'restart')
	if [ -f "$PIDFILE" ]; then
		/usr/bin/kill -HUP `/usr/bin/cat $PIDFILE`
	fi
	;;
*)
	echo "Usage: $0 { start | stop }"
	exit 1
	;;
esac	
