/*
 * Copyright (c) 2022 Arran Cudbard-Bell <a.cudbardb@freeradius.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#ifndef NDEBUG

#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "debug.h"
#include "private.h"

bool libkqueue_debug = false;

/** Prefix for libkqueue debug messages
 */
char const *libkqueue_debug_ident = "KQ";

/** Copy of the externally provided identity string
 */
static char *libkqueue_debug_ident_copy;

static void dbg_stderr(char const *fmt, ...);

/** Custom logging function
 */
dbg_func_t libkqueue_debug_func = dbg_stderr;

static void
dbg_stderr(char const *fmt, ...)
{
    va_list ap;

    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
}

/** Set a new logging debug function
 */
void
libkqueue_debug_func_set(dbg_func_t func)
{
    if (!func) {
        libkqueue_debug_func = dbg_stderr;
    } else {
        libkqueue_debug_func = func;
    }
}

/** Set a new debug identity
 */
void
libkqueue_debug_ident_set(char const *str)
{
    free(libkqueue_debug_ident_copy);
    libkqueue_debug_ident_copy = strdup(str);
    libkqueue_debug_ident = libkqueue_debug_ident_copy;
}

/** Clear any previously allocated identities
 */
TSAN_IGNORE
void
libkqueue_debug_ident_clear(void)
{
    libkqueue_debug_ident = "";
    free(libkqueue_debug_ident_copy);
    libkqueue_debug_ident_copy = NULL;
}
#endif
