#include <syslog.h>
#include <stdarg.h>
#include <stdio.h>
#include "antispam-plugin.h"
#include "antispam-version.h"


static void _debug(const struct antispam_settings *cfg,
		   const char *format, va_list ap)
{
	const char *fmt;

	if (cfg->debug_target == ADT_NONE)
		return;

	T_BEGIN {

	fmt = t_strconcat(cfg->debug_prefix, format, NULL);

	switch (cfg->debug_target) {
	case ADT_NONE:
		break;
	case ADT_SYSLOG:
		vsyslog(LOG_DEBUG, fmt, ap);
		break;
	case ADT_STDERR:
		vfprintf(stderr, fmt, ap);
		fflush(stderr);
		break;
	}

	} T_END;
}

void debug(const struct antispam_settings *cfg, const char *fmt, ...)
{
	va_list args;

	va_start(args, fmt);
	_debug(cfg, fmt, args);
	va_end(args);
}

void debugv(const struct antispam_settings *cfg, char **args)
{
	size_t len, pos = 0, buflen = 1024;
	char *buf;
	const char *str;

	T_BEGIN {
	buf = t_buffer_get(buflen);

	while (1) {
		str = *args;
		if (!str)
			break;
		len = strlen(str);
		if (pos + len + 1 >= buflen) {
			buflen = nearest_power(pos + len + 2);
			buf = t_buffer_reget(buf, buflen);
		}

		memcpy(buf + pos, str, len);
		pos += len;
		buf[pos++] = ' ';
		args++;
	}

	buf[pos++] = '\0';

	t_buffer_alloc(pos);

	debug(cfg, "%s", buf);
	} T_END;
}

void debugv_not_stderr(const struct antispam_settings *cfg, char **args)
{
	if (cfg->debug_target == ADT_STDERR)
		return;

	debugv(cfg, args);
}

void debug_verbose(const struct antispam_settings *cfg, const char *fmt, ...)
{
	va_list args;

	if (!cfg->verbose_debug)
		return;

	va_start(args, fmt);
	_debug(cfg, fmt, args);
	va_end(args);
}
