/*
 * $Id$
 *
 * Code (c)2006 Bruno Cornec <bruno@mondorescue.org>
 *
 *     Main file of mr_msg : a very small and simple
 *     library for messages management
 *
 * Provided under the GPLv2
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

static int mr_loglevel = 0;
static char *mr_logfile = NULL;
static FILE *mr_flog = NULL;

/*
 * This function is in the lowest part of the tree
 * It should not depend on any other function of the mr lib 
 */

/* Function allowing to change loglevel after init */
void mr_msg_loglevel(int loglevel) {

	mr_loglevel = loglevel;
}

/* Cleanup function for messages */
void mr_msg_close(void) {

	int res = 0;
	if ((res = fclose(mr_flog)) != 0) {
		fprintf(stderr,"Unable to close %s\n",mr_logfile);
	}
	free(mr_logfile);

	mr_logfile = NULL;
	mr_loglevel = 0;
	mr_flog = NULL;
return;
}

/* Initialization function for messages */
void mr_msg_init(const char *logfile, int loglevel, int argc, char *argv[]) {

	int i=1;

	if (asprintf(&mr_logfile, "%s", logfile) == -1) {
		fprintf(stderr,"Unable to alloc memory\n");
		fprintf(stderr,"Logging desactivated\n");
		mr_msg_close();
	}
	if (fopen(mr_logfile, "r") == NULL) {
		/*  log file doesn't exist yet, so creating it */
		if ((mr_flog = fopen(mr_logfile, "w")) == NULL) {
			fprintf(stderr,"Unable to write to %s\n",mr_logfile);
			fprintf(stderr,"Logging desactivated\n");
			mr_msg_close();
		}
	} else {
		/*  If it exists try to append to it */
		if ((mr_flog = fopen(mr_logfile, "a")) == NULL) {
			fprintf(stderr,"Unable to write to %s\n",mr_logfile);
			fprintf(stderr,"Logging desactivated\n");
			mr_msg_close();
		}
	}
	while (i < argc) {
		if (strcmp(argv[i],"-K") == 0) {
			i++;
			if (argv[i]) {
				loglevel = atoi(argv[i]);
			} else {
				fprintf(stderr,"-K option requires a loglevel\n");
				mr_msg_close();
				exit(-1);
			}
		}
		i++;
	}
	mr_msg_loglevel(loglevel);
}

/*
 * Function that log a message. Not called directly 
 * but through other functions
 * fmt needs to be just before ...
 * level should be >0 to have file and line printed (real debug)
 * If =0 it's an informative log message
 */
void mr_msg_int(int level, int line, const char *file, char *function, const char *fmt, ...) {

	va_list args;

	if ((mr_logfile == NULL) || (mr_flog == NULL)) {
		return;
	}

	if (level <= mr_loglevel) {
		if (level > 0) {
			fprintf(mr_flog, "DBG%d: ", level);
			fprintf(mr_flog, "%s->%s#%d: ", file, function, line);
		} else {
			fprintf(mr_flog, "INFO: ");
		}
		va_start(args,fmt);
		if (vfprintf(mr_flog, fmt, args) < 0) {
			fprintf(stderr,"Unable to print to %s\n",mr_logfile);
		}
		fprintf(mr_flog,"\n");
		va_end(args);

	}
	return;
}

