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

me="[$(printf $0 | xargs basename)]"

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 "${me} Starting dropbear not allowed!"
    exit
  fi
  
  echo "${me} Starting dropbear sshd..."
  start-stop-daemon -S -q -p /var/run/dropbear.pid --exec /usr/sbin/dropbear -- -R
}
stop() {
  echo "${me} Stopping dropbear sshd..."
  start-stop-daemon -K -q -p /var/run/dropbear.pid
  killall dropbear
}
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 $?
