/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <devfs/ops.h>
#include <devfs/types.h>
#include <fs/inode.h>
#include <ramfs.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

int devfs_mknod(const char *const node, const mode_t mode, const dev_t dev,
    const struct drv_event_ops *const ops, struct fs_mp_prv *const pr)
{
    struct devfs_ops *dops = NULL;
    char *const nodedup = strdup(node);

    if (!nodedup
        || !(dops = malloc(sizeof *dops))
        || ramfs_mknod(node, mode, dev, pr->rfs))
        goto failure;

    *dops = (const struct devfs_ops){.node = nodedup, .ops = *ops};

    if (!pr->head)
        pr->head = dops;
    else
    {
        dops->prev = pr->tail;
        pr->tail->next = dops;
    }

    pr->tail = dops;
    return 0;

failure:
    free(dops);
    return -1;
}
