# this is a developer helper script to install the public ssh key in the created image

DROPBEAR_AUTHORIZED_KEYS_FILE=/etc/dropbear/authorized_keys

function get_ssh_public_keys {
    (
        shopt -s nullglob
        # home directory, not all of those are supported by dropbear,
        # but let's include them now already to decrease future maintenance
        cat /dev/null ~/.ssh/{id_rsa,id_dsa,id_ecdsa,id_ecdsa_sk,id_ed25519,id_ed25519_sk,id_xmss}.pub 2> /dev/null
        # keys added manually or automatically to the build dir
        cat "files${DROPBEAR_AUTHORIZED_KEYS_FILE}" 2>/dev/null
        # keys in the agent (useful when using SSH agent forwarding)
        ssh-add -L 2> /dev/null
    ) | sort | uniq
}

function install_key {
    local build_dir_dropbear_authorized_keys_file="files${DROPBEAR_AUTHORIZED_KEYS_FILE}"
    mkdir -p "$(dirname "$build_dir_dropbear_authorized_keys_file")"
    get_ssh_public_keys > "$build_dir_dropbear_authorized_keys_file"
    chmod 0644 "$build_dir_dropbear_authorized_keys_file"
    echo "Keys in "$build_dir_dropbear_authorized_keys_file" are now:"
    cat "$build_dir_dropbear_authorized_keys_file"
    echo
    echo "Disabling login on serial console..."
    echo "::sysinit:/etc/init.d/rcS S boot" >files/etc/inittab
    echo "::shutdown:/etc/init.d/rcS K shutdown" >>files/etc/inittab
    echo "console::askconsolelate:/bin/cttyhack /bin/ash --login" >>files/etc/inittab

    echo Done
}

function ssh_install_key_help() {
    echo Usage: $0 ssh_install_key HOSTNAME
    echo
    echo "Installs SSH public keys to a device's authorized_keys file"
}


# this is a developer helper script to install the public ssh key on host running dropbear
function ssh_install_key {
    if [ $# -ne 1 ] || [ "$1" == '--help' ]; then
        ssh_install_key_help
        [ $# -eq 1 ]; return
    fi
    host="$1"
    local keys="$(get_ssh_public_keys)"
    echo "Adding the following keys to $DROPBEAR_AUTHORIZED_KEYS_FILE on $host:"
    echo "$keys"
    ssh \
        -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
        root@$host \
        "echo '$keys' >> '$DROPBEAR_AUTHORIZED_KEYS_FILE'" && echo ok
}

register_command "ssh_install_key" "Install the users public ssh key on host running dropbear"
register_command "install_key" "Install the user's public ssh key in the created image"
