#! /bin/sh
#
# Generic network daemon RC script. If installed as /etc/rc.d/init.d/foobar,
# it source /etc/sysconfig/daemons/foobar and looks at the
# variable definitions (Bourne shell syntax). Variables marked with an
# asterisk are required.
#
# * IDENT=sshd
#   DESCRIPTIVE="@OPENSSH_VERSION@"
# * DAEMON=/usr/sbin/sshd
#   DAEMON_ARGS="-p some_other_port"
#   ONBOOT=yes
#

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# Source function library, check sysconfig/daemon file and source it.
. /etc/rc.d/init.d/functions

[ -x $DAEMON ] || exit 0

# Some functions to make the below more readable
KEYGEN=/usr/bin/ssh-keygen
RSA1_KEY=/etc/ssh/ssh_host_key
RSA_KEY=/etc/ssh/ssh_host_rsa_key
DSA_KEY=/etc/ssh/ssh_host_dsa_key
PID_FILE=/var/run/sshd.pid
do_rsa1_keygen() {
	if ! test -f $RSA1_KEY ; then
		echo -n "Generating SSH1 RSA host key: "
		if $KEYGEN -q -t rsa1 -f $RSA1_KEY -C '' -N '' >&/dev/null; then
			echo "RSA1 key generation success"
		else
			echo "RSA1 key generation failure"
			exit 1
		fi
	fi
}
do_rsa_keygen() {
	if ! test -f $RSA_KEY ; then
		echo -n "Generating SSH2 RSA host key: "
		if $KEYGEN -q -t rsa -f $RSA_KEY -C '' -N '' >&/dev/null; then
			echo "RSA key generation success"
		else
			echo "RSA key generation failure"
			exit 1
		fi
	fi
}
do_dsa_keygen() {
	if ! test -f $DSA_KEY ; then
		echo -n "Generating SSH2 DSA host key: "
		if $KEYGEN -q -t dsa -f $DSA_KEY -C '' -N '' >&/dev/null; then
			echo "DSA key generation success"
		else
			echo "DSA key generation failure"
			exit 1
		fi
	fi
}

# See how we were called.
case "$1" in
  start)
	# Create keys if necessary
	do_rsa1_keygen
	do_rsa_keygen
	do_dsa_keygen

        # Start daemons.
	[ ! -e $LOCK ] || exit 1
	echo -n "Starting $SUBSYS services: "
	start-stop-daemon -S -n $IDENT -x $DAEMON -- $DAEMON_ARGS
	sleep 1
        echo .
	touch $LOCK
        ;;
  stop)
        # Stop daemons.
	[ -e $LOCK ] || exit 0
	echo -n "Stopping $SUBSYS services: "
	start-stop-daemon -K -n $IDENT -x $DAEMON
        echo
	rm -f $LOCK
        ;;
	restart)
		$0 stop
		$0 start
		;;
  *)
        echo "Usage: $SUBSYS {start|stop|restart}"
        exit 1
esac

exit 0
