#!/bin/sh
### BEGIN INIT INFO
# Provides:		sshd
# Required-Start:	$remote_fs $syslog $networking
# Required-Stop:	$remote_fs $syslog
# Default-Start:	2 3 4 5
# Default-Stop:		1
# Short-Description:	Dropbear Secure Shell server
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/dropbear
NAME=dropbear
DESC="Dropbear SSH server"
PIDFILE=/var/run/dropbear.pid

DROPBEAR_PORT=22
DROPBEAR_EXTRA_ARGS=
NO_START=0

set -e

test ! -r /etc/default/dropbear || . /etc/default/dropbear
test "$NO_START" = "0" || exit 0
test -x "$DAEMON" || exit 0
test ! -h /var/service/dropbear || exit 0

DROPBEAR_RSAKEY_DEFAULT="/opt/userdata/dropbear_rsa_host_key"
DROPBEAR_DSSKEY_DEFAULT="/opt/userdata/dropbear_dss_host_key"

test -z "$DROPBEAR_BANNER" || \
  DROPBEAR_EXTRA_ARGS="$DROPBEAR_EXTRA_ARGS -b $DROPBEAR_BANNER"
test -n "$DROPBEAR_RSAKEY" || \
  DROPBEAR_RSAKEY=$DROPBEAR_RSAKEY_DEFAULT
test -n "$DROPBEAR_DSSKEY" || \
  DROPBEAR_DSSKEY=$DROPBEAR_DSSKEY_DEFAULT
test -n "$DROPBEAR_KEYTYPES" || \
  DROPBEAR_KEYTYPES="rsa dsa"

gen_keys() { 
  for t in $DROPBEAR_KEYTYPES; do
    case $t in
      rsa)
          if [ -f "$DROPBEAR_RSAKEY" -a ! -s "$DROPBEAR_RSAKEY" ]; then
                  rm $DROPBEAR_RSAKEY || true
          fi
          test -f $DROPBEAR_RSAKEY || dropbearkey -t rsa -f $DROPBEAR_RSAKEY
    ;;
      dsa)
          if [ -f "$DROPBEAR_DSSKEY" -a ! -s "$DROPBEAR_DSSKEY" ]; then
                  rm $DROPBEAR_DSSKEY || true
          fi
          test -f $DROPBEAR_DSSKEY || dropbearkey -t dss -f $DROPBEAR_DSSKEY
    ;;
    esac
  done
}

SSH_ENABLED="/opt/userdata/.ssh-enabled"
# pidof returns 1 (one) in case dropbear is NOT running
# and 0 (zero) in case it is.
DROPBEAR_IS_NOT_RUNNING=1

start_once() {
    set +e
    pidof dropbear > /dev/null
    if [ $? -eq ${DROPBEAR_IS_NOT_RUNNING} ]
    then
      printf "Starting %s: " "$DESC"
      gen_keys
      KEY_ARGS=""
      test -f $DROPBEAR_DSSKEY && KEY_ARGS="$KEY_ARGS -d $DROPBEAR_DSSKEY"
      test -f $DROPBEAR_RSAKEY && KEY_ARGS="$KEY_ARGS -r $DROPBEAR_RSAKEY"
      start-stop-daemon -S -p $PIDFILE \
        -x "$DAEMON" -- $KEY_ARGS \
          -p "$DROPBEAR_PORT" $DROPBEAR_EXTRA_ARGS
      printf "%s.\\n" "$NAME"
    fi
    set -e
}

start(){
  if [ -f ${SSH_ENABLED} ]; then  
    start_once
  fi
}

stop(){
    printf "Stopping %s: " "$DESC"
    start-stop-daemon -K -x "$DAEMON" -p $PIDFILE
    printf "%s.\\n" "$NAME"
}

restart(){
	stop
  sleep 1
	start
}

disable() {
	rm -f ${SSH_ENABLED}
}
enable() {
	touch ${SSH_ENABLED}
}

case "$1" in
  start)
    start
  ;;
  start-once)
    start_once
  ;;
  stop)
    stop
  ;;
  restart|force-reload)
    restart
  ;;
  enable)
    enable
  ;;
  disable)
    disable
  ;;
  *)
    N=/etc/init.d/$NAME
    printf "Usage: %s {start|stop|restart|force-reload}\\n" "$N" >&2
    exit 1
  ;;
esac

exit 0
