#!/bin/sh
#
# $FreeBSD: ports/security/openssh-portable/files/openssh.in,v 1.2 2006/02/21 19:28:37 mnag Exp $
#
# PROVIDE: openssh
# REQUIRE: DAEMON
#
# Add the following lines to /etc/rc.conf to enable openssh:
#
# openssh_enable (bool):	Set it to "YES" to enable openssh.
#				Default is "NO".
# openssh_flags (flags):	Set extra flags to openssh.
#				Default is "". see sshd(1).
# openssh_pidfile (file):	Set full path to pid file.
#				Default is "/var/run/sshd.pid".
#

. /etc/rc.subr

name="openssh"
rcvar=${name}_enable

load_rc_config ${name}

: ${openssh_enable="NO"}
: ${openssh_pidfile="/var/run/sshd.pid"}

command=/usr/local/sbin/sshd
extra_commands="reload keygen"
start_precmd="${name}_checks"
restart_precmd="${name}_checks"
keygen_cmd="${name}_keygen"
pidfile=${openssh_pidfile}

openssh_keygen()
{
	if [ ! -f /usr/local/etc/ssh/ssh_host_key -o \
		! -f /usr/local/etc/ssh/ssh_host_dsa_key -o \
		! -f /usr/local/etc/ssh/ssh_host_rsa_key ]; then

		umask 022

		# Can't do anything if ssh is not installed
		[ -x /usr/local/bin/ssh-keygen ] || {
			err 1 "/usr/local/bin/ssh-keygen does not exist."
		}

		if [ -f /usr/local/etc/ssh/ssh_host_key ]; then
			echo "You already have an RSA host key" \
				"in /usr/local/etc/ssh/ssh_host_key"
			echo "Skipping protocol version 1 RSA Key Generation"
		else
			/usr/local/bin/ssh-keygen -t rsa1 -b 1024 \
				-f /usr/local/etc/ssh/ssh_host_key -N ''
		fi

		if [ -f /usr/local/etc/ssh/ssh_host_dsa_key ]; then
			echo "You already have a DSA host key" \
				"in /usr/local/etc/ssh/ssh_host_dsa_key"
			echo "Skipping protocol version 2 DSA Key Generation"
		else
			/usr/local/bin/ssh-keygen -t dsa \
				-f /usr/local/etc/ssh/ssh_host_dsa_key -N ''
		fi

		if [ -f /usr/local/etc/ssh/ssh_host_rsa_key ]; then
			echo "You already have a RSA host key" \
				"in /usr/local/etc/ssh/ssh_host_rsa_key"
			echo "Skipping protocol version 2 RSA Key Generation"
		else
			/usr/local/bin/ssh-keygen -t rsa \
				-f /usr/local/etc/ssh/ssh_host_rsa_key -N ''
		fi

	fi
}

openssh_checks()
{
	if checkyesno sshd_enable ; then
		err 1 "sshd_enable is set. Please set sshd_enable to NO in your rc.conf"
	fi

	run_rc_command keygen
	eval "${command} -t"
}

run_rc_command "$1"
