/*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
 *
 * librsync -- library for network deltas
 * $Id: log.c,v 1.18 2001/08/01 09:08:22 mbp Exp $
 *
 * Copyright (C) 2000, 2001 by Martin Pool <mbp@samba.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

                                     /*
                                      | Finality is death.
                                      | Perfection is finality.
                                      | Nothing is perfect.
                                      | There are lumps in it.
                                      */

#include <includes.h>

#include <sys/time.h>

/**
 * Log messages passed in should \b not have terminating newlines, but
 * they may have newlines in the middle.
 *
 * Messages passed to log implementations have trailing and
 * intermediate newlines.  Implementations that can't handle more than
 * one newline (e.g. syslog) need to split the string themselves.
 **/

static n4log_fn_t *n4log_impl = n4log_to_stderr;

int n4trace_level = N4LOG_NOTICE;

/* Might need something else on non-gcc */
#define MY_NAME program_invocation_short_name

static void n4log_va(int level, char const *domain,
                     char const *fn, char const *fmt, va_list va);

const int n4log_use_domain = FALSE;


/**
 * Log severity strings, if any.  Must match ordering in
 * ::n4loglevel.
 */
static const char *n4_severities[] = {
    "PANIC! ", "ALERT! ", "CRITICAL! ", "ERROR: ", "Warning: ",
     "", "", ""
 };



 /**
  * \brief Set the destination of trace information.
  *
  * The callback scheme allows for use within applications that may
  * have their own particular ways of reporting errors: log files for a
  * web server, perhaps, and an error dialog for a browser.
  *
  * \todo Do we really need such fine-grained control, or just yes/no
  * tracing?
  */
void n4_set_log_fn(n4log_fn_t * new_impl)
{
    n4log_impl = new_impl;
}



void n4log_to_syslog(int flags, const char *fn, const char *msg)
{
    const char                  *start = msg;
    int                         toprint = strcspn(start, "\n");
    int level                   = flags & N4LOG_PRIMASK;
    
    if (!fn  ||  (flags & N4LOG_NOFN)) {
        syslog(level, "%s%.*s", n4_severities[level], toprint, start);
    } else {
        syslog(level, "(%20s) %s%.*s", fn, n4_severities[level],
               toprint, start);
    } 

    while (1) {
        start += toprint;
        while (*start == '\n')
            start++;
        if (!*start)
            break;
        toprint = strcspn(start, "\n");
        syslog(level, "%.*s", toprint, start);
    }
}


void n4log_to_stderr(int flags, const char *fn, const char *msg)
{
    int level                   = flags & N4LOG_PRIMASK;
    
    if (!fn  ||  flags & N4LOG_NOFN) {
        fprintf(stderr, "%s: %s%s\n", MY_NAME, n4_severities[level], msg);
    } else {
        fprintf(stderr, "%s(%20s) %s%s\n",
                MY_NAME, fn, n4_severities[level], msg);
    }
}


void n4log_open_syslog(int facility)
{
    openlog(MY_NAME, LOG_PID, facility);
}


/** 
  * Set the least important message severity that will be output.
  */
void
n4trace_set_level(n4loglevel level)
{
    n4trace_level = level;
}


static void n4log_va(int flags, char const *UNUSED(domain),
                     char const *fn, char const *fmt, va_list va)
{
    int                         level = flags & N4LOG_PRIMASK;
    static char                 *buf = 0;
    static size_t               buf_alloc = 0;

    if (n4log_impl  &&  level <= n4trace_level) {
        size_t                  need;

        need = vsnprintf(NULL, 0, fmt, va) + 1;
        if (need > buf_alloc  ||  !buf) 
            buf = realloc(buf, buf_alloc = need);
            
        if (buf) {
            vsnprintf(buf, buf_alloc, fmt, va);

            n4log_impl(flags, fn, buf);
        }
    }
}



/**
 * Called by a macro, used on platforms where we can't determine the
 * calling function name.
 */
void
n4log0_nofn(int level, char const *fmt, ...)
{
    va_list         va;

    va_start(va, fmt);
    n4log_va(level, PACKAGE, NULL, fmt, va);
    va_end(va);
}


/* Called by a macro that prepends the calling function name,
 * etc.  */
void
n4log0(int level, char const *domain, char const *fn, char const *fmt, ...)
{
    va_list         va;

    va_start(va, fmt);
    n4log_va(level, domain, fn, fmt, va);
    va_end(va);
}


/* This is called directly if the machine doesn't allow varargs
 * macros. */
void
n4fatal0(char const *s, ...) 
{
    va_list	va;

    va_start(va, s);
    n4log_va(N4LOG_CRIT, PACKAGE, NULL, s, va);
    va_end(va);
}


/* This is called directly if the machine doesn't allow varargs
 * macros. */
void
n4_error0(char const *s, ...) 
{
    va_list	va;

    va_start(va, s);
    n4log_va(N4LOG_ERR, PACKAGE, NULL, s, va);
    va_end(va);
}


/* This is called directly if the machine doesn't allow varargs
 * macros. */
void
n4trace0(char const *s, ...) 
{
    va_list	va;

    va_start(va, s);
    n4log_va(N4LOG_DEBUG, PACKAGE, NULL, s, va);
    va_end(va);
}


/**
 * Return true if the library contains trace code; otherwise false.
 * If this returns false, then trying to turn trace on will achieve
 * nothing.
 */
int
n4_supports_trace(void)
{
#ifdef DO_N4_TRACE
    return 1;
#else
    return 0;
#endif				/* !DO_N4_TRACE */
}


MKPROTO void n4log_elapsed0(char const *domain,
                            char const *fn,
                            char const *what,
                            struct timeval *before,
                            struct timeval *after)
{
    struct timeval delta;

    timeval_subtract(&delta, after, before);
    n4log0(N4LOG_INFO, domain, fn, 
           "%s completed in %ld.%06ds", what, (long) delta.tv_sec,
           (int) delta.tv_usec); 
}

