/*
 * 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 <drv/drv.h>
#include <fs/fs.h>
#include <ramfs.h>
#include <stdlib.h>

int devfs_mount(const struct fs_mount *const m, struct fs_ret *const r)
{
    struct drv *drv = NULL;
    struct fs_mp_prv *p = NULL;
    struct ramfs *const rfs = ramfs_mount(m, r);

    if (!rfs || !(p = malloc(sizeof *p)))
        goto failure;

    const struct drv_event ev =
    {
        .status = devfs_status,
        .args = p
    };

    if (!(drv = drv_init(&ev))
        || fs_mountpoint(m->src, m->tgt, &devfs, devfs_update, p))
        goto failure;

    *p = (const struct fs_mp_prv)
    {
        .drv = drv,
        .rfs = rfs
    };

    return 0;

failure:
    drv_free(drv);
    free(p);
    ramfs_free(rfs);
    return -1;
}
