#!/bin/sh

generate_missing_keys () {
    for key_type in dsa rsa ecdsa ed25519
    do
        # key is missing or has zero length
        if [ ! -s "/etc/ssh/ssh_host_${key_type}_key" ]
        then
            rm -f "/etc/ssh/ssh_host_${key_type}_key"
            rm -f "/etc/ssh/ssh_host_${key_type}_key.pub"
            echo "Generating ${key_type} keypair for the ssh server: "
            ssh-keygen -q -t ${key_type} -f "/etc/ssh/ssh_host_${key_type}_key"  -C '' -N ''
        fi
        chmod 600 "/etc/ssh/ssh_host_${key_type}_key"
        chmod 644 "/etc/ssh/ssh_host_${key_type}_key.pub"
    done
}

delete_all_keys () {
    echo "Deleting all keys"
    for key_type in dsa rsa ecdsa ed25519
    do
        rm -f "/etc/ssh/ssh_host_${key_type}_key"
        rm -f "/etc/ssh/ssh_host_${key_type}_key.pub"
    done
}

if [ ! -x /usr/sbin/sshd ]
then
    exit 0
fi

if [ "$1" = "stop" -o "$1" = "restart" ]
then
    echo "Stopping the ssh server: "
    pkill sshd
fi

if [ "$1" = "start" -o "$1" = "restart" ]
then
    # start ssh only when the terminal in development mod
    if [ "`cat /sys/kernel/secure/state`" == "2" ]; then
        first_attempt=true
        while true; do
            generate_missing_keys
            echo "Starting the ssh server: "
            /usr/sbin/sshd
            if pgrep -x "/usr/sbin/sshd" > /dev/null
                then
                    break
                else
                    if [ "$first_attempt" = "true" ]
                        then
                            delete_all_keys
                            first_attempt=false
                        else
                            break
                    fi
            fi
        done
    fi
fi

