#!/bin/dash
# will be sourced by /sbin/inst_setup
# but can also be called manually: $0 [-n] rootpassword

# vim: syntax=sh

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
  echo "Usage: setup_ssh [OPTIONS] [PASSWORD]"
  echo "Setup and run sshd."
  echo
  echo "If PASSWORD is specified, set root password to PASSWORD."
  echo
  echo "Options:"
  echo "  -n, --no-sshkey           Don't create new set of ssh keys."
  echo "  -h, --help                Write this help text."
  exit 0
fi

nosshkey=false
if [ "$1" = "-n" ] || [ "$1" = "--no-sshkey" ] ; then
  nosshkey=true
  shift
fi

if grep -qwi nosshkey < /proc/cmdline ; then
  nosshkey=true
fi

if test -n "$1" ; then
  sshpassword=$1
fi

if [ "$nosshkey" = "true" ] ; then
  # for inst-sys testing
  echo using built-in ssh keys
  cp -a --remove-destination /lib/ssh/*key* /etc/ssh/
  chmod 644 /etc/ssh/*key.pub
  chmod 600 /etc/ssh/*key
fi

if [ -n "$sshpassword" ] ; then
  echo "setting temporary root password to '$sshpassword'"
  echo "root:$sshpassword" | chpasswd
fi
chown -R 0.0  /etc/ssh /root /etc/shadow 2>/dev/null

ssh-keygen -A

echo -n "Starting SSH daemon... "

export YAST2_SSH=false

/usr/sbin/sshd || {
  export SSH_FAILED=true
  echo failed
}

if [ ! "$SSH_FAILED" ] ; then
  echo ok
  if grep -q "^UseSSH:.*1" /etc/install.inf ; then
    export YAST2_SSH=true
  fi
fi

[ -f /proc/splash ] && echo verbose >/proc/splash
