#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/param.h>
#include <errno.h>
#include <unistd.h>
#include <stdarg.h>
#include "meta.h"

static FILE *logfp = NULL;	/* log file */

/*
 * open the log file and print a friendly message
 */
void open_log()
{
  time_t now;
  char *ostr;

  if (!do_log) return;

  /* prepare the log file */
  if (!trun)
    ostr = "a";	/* just append */
  else
    ostr = "w";	/* truncate */

  if ((logfp = fopen(LOGFILE, ostr)) == NULL) {
    perror("ERROR: can't open log file for writing");
    exit(1);
  } else {
    setvbuf(logfp, NULL, _IONBF, 0);   /* no buffering */

    log_msg("\n");
    now = time(0);
    log_msg("** MetaServerII v%s started on %s", VERSION, ctime(&now));
  }
}

/*
 * print a message to the log
 */
void log_msg(const char *fmt, ...) {
  va_list args;
  char buf[256];

  if (!do_log) return;
  if (logfp == NULL) {
    fprintf(stderr, "WARNING: attempt to write message to closed log\n");
    return;
  }

  sprintf(buf, "%d: ", (int) time(NULL));
  va_start(args, fmt);
  vsnprintf(buf+strlen(buf), 255-strlen(buf), fmt, args);
  va_end(args);
  if (*(buf + strlen(buf)-1) != '\n')
    strcat(buf, "\n");

  /* since there should only be one metaserver process, we probably don't */
  /* need to seek to the end every time (but it allows truncation...) */
  fseek(logfp, (off_t) 0, 2);
  fprintf(logfp, "%s", buf);
  if (verbose) fprintf(stderr, "%s", buf);
}
