/*
 * tools.c: some helper classes
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id$
 */
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>
#include <syslog.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "tools.h"

bool StackLogger::wantTS = 1;
int StackLogger::level = 0;
const char * StackLogger::fnLog = "/var/stackker.log";
static const char FF_UNKNOWN[] = "unknown";

StackLogger::StackLogger(const char * fn,int ln,const char * ff)
: hLen(40)	
, file(fn)
, line(ln)	
{
  if(ff)	name = ff;	
  else name = FF_UNKNOWN;
  level++;
  Log(LOG_INFO,fn,ln,"> enter %s() --->",name);
}

StackLogger::~StackLogger()
{
  Log(LOG_INFO,file,line,"< leave %s() <---",name);
  level--;
}

void    StackLogger::Log(int ll, const char* fn, int ln, const char * fmt, ...)
{
	FILE * fp = NULL;
	if((fp = fopen(fnLog, "a"))) {
	  switch(ll) {
		  case LOG_DEBUG: snprintf(scratch,sizeof(scratch),"%s/%s():%4d- dbg:",fn,name,ln); break;
		  case LOG_INFO: snprintf(scratch,sizeof(scratch),"%s/%s():%4d-Info:",fn,name,ln); break;
		  case LOG_WARNING: snprintf(scratch,sizeof(scratch),"%s/%s():%4d-WARN:",fn,name,ln); break;
		  case LOG_ERR: snprintf(scratch,sizeof(scratch),"%s/%s():%4d- ERR:",fn,name,ln); break;
		  default: break;
		  }					 
	  if(wantTS) {
		  time_t now = time(NULL);
		  struct tm t={0};

		  gmtime_r(&now, &t);
		  localtime_r(&now, &t);
		  snprintf(msg, sizeof(msg), "%2d.%02d.%02d %2d:%02d:%02d %*.*s%*.*s"
					, t.tm_mday, t.tm_mon, (1900+t.tm_year)%1000, t.tm_hour, t.tm_min, t.tm_sec
					, hLen, hLen, strlen(scratch)>hLen?scratch+strlen(scratch)-hLen:scratch
					, 2*level,2*level," ");
	     }
	  else {
		  snprintf(msg, sizeof(msg), "%*.*s%*.*s"
					, hLen, hLen, strlen(scratch)>hLen?scratch+strlen(scratch)-hLen:scratch
					, 2*level,2*level," ");
	     }
	  va_list ap;
	  va_start(ap, fmt);
	  vsnprintf(msg+strlen(msg), sizeof(msg) -2 -strlen(msg),fmt, ap);
	  va_end(ap);
	  fprintf(fp, "%s\n", msg);
	  fclose(fp);
	  if(ll == LOG_ERR) {
		  syslog(LOG_ERR, "ERROR in plugin xms! Please have a look at %s", fnLog);
	  	  }
     }
  else {
	  syslog(LOG_ERR, "xms-ERROR: could not open Logfile %s\n", fnLog);
     }
}

