#!/bin/sh /etc/rc.common
# Copyright (C) 2006 OpenWrt.org
START=50
# Copyright (C) 2006 Carlos Sobrinho

config_cb() {
	local cfg="$CONFIG_SECTION"
	local nopasswd
	local cfgt
	config_get cfgt "$cfg" TYPE

	case "$cfgt" in
		dropbear)
			config_get passauth $cfg PasswordAuth
			config_get port $cfg Port

			case "$passauth" in
				no|off|disabled|0) nopasswd=1;;
			esac
			DROPBEAR_ARGS="${nopasswd:+-s }${port:+-p $port}"
		;;
	esac
}

keygen() {
	for keytype in rsa dss; do
		# check for keys
		key=dropbear/dropbear_${keytype}_host_key
		[ -f /tmp/$key -o -s /etc/$key ] || {
			# generate missing keys
			mkdir -p /tmp/dropbear
			[ -x /usr/bin/dropbearkey ] && {
				/usr/bin/dropbearkey -t $keytype -f /tmp/$key 2>&- >&- && exec /etc/rc.common "$initscript" start
			} &
		exit 0
		}
	done

	lock /tmp/.switch2jffs
	mkdir -p /etc/dropbear
	mv /tmp/dropbear/dropbear_* /etc/dropbear/
	lock -u /tmp/.switch2jffs
	chown root /etc/dropbear
	chmod 0700 /etc/dropbear
}

start() {
	[ -s /etc/dropbear/dropbear_rsa_host_key -a \
	  -s /etc/dropbear/dropbear_dss_host_key ] || keygen
	
	config_load dropbear
	/usr/sbin/dropbear $DROPBEAR_ARGS
}

stop() {
	killall dropbear
}
