#!/bin/sh

. /etc/init.d/globals

ETCDIR=/etc/dropbear

genkeys() {
	for keytype in dss rsa ecdsa ed25519; do
		keyfile=$ETCDIR/dropbear_${keytype}_host_key
		test -e $keyfile && continue
		/usr/bin/dropbearkey -t $keytype -f $keyfile
	done
}

fixperms() {
	# /root must be owned by root and must not world writable.
	# fresh from the buildsystem it belongs to the building user...
	test -L /root -o ! -d /root && return # not a directory
	chown 0:0 /root
	chmod go-w /root
}

case $1 in
	start)
		if [ -e /var/etc/.dropbear ]; then
			genkeys
			fixperms
			/usr/sbin/dropbear
		fi
	;;
	stop)
		if [ -e /var/etc/.dropbear ]; then
			pid=$(cat /var/run/dropbear.pid 2>/dev/null)
			test -n "$pid" && kill $pid || true
		fi
	;;
	*)
		echo "[${BASENAME}] Usage: $0 {start|stop}"
	;;
esac
