/*
 * 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 <iso9660.h>
#include <iso9660/ops.h>
#include <iso9660/routines.h>
#include <iso9660/types.h>
#include <fs/fs.h>
#include <fs/inode.h>
#include <errno.h>
#include <stdlib.h>

struct open
{
    struct inode inode;
    struct fs_fd *fd;
    struct fs_ret *pr, r;
    struct fs_mp mp;
    struct fs_stdstreams ss;
};

static int search_done(const enum state state, const char *const relpath,
    const struct fs_mp *const mp, const union inode_result *const inode,
    void *const args)
{
    int ret = 0;
    struct open *const op = args;
    const struct inode *const mpinode = &op->inode;
    struct fs_fd *const fd = op->fd;

    if (mpinode->flags & INODE_DIR)
    {
        fd->error = EISDIR;
        ret = -1;
    }
    else if (state)
    {
        fd->error = ENODEV;
        ret = -1;
    }
    else
    {
        *fd = (const struct fs_fd)
        {
            .start = mpinode->prv->offset,
            .size = mpinode->size,
            .tgt_mp = &op->mp,
            .inode = *inode,
            .mp = *mp
        };

        *op->pr = op->r;
    }

    free(op);
    return ret;
}

int iso9660_open(const struct fs_open *const o, const struct fs_mp *const mp,
    const union inode_result *const inode, struct fs_ret *const r)
{
    const struct inode *const i = &inode->cachei;
    struct open *const op = malloc(sizeof *op);

    if (!op)
        return -1;

    const struct inode_search s =
    {
        .args = op,
        .path = mp->src,
        .done = search_done
    };

    *op = (const struct open)
    {
        .fd = o->fd,
        .inode = *i,
        .mp = *mp,
        .pr = r,
        .r = *r,
        .ss = o->ss
    };

    if (inode_search(&s, r))
        goto failure;

    return 0;

failure:
    free(op);
    return -1;
}
