/*
 * 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 <drv/drv.h>
#include <drv/types.h>
#include <drv/tree.h>
#include <drv/port.h>
#include <stddef.h>
#include <stdlib.h>

struct drv *drv_init(const struct drv_event *const ev)
{
    size_t init = 0;
    struct drv *const ret = malloc(sizeof *ret);
    struct drv_port **const ports = malloc(drv_tree_n * sizeof *ports);

    if (!ports || !ret)
        goto failure;

    for (size_t i = 0; i < drv_tree_n; i++, init++)
    {
        struct drv_port *const p = drv_tree_init[i](ev);

        if (!p)
            goto failure;

        ports[i] = p;
    }

    *ret = (const struct drv)
    {
        .ports = ports,
        .n = drv_tree_n
    };

    return ret;

failure:

    if (ports)
        for (size_t i = 0; i < init; i++)
            drv_tree_free[i](ports[i]);

    free(ports);
    free(ret);
    return NULL;
}
