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

int iso9660_totimespec(const struct iso9660_dt *const dt,
    struct timespec *const ts)
{
    char hsec[sizeof dt->hsec + 1], *end;
    unsigned long v;
    struct tm tm;
    time_t t;

    if (iso9660_totm(dt, &tm)
        || ((t = mktime(&tm)) == (time_t)-1))
        return -1;

    errno = 0;
    memcpy(hsec, dt->hsec, sizeof dt->hsec);
    hsec[sizeof dt->hsec] = '\0';
    v = strtoul(hsec, &end, 10);

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

    *ts = (const struct timespec)
    {
        .tv_sec = t,
        .tv_nsec = v * 100000ul
    };

    return 0;
}
