
/*
 * 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 <ramfs.h>
#include <ramfs/types.h>
#include <fs/inode.h>
#include <sys/types.h>
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

static struct inode *find(const char *const node, struct inode *const root)
{
    for (struct inode *c = root->child; c; c = c->right)
        if (!strcmp(c->name, node))
            return c;

    return NULL;
}

int ramfs_mknod(const char *const node, const mode_t mode, const dev_t dev,
    struct ramfs *const rfs)
{
    struct inode *const r = rfs->root,
        *const inode = find(node, r),
        *newinode = NULL;
    char *nodedup = NULL;
    struct timespec ts;

    if (inode)
    {
        errno = EEXIST;
        goto failure;
    }
    else if (clock_gettime(CLOCK_REALTIME, &ts)
        || !(nodedup = strdup(node))
        || !(newinode = malloc(sizeof *newinode)))
        goto failure;

    *newinode = (const struct inode)
    {
        .atim = ts,
        .ctim = ts,
        .mtim = ts,
        .flags = INODE_BLOCKDEV,
        .mode = mode,
        .parent = rfs->root,
        .name = nodedup
    };

    if (!r->child)
        r->child = newinode;
    else
        for (struct inode *c = r->child; c; c = c->right)
            if (!c->right)
            {
                c->right = newinode;
                newinode->left = c;
                break;
            }

    r->atim = r->mtim = ts;
    return 0;

failure:
    free(nodedup);
    free(newinode);
    return -1;
}
