/*
 * 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 <caio.h>
#include <caio/types.h>
#include <aio.h>
#include <loop.h>
#include <fs/fs.h>
#include <stdlib.h>

static int done(const enum state state, void *const args)
{
    struct caio *const a = args;
    const struct aio_done *const d = &a->done;

    if (loop_rm_aio(a->aio))
        return -1;

    aio_free(a->aio);
    a->aio = NULL;
    return d->f ? d->f(state, d->args) : 0;
}

struct caio *caio_open(const struct caio_open *op,
    const struct aio_done *const d)
{
    struct aio *aio = NULL;
    struct caio *const ret = malloc(sizeof *ret);

    if (!ret)
        goto failure;

    const struct fs_open aio_op =
    {
        .flags = op->flags,
        .path = op->path,
        .uid = op->uid,
        .gid = op->gid,
        .fd = &ret->fd,
    };

    const struct aio_done dd =
    {
        .f = done,
        .args = ret
    };

    *ret = (const struct caio){0};

    if (caio_set_caches(ret, 1)
        || !(aio = aio_open(&aio_op, &dd))
        || loop_add_aio(aio))
        goto failure;
    else if (d)
        ret->done = *d;

    ret->aio = aio;
    return ret;

failure:
    aio_free(aio);
    free(ret);
    return NULL;
}
