#!/bin/sh
# openssh sshd start script
[ $(id -u) = 0 ] || { echo "must be root" ; exit 1; }

start(){

   [ -d /var/lib/sshd ] || mkdir /var/lib/sshd

   [ -f /usr/local/etc/ssh ] || mkdir -p /usr/local/etc/ssh

   [ -f /usr/local/etc/ssh/sshd_config ] || cp /usr/local/etc/ssh/sshd_config.example /usr/local/etc/ssh/sshd_config
   [ -f /usr/local/etc/ssh/ssh_config ] || cp /usr/local/etc/ssh/ssh_config.example /usr/local/etc/ssh/ssh_config

   [ -f /usr/local/etc/ssh/ssh_host_rsa_key ] || ssh-keygen -t rsa -N "" -f /usr/local/etc/ssh/ssh_host_rsa_key
   [ -f /usr/local/etc/ssh/ssh_host_dsa_key ] || ssh-keygen -t dsa -N "" -f /usr/local/etc/ssh/ssh_host_dsa_key
   [ -f /usr/local/etc/ssh/ssh_host_ecdsa_key ] || ssh-keygen -t ecdsa -N "" -f /usr/local/etc/ssh/ssh_host_ecdsa_key
   [ -f /usr/local/etc/ssh/ssh_host_ed25519_key ] || ssh-keygen -t ed25519 -N "" -f /usr/local/etc/ssh/ssh_host_ed25519_key

   /usr/local/sbin/sshd
}

stop(){
   kill $(pidof sshd)
}

restart(){
   if pidof sshd >/dev/null; then
      stop && start
   else
      start
   fi
}

keygen(){
   ssh-keygen -t rsa -N "" -f /usr/local/etc/ssh/ssh_host_rsa_key
   ssh-keygen -t dsa -N "" -f /usr/local/etc/ssh/ssh_host_dsa_key
   ssh-keygen -t ecdsa -N "" -f /usr/local/etc/ssh/ssh_host_ecdsa_key
   ssh-keygen -t ed25519 -N "" -f /usr/local/etc/ssh/ssh_host_ed25519_key
}

status(){
  if [ -f /var/run/sshd.pid ]; then
    echo "OpenSSH daemon is running"
    exit 0
  else
    echo "OpenSSH daemon is not running"
    exit 1
  fi
}

case $1 in
   start) start;;
   stop) stop;;
   restart) restart;;
   keygen) keygen;;
   status) status;;
   *) echo "Usage $0 {start|stop|restart|keygen|status}"; exit 1
esac
