/*
 * 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/routines.h>
#include <iso9660/types.h>
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int iso9660_totm(const struct iso9660_dt *const dt, struct tm *const tm)
{
    char year[sizeof dt->year + 1],
        month[sizeof dt->month + 1],
        day[sizeof dt->day + 1],
        hour[sizeof dt->hour + 1],
        min[sizeof dt->min + 1],
        sec[sizeof dt->sec + 1];

    struct buf
    {
        const char *src;
        char *s;
        int *v;
        size_t n;
    } bufs[] =
    {
        {.src = dt->year, .s = year, .n = sizeof dt->year, .v = &tm->tm_year},
        {.src = dt->month, .s = month, .n = sizeof dt->month, .v = &tm->tm_mon},
        {.src = dt->day, .s = day, .n = sizeof dt->day, .v = &tm->tm_yday},
        {.src = dt->hour, .s = hour, .n = sizeof dt->hour, .v = &tm->tm_hour},
        {.src = dt->min, .s = min, .n = sizeof dt->min, .v = &tm->tm_min},
        {.src = dt->sec, .s = sec, .n = sizeof dt->sec, .v = &tm->tm_sec}
    };

    for (size_t i = 0; i < sizeof bufs / sizeof *bufs; i++)
    {
        struct buf *const b = &bufs[i];
        unsigned long v;
        char *end;

        memcpy(b->s, b->src, b->n - 1);
        b->s[b->n] = '\0';
        errno = 0;
        v = strtoul(b->s, &end, 10);

        if (errno || *end || v > INT_MAX)
            return -1;

        *b->v = v;
    }

    return 0;
}
