#! /bin/sh

# /etc/init.d/ssh: start and stop the OpenBSDh "secure shell(tm)" daemon

test -x /usr/sbin/sshd || exit 0
( /usr/sbin/sshd -\? 2>&1 | grep -q OpenSSH ) 2>/dev/null || exit 0

# forget it if we're trying to start, and /etc/ssh/NOSERVER exists
if /usr/bin/expr "$1" : '.*start$' >/dev/null && [ -e /etc/ssh/NOSERVER ]; then 
    echo "Not starting OpenBSD Secure Shell server (/etc/ssh/NOSERVER)"
    exit 0
fi

update_sshd_config() {
    protocols = ""
    if [ -e /etc/ssh/ssh_host_dsa_key ]; then
	if [ -e /etc/ssh/ssh_host_key ]; then
	    protocols="Protocol 2,1"
	else
	    protocols="Protocol 2"
	fi
    else
	if [ -e /etc/ssh/ssh_host_key ]; then
	    protocols="Protocol 1"
	fi
    fi
    sed "s/^Protocol.*/$protocols/" < /etc/ssh/sshd_config > /tmp/sshd_config
    cp /tmp/sshd_config /etc/ssh/sshd_config
}

# Configurable options:

case "$1" in
  start)
	test -f /etc/ssh/sshd_not_to_be_run && exit 0
	if ! [ -e /etc/ssh/ssh_host_dsa_key ]; then
	    /etc/init.d/ssh keygen2
	fi

        echo -n "Starting OpenBSD Secure Shell server: sshd"
	start-stop-daemon --start --quiet --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd
        echo "."
	;;
  stop)
        echo -n "Stopping OpenBSD Secure Shell server: sshd"
	start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd
        echo "."
	;;

  reload|force-reload)
        echo -n "Reloading OpenBSD Secure Shell server's configuration"
	start-stop-daemon --stop --signal 1 --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd
	echo "."
	;;

  restart)
        echo -n "Restarting OpenBSD Secure Shell server: sshd"
	start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd
	sleep 10
	start-stop-daemon --start --quiet --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd
	echo "."
	;;

  keygen1)
	echo "Generating SSH RSA host key (this is slow, please be patient)... "
	/usr/bin/ssh-keygen -f /etc/ssh/ssh_host_key -N '' 
	echo "Done."
	update_sshd_config
	;;

  keygen2)
	echo "Generating SSH DSA host key (this is slow, please be patient)... "
	/usr/bin/ssh-keygen -d -f /etc/ssh/ssh_host_dsa_key -N '' 
	echo "Done."
	update_sshd_config
	;;

  *)
	echo "Usage: /etc/init.d/ssh {start|stop|reload|force-reload|restart|keygen1|keygen2}"
	exit 1
esac

exit 0
