#!/bin/sh
#
# Starts dropbear sshd.
#

me="[S50dropbear]"
# Make sure the dropbearkey progam exists
[ -f /usr/bin/dropbearkey ] || exit 0

DSS_FILE="/opt/userdata/dropbear_dss_host_key"
RSA_FILE="/opt/userdata/dropbear_rsa_host_key"

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
pidof dropbear > /dev/null
IS_DROPBEAR_RUNNING=$?

start() {
  echo -n "$me Starting dropbear sshd: "

  # Check for the Dropbear RSA key
  if [ ! -f $RSA_FILE ]
  then
    echo -n "generating rsa key... "
    /usr/bin/dropbearkey -t rsa -f $RSA_FILE > /dev/null 2>&1
  fi

  # Check for the Dropbear DSS key
  if [ ! -f $DSS_FILE ]
  then
    echo -n "generating dsa key... "
    /usr/bin/dropbearkey -t dss -f $DSS_FILE > /dev/null 2>&1
  fi

  # now start the daemon
  umask 077
  start-stop-daemon -S -q -p /var/run/dropbear.pid --exec /usr/sbin/dropbear -- -d $DSS_FILE -r $RSA_FILE
  echo "OK"
}

stop() {
  echo -n "$me Stopping dropbear sshd: "
  start-stop-daemon -K -q -p /var/run/dropbear.pid
  killall dropbear
  echo "$me OK"
}

restart() {
  stop
  start
}

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

enable() {
  touch ${SSH_ENABLED}
}

# Sets root password to 'root'
reset_passwd() {
  install -m 600 /opt/gira/etc/devicestack/shadow.template.root /var/etc/shadow
}

case "$1" in
  start)
    if [ -f ${SSH_ENABLED} ]
    then
      start
    fi
    ;;
  stop)
    stop
    ;;
  restart|reload)
    restart
    ;;
  start-once)
	if [ ${IS_DROPBEAR_RUNNING} -eq ${DROPBEAR_IS_NOT_RUNNING} ]
	then
		start
	fi
    ;;
  enable)
    enable
    ;;
  reset-passwd)
    reset_passwd
    ;;
  disable)
    disable
    ;;
  *)
    echo $"$me Usage: $0 {start|stop|restart|start-once|enable|disable}"
    exit 1
esac

exit $?
