/*
 * 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.h>
#include <devfs/types.h>
#include <devfs/ops.h>
#include <fs/fs.h>
#include <state.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

struct open
{
    struct fs_ret *pr, r;
};

static enum state done(void *const args)
{
    struct open *const op = args;

    *op->pr = op->r;
    free(op);
    return STATE_AGAIN;
}

int devfs_open(const struct fs_open *const o, const struct fs_mp *const mp,
    const union inode_result *const inode, struct fs_ret *const r)
{
    struct open *const op = malloc(sizeof *op);

    if (!op)
        return -1;
    else
    {
        const struct fs_stdstreams *const ss = &o->ss;
        const char *const name = inode->memi->name;
        struct fs_fd *const fd = o->fd;

        if (!strcmp(name, "stderr"))
            *fd = ss->streams[STDERR_FILENO];
        else if (!strcmp(name, "stdin"))
            *fd = ss->streams[STDIN_FILENO];
        else if (!strcmp(name, "stdout"))
            *fd = ss->streams[STDOUT_FILENO];
        else
            *fd = (const struct fs_fd)
            {
                .inode = *inode,
                .mp = *mp
            };
    }

    *op = (const struct open){.pr = r, .r = *r};
    *r = (const struct fs_ret){.f = done, .args = op};
    return 0;
}
