/*
 * 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 <aio.h>
#include <aio/types.h>
#include <fs/fs.h>
#include <fs/inode.h>
#include <sys/types.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

struct stat_prv
{
    struct fs_stat stat;
    struct aio_done done;
    struct aio *aio;
};

static int done(const enum state state, void *const args)
{
    int ret = 0;
    struct stat_prv *const p = args;
    const struct aio_done *const d = &p->done;

    if (d->f)
        ret = d->f(state, d->args);

    free(p);
    return ret;
}

static int search_done(const enum state s, const char *const relpath,
    const struct fs_mp *const mp, const union inode_result *const inode,
    void *const args)
{
    struct stat_prv *const p = args;
    struct aio *const aio = p->aio;
    const struct fs *const fs = mp->fs;

    if (!inode)
    {
        aio->error = ENOENT;
        goto failure;
    }
    else if (fs->stat(&p->stat, mp, inode, &aio->r))
    {
        aio->error = errno;
        goto failure;
    }

    return 0;

failure:
    aio->done = p->done;
    free(p);
    return -1;
}

struct aio *aio_stat(const struct fs_stat *const as,
    const struct aio_done *const d)
{
    struct aio *const aio = malloc(sizeof *aio);
    struct stat_prv *const p = malloc(sizeof *p);

    if (!p || !aio)
        goto failure;

    const struct inode_search s =
    {
        .path = as->path,
        .done = search_done,
        .args = p
    };

    *p = (const struct stat_prv)
    {
        .aio = aio,
        .stat = *as
    };

    *aio = (const struct aio)
    {
        .done =
        {
            .f = done,
            .args = p
        }
    };

    if (inode_search(&s, &aio->r))
        goto failure;
    else if (d)
        p->done = *d;

    return aio;

failure:
    free(p);
    free(aio);
    return NULL;
}
