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

# Ensure required binaries exist
[ -x /usr/bin/ssh-keygen ] || exit 0
[ -x /usr/sbin/sshd ] || exit 1

PIDFILE="/var/run/sshd.pid"

umask 077

startssh() {
    # Generate SSH keys if they do not exist
    [ ! -f /etc/ssh/ssh_host_rsa_key ] && /usr/bin/ssh-keygen -A

        printf "Starting sshd: "
        /usr/sbin/sshd
        touch /var/lock/sshd
        echo "OK"
}

start() {
    if [ -e /etc/kvm/ssh_stop ]; then
        if [ -e /boot/start_ssh_once ]; then
            rm -f /boot/start_ssh_once
            startssh
        else
            echo "SSH does not start"
            exit 0
        fi
    else
        startssh
    fi
}

stop() {
        printf "Stopping sshd: "
        killall sshd 2>/dev/null
        rm -f /var/lock/sshd
        echo "OK"
}

restart() {
        stop
        start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|reload)
        restart
        ;;
    permanent_on)
        rm -f /etc/kvm/ssh_stop
        start
        ;;
    permanent_off)
        touch /etc/kvm/ssh_stop
        stop
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|permanent_on|permanent_off}"
        exit 1
esac

exit 0