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

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

int ramfs_mkdir(const struct fs_mkdir *const m, struct ramfs *const rfs,
    const union inode_result *const inode, struct fs_ret *const r)
{
    struct timespec ts;
    struct inode *ni = NULL;
    struct inode *const parent = inode->memi;
    char *const name = strdup(m->path);

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

    *ni = (const struct inode)
    {
        .name = name,
        .mode = m->mode,
        .uid = m->uid,
        .gid = m->gid,
        .flags = INODE_DIR,
        .atim = ts,
        .ctim = ts,
        .mtim = ts,
        .ino = rfs->ino++,
        .parent = parent
    };

    if (!parent->child)
        parent->child = ni;
    else
        for (struct inode *i = parent->child; i; i = i->right)
            if (!i->right)
            {
                i->right = ni;
                ni->left = i;
                break;
            }

    parent->atim = parent->mtim = ts;
    *r = (const struct fs_ret){.f = done};
    return 0;

failure:
    free(ni);
    free(name);
    return -1;
}
