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

static enum state mount(void *const args)
{
    return STATE_OK;
}

struct ramfs *ramfs_mount(const struct fs_mount *const m,
    struct fs_ret *const r)
{
    struct ramfs *ret = NULL;
    struct timespec ts;
    char *const name = strdup("/");
    struct inode *root = NULL;

    if (!name
        || clock_gettime(CLOCK_REALTIME, &ts)
        || !(root = malloc(sizeof *root))
        || !(ret = malloc(sizeof *ret)))
        goto failure;

    *root = (const struct inode)
    {
        .name = name,
        .mode = m->mode,
        .uid = m->uid,
        .gid = m->gid,
        .atim = ts,
        .mtim = ts,
        .ctim = ts
    };

    *ret = (const struct ramfs){.root = root};
    *r = (const struct fs_ret){.f = mount};
    ret->ino++;
    return ret;

failure:
    free(root);
    free(ret);
    free(name);
    return NULL;
}
