#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/dropbear
NAME=dropbear

DROPBEAR_PORT=22
DROPBEAR_EXTRA_ARGS=

. /usr/lib/init/dropbear.sh

# test ! -h /var/service/dropbear || exit 0

test -z "$DROPBEAR_BANNER" || \
  DROPBEAR_EXTRA_ARGS="$DROPBEAR_EXTRA_ARGS -b $DROPBEAR_BANNER"

dropbear_start() {
    KEY_ARGS=""
    for keytype in $DROPBEAR_KEYTYPES
    do
        case "$keytype" in
            rsa)
                test -f "$DROPBEAR_RSAKEY" && KEY_ARGS="$KEY_ARGS -r $DROPBEAR_RSAKEY"
                ;;
            ecdsa)
                test -f "$DROPBEAR_ECDSAKEY" && KEY_ARGS="$KEY_ARGS -r $DROPBEAR_ECDSAKEY"
                ;;
            ed25519)
                test -f "$DROPBEAR_ED25519KEY" && KEY_ARGS="$KEY_ARGS -r $DROPBEAR_ED25519KEY"
                ;;
            *)
                echo "Key type '$keytype' not supported"
                ;;
        esac
    done

    echo -n "starting dropbear..."

    start-stop-daemon -S -x "$DAEMON" --oknodo -- \
        $KEY_ARGS -p "$DROPBEAR_PORT" $DROPBEAR_EXTRA_ARGS > /dev/null 2>&1

    if [ "$?" = "0" ]; then
        echo "done"
    else
        echo "failed"
        exit 1
    fi
}

dropbear_stop() {

    echo -n "stopping dropbear..."

    start-stop-daemon -K -x "$DAEMON" --oknodo > /dev/null 2>&1

    if [ "$?" = "0" ]; then
        echo "done"
    else
        echo "failed"
        exit 1
    fi
}


case "$1" in
start)
    dropbear_start;;
stop)
    dropbear_stop;;
restart|force-reload)
    dropbear_stop
    dropbear_start
    ;;
*)
    N=/etc/init.d/$NAME
    echo "usage: $N {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0

