/**
 * Callback function that appends an SSH key tot the list of keys authorised for
 * access to the initrd.
 *
 * Example output:
 * {"ssh-keys":{"1":"ssh-rsa AAAAB3... example@example.com",
 * "2":"ssh-rsa AAAAB3...","5":"command=\"/usr/bin/cryptops-client\" ssh-rsa
 *  AAAAB3... cryptops-test@greenhost"}}
 *
 * The indices correspond to line numbers of the authorized_keys file.
 * Missing indices (like 3 and 4 in the example) arise from empty lines in the
 * file; those are creted when keys are deleted.
 *
 * @param[in]   request   incoming HTTP request
 * @param[out]  response  HTTP response to the request
 * @param[in]   user_data extra data to pass between main thread and callbacks
 * @return                internal status code
 */
int callback_ssh_keys_post(const struct _u_request * request,
    struct _u_response * response, void * user_data)
{
    // Open file with append mode
    FILE * authorized_keys = fopen(AUTHORIZED_KEYS_PATH, "a");

    // Check if that succeeded.
    if (authorized_keys == NULL)
    {
        y_log_message(Y_LOG_LEVEL_ERROR,
            "Could not open authorized_keys file for writing");
        return send_simple_response(response, 500, "error",
            "error opening authorized_keys");
    }

    // Read in json request body.
    json_t * json_input = ulfius_get_json_body_request(request, NULL);

    // Read SSH key from request.
    const char * ssh_key;
    ssh_key = json_string_value(json_object_get(json_input, "ssh-key"));
    if (ssh_key == NULL)
    {
        return send_simple_response(response, 400, "error", "missing ssh-key");
    }

    // add cryptops-client command to ssh-key
    char * ssh_key_with_command;
    add_ssh_command(&ssh_key_with_command, ssh_key);

    // Write SSH key to file
    asprintf(&ssh_key_with_command, "%s\n", ssh_key_with_command);
    fprintf(authorized_keys, ssh_key_with_command);
    fclose(authorized_keys);

    return send_simple_response(response, 200, "status", "ok");
}