/* Copyright (C) 2022-2024  Philipp "ph3-der-loewe" Schafft <lion@lion.leolix.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>

#include <igloo/uuid.h>
#include <igloo/sp.h>
#include <igloo/error.h>
#include <igloo/prng.h>

#define UUID_LENGTH_BINARY  16
#define UUID_LENGTH_STRING  36

static igloo_error_t igloo_uuid_new_random_r(char *buffer, igloo_ro_t instance)
{
    unsigned char id[UUID_LENGTH_BINARY];

    if (!buffer)
        return igloo_ERROR_FAULT;

    if (igloo_prng_read(instance, id, sizeof(id), igloo_PRNG_FLAG_NONE) != sizeof(id))
        return igloo_ERROR_IO;

    id[6] = (id[6] & 0x0F) | 0x40;
    id[8] = (id[8] & 0x3F) | 0x80;

    //  0 1 2 3  4 5  6 7  8 9 101112131415
    // 551a9547-fe63-45cf-a153-2801bac47ff8
    snprintf(buffer, UUID_LENGTH_STRING+1, "%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x",
            (unsigned int)id[0], (unsigned int)id[1], (unsigned int)id[2], (unsigned int)id[3],
            (unsigned int)id[4], (unsigned int)id[5],
            (unsigned int)id[6], (unsigned int)id[7],
            (unsigned int)id[8], (unsigned int)id[9],
            (unsigned int)id[10], (unsigned int)id[11], (unsigned int)id[12],
            (unsigned int)id[13], (unsigned int)id[14], (unsigned int)id[15]
            );

    return igloo_ERROR_NONE;
}

igloo_error_t igloo_uuid_new_random_sp(const char **ref, igloo_ro_t instance)
{
    char buffer[UUID_LENGTH_STRING+1];
    igloo_error_t error = igloo_uuid_new_random_r(buffer, instance);

    if (error != igloo_ERROR_NONE)
        return error;

    return igloo_sp_replace(buffer, ref, instance);
}

igloo_error_t igloo_uuid_new_random_cstr(char **str, igloo_ro_t instance)
{
    char buffer[UUID_LENGTH_STRING+1];
    igloo_error_t error = igloo_uuid_new_random_r(buffer, instance);
    char *res;

    if (!str || *str)
        return igloo_ERROR_FAULT;

    if (error != igloo_ERROR_NONE)
        return error;

    res = strdup(buffer);
    if (res == NULL)
        return igloo_ERROR_NOMEM;

    *str = res;

    return igloo_ERROR_NONE;
}


igloo_error_t igloo_uuid_is_valid(const char *str, igloo_uuid_strictness_t strictness)
{
    static const size_t group_sizes[] = {8, 4, 4, 4, 12};
    bool fenced = false;

    if (!str)
        return igloo_ERROR_FAULT;

    if (strictness == igloo_UUID_STRICTNESS_LOOSE) {
        for (; *str && isspace(*str); str++);
        if (*str == '{') {
            str++;
            fenced = true;
        }
    }

    for (size_t group = 0; group < (sizeof(group_sizes)/sizeof(*group_sizes)); group++) {
        /* check if we have the group seperator between groups */
        if (group != 0) {
            if (*str != '-')
                return igloo_ERROR_ILLSEQ;
            str++;
        }

        for (size_t need = group_sizes[group]; need; need--, str++) {
            if (*str >= '0' && *str <= '9')
                continue;

            if (*str >= 'a' && *str <= 'f')
                continue;

            if (strictness == igloo_UUID_STRICTNESS_RELAXED || strictness == igloo_UUID_STRICTNESS_LOOSE) {
                /* allow upper case as well for more relaxed modes */
                if (*str >= 'A' && *str <= 'F')
                    continue;
            }

            /* otherwise we got something invalid */
            return igloo_ERROR_ILLSEQ;
        }
    }

    if (strictness == igloo_UUID_STRICTNESS_LOOSE) {
        if (fenced) {
            if (*str == '}') {
                str++;
            } else {
                return igloo_ERROR_ILLSEQ;
            }
        }
        for (; *str && isspace(*str); str++);
    }

    /* if there is anything left, we're invalid. */
    if (*str)
        return igloo_ERROR_ILLSEQ;

    return igloo_ERROR_NONE;
}
