#!/system/bin/sh

umask 077

# DEBUG=1

ECDSA_KEY=/data/ssh/ssh_host_ecdsa_key
ECDSA_PUB_KEY=/data/ssh/ssh_host_ecdsa_key.pub
RSA_KEY=/data/ssh/ssh_host_rsa_key
RSA_PUB_KEY=/data/ssh/ssh_host_rsa_key.pub
ED25519_KEY=/data/ssh/ssh_host_ed25519_key
ED25519_PUB_KEY=/data/ssh/ssh_host_ed25519_key.pub
AUTHORIZED_KEYS=/data/ssh/authorized_keys
DEFAULT_AUTHORIZED_KEYS=/product/etc/security/authorized_keys.default

if [ ! -f $ECDSA_KEY ]; then
    /product/bin/ssh-keygen -t ecdsa -f $ECDSA_KEY -N ""
    chmod 600 /$ECDSA_KEY
    chmod 644 $ECDSA_PUB_KEY
fi

if [ ! -f $RSA_KEY ]; then
    /product/bin/ssh-keygen -t rsa -f $RSA_KEY -N ""
    chmod 600 /$RSA_KEY
    chmod 644 $RSA_PUB_KEY
fi

if [ ! -f $ED25519_KEY ]; then
    /product/bin/ssh-keygen -t ed25519 -f $ED25519_KEY -N ""
    chmod 600 /$ED25519_KEY
    chmod 644 $ED25519_PUB_KEY
fi

if [[ ! -f $AUTHORIZED_KEYS && -f $DEFAULT_AUTHORIZED_KEYS ]]; then
    cat $DEFAULT_AUTHORIZED_KEYS > $AUTHORIZED_KEYS
fi


if [ "1" == "$DEBUG" ] ; then
    # run sshd in debug mode and capture output to logcat
    /system/bin/logwrapper /product/bin/sshd -f /product/etc/ssh/sshd_config -D -d
else
    # don't daemonize - otherwise we can't stop the sshd service
    /product/bin/sshd -f /product/etc/ssh/sshd_config -D
fi
