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

int fs_mountpoint(const char *const src, const char *const tgt,
    const struct fs *const fs, const fs_update_fn fn,
    struct fs_mp_prv *const pr)
{
    struct fs_mountpoint *m = NULL;
    char *srcdup = NULL, *const tgtdup = strdup(tgt);

    if (!tgtdup)
        goto failure;
    else if (src && !(srcdup = strdup(src)))
        goto failure;
    else if (!(m = malloc(sizeof *m)))
        goto failure;

    *m = (const struct fs_mountpoint)
    {
        .src = srcdup,
        .tgt = tgtdup,
        .update = fn,
        .fs = fs,
        .prv = pr
    };

    if (!fs_mphead)
        fs_mphead = m;
    else if (fs_mptail)
        fs_mptail->next = m;

    fs_mptail = m;
    return 0;

failure:
    free(srcdup);
    free(tgtdup);
    free(m);
    return -1;
}
