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

me="[$(printf $0 | xargs basename)]"
# 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() {
  if [ ! -f ${SSH_ENABLED} ]; then
    echo -n "Starting dropbear not allowed!"
    exit
  fi
  echo -n "${me} Starting dropbear sshd: "

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

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

  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 "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)
      start
    ;;
  stop)
    stop
    ;;
  restart|reload)
    restart
    ;;
  start-once)
    if [ ${IS_DROPBEAR_RUNNING} -eq ${DROPBEAR_IS_NOT_RUNNING} ]; then
      enable
      start
      disable
    fi
    ;;
  enable)
    enable
    ;;
  reset-passwd)
    reset_passwd
    ;;
  disable)
    disable
    ;;
  *)
  echo $"${me} Usage: $0 {start|stop|restart|start-once|enable|disable}"
  exit 1
esac

exit $?
