/*
 * mxallowd
 * (c) 2007-2009 Michael Stapelberg
 * 
 * See mxallowd.c for description, website and license information
 *
 */
#include <stdbool.h>
#include <stdarg.h>
#include <time.h>
#include <syslog.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

#include "mxallowd.h"

void slog(char *format, ...) {
	va_list ap;

	if (quiet)
		return;

	va_start(ap, format);
	if (to_stdout) {
		/* When not logging to syslog, we generate a timestamp */
		char timebuf[23];
		time_t t = time(NULL);
		struct tm *tmp = localtime(&t);
		
		strftime(timebuf, sizeof(timebuf), "%d.%m.%Y %H:%M:%S - ", tmp);
		printf("%s", timebuf);
		vprintf(format, ap);
	} else vsyslog(LOG_CONS | LOG_PID | LOG_DAEMON, format, ap);
	va_end(ap);
}

/*
 * Replaces perror() by logging to syslog if enabled
 *
 */
void slogerror(char *message) {
        if (to_stdout)
                fprintf(stderr, "%s: %s\n", message, strerror(errno));
        else syslog(LOG_CONS | LOG_PID | LOG_DAEMON | LOG_PERROR, "%s: %s\n", message, strerror(errno));
}

/*
 * Print the given message to stdout/syslog and exit(1)
 *
 */
void diem(char *message) {
        if (to_stdout)
                fprintf(stderr, "%s\n", message);
        else syslog(LOG_CONS | LOG_PID | LOG_DAEMON | LOG_PERROR, "%s\n", message);
	exit(1);
}

/*
 * Print the given message and errstr(errno) (like perror) to stdout/syslog and exit(1)
 *
 */
void diep(char *message) {
	slogerror(message);
	exit(1);
}

/*
 * Print the given message string (like printf) to stdout/syslog and exit(1)
 *
 */
void dief(char *format, ...) {
	va_list ap;

	va_start(ap, format);
	if (to_stdout) {
		vfprintf(stderr, format, ap);
	} else vsyslog(LOG_CONS | LOG_PID | LOG_DAEMON, format, ap);
	va_end(ap);

	exit(1);
}

