/*
 * 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 <bin.h>
#include <bin/routines.h>
#include <bin/types.h>
#include <stdlib.h>

static void add_proc(struct bin_proc *const pr)
{
    struct bin *const p = &bin_pending, *const a = &bin_active;

    if (p->proc_head == pr)
        p->proc_head = pr->next;

    if (p->proc_tail == pr)
        p->proc_tail = pr->prev;

    if (pr->next)
        pr->next->prev = pr->prev;

    if (pr->prev)
        pr->prev->next = pr->next;

    if (!a->proc_head)
        a->proc_head = pr;
    else
    {
        struct bin_proc *const t = a->proc_tail;

        t->next = pr;
        pr->prev = t;
        pr->next = NULL;
    }

    a->proc_tail = pr;
}

static void move_mod(struct bin_mod *const m)
{
    struct bin *const p = &bin_pending, *const a = &bin_active;

    if (p->mod_head == m)
        p->mod_head = m->next;

    if (p->mod_tail == m)
        p->mod_tail = m->prev;

    if (m->next)
        m->next->prev = m->prev;

    if (m->prev)
        m->prev->next = m->next;

    if (!a->mod_head)
        a->mod_head = m;
    else
    {
        struct bin_mod *const t = a->mod_tail;

        t->next = m;
        m->prev = t;
        m->next = NULL;
    }

    a->mod_tail = m;
}

static int setup_mems(struct bin_proc *const p)
{
    const struct nw_mod_out *const mout = &p->mod->mod_out;
    const size_t n = mout->global;
    void *const gl = malloc(n);

    if (!gl)
        return -1;

    p->global = (const struct bin_global)
    {
        .buf = gl,
        .sz = n
    };

    return 0;
}

int bin_start(struct bin_mod *const m)
{
    int ret = -1;
    struct bin *const b = &bin_pending;

    for (struct bin_proc *p = b->proc_head; p;)
    {
        struct bin_proc *const next = p->next;

        if (p->mod == m)
        {
            if (setup_mems(p))
                return -1;

            add_proc(p);
            ret = 0;
        }

        p = next;
    }

    if (!ret)
        move_mod(m);

    return ret;
}
