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

struct write
{
    bool done;
    struct fs_fd *fd;
    struct fs_ret *pr, r;
};

static int done(const int error, void *const args)
{
    struct write *const w = args;

    w->done = true;
    return 0;
}

static enum state wait(void *const args)
{
    struct write *const w = args;

    if (!w->done)
        return STATE_AGAIN;

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

int devfs_write(const struct fs_write *const fw, struct fs_ret *const r)
{
    struct fs_fd *const fd = fw->fd;
    const struct fs_mp *const mp = &fd->mp;
    const struct inode *const inode = fd->inode.memi;
    const struct devfs_ops *const o = devfs_ops(mp->prv, inode->name);
    struct write *const w = malloc(sizeof *w);

    if (!w)
        goto failure;
    else if (!o)
    {
        errno = ENOENT;
        goto failure;
    }

    *w = (const struct write)
    {
        .fd = fd,
        .pr = r,
        .r = *r
    };

    const struct drv_event_done d =
    {
        .f = done,
        .args = w
    };

    const struct drv_event_ops *const ops = &o->ops;

    if (ops->write(ops->p, fw->buf, fw->n, &d))
        goto failure;

    *r = (const struct fs_ret){.f = wait, .args = w};
    return 0;

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