#!/bin/bash
#
# Initialize ssh server for remote connections (option `--server ssh`)

if [ -z "${virtme_ssh_user}" ]; then
    echo "ssh: virtme_ssh_user is not defined" >&2
    exit 1
fi

mkdir -p /run/sshd
rm -f /var/run/nologin

SSH_HOME=$(getent passwd "${virtme_ssh_user}" | cut -d: -f6)
if [ ! -e "${SSH_HOME}" ]; then
    # Setup an arbitrary ssh location, just to be able to start sshd.
    SSH_HOME=/run/sshd
fi

# Generate authorized_keys in the virtme-ng cache directory and add all
# user's public keys.
CACHE_DIR=${SSH_HOME}/.cache/virtme-ng/.ssh
SSH_AUTH_KEYS="${CACHE_DIR}/authorized_keys"
cat "${SSH_HOME}"/.ssh/id_*.pub >> "${SSH_AUTH_KEYS}" 2>/dev/null
chown "${virtme_ssh_user}" "${SSH_AUTH_KEYS}" 2>/dev/null
chmod 600 "${SSH_AUTH_KEYS}" 2>/dev/null

# Generate ssh host keys (if they don't exist already).
mkdir -p "${CACHE_DIR}/etc/ssh"
ssh-keygen -A -f "${CACHE_DIR}"

# Generate a minimal sshd config.
SSH_CONFIG=/run/sshd/sshd_config
cat << EOF > "${SSH_CONFIG}"
# This file is automatically generated by virtme-ng.
Port 22
PermitRootLogin yes
AuthorizedKeysFile ${SSH_AUTH_KEYS}
PubkeyAuthentication yes
UsePAM yes
PrintMotd no
EOF

# Start sshd.
ARGS=(-f "${SSH_CONFIG}")
for key in "${CACHE_DIR}"/etc/ssh/ssh_host_*_key; do
    ARGS+=(-h "${key}")
done

/usr/sbin/sshd -f "${SSH_CONFIG}" "${ARGS[@]}"
