/* errors.c
 * Nicholas Ingolia
 * ingolia@mit.edu
 */

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

#include "errors.h"

#define ERRMSGLEN 1024
static char errmsg[ERRMSGLEN];

#define COMMANDLEN 512
static char command[COMMANDLEN];

#define HOSTLEN 64
static char host[HOSTLEN];

const char *errormail = "/usr/bin/mail";
const char *errorsto = "ingolia@mit.edu";
const char *errorsbj = "zbot error";

void error(const char *errstr)
{
  FILE  *fmail;
  time_t now;

  fprintf(stderr, errstr);

  now = time(NULL);
  gethostname(host, HOSTLEN);

  snprintf(command, COMMANDLEN, "%s %s", errormail, errorsto);
  fmail = popen(command, "w");
  fprintf(fmail, errorsbj);
  fputc('\n', fmail);
  fprintf(fmail, "%s\n", ctime(&now));
  fprintf(fmail, "%lu@%s\n", (unsigned long) getpid(), host);
  fprintf(fmail, errstr);
  pclose(fmail);
}

void *xmalloc(size_t sz)
{
  void *p = malloc(sz);

  if (p == NULL) {
    snprintf(errmsg, ERRMSGLEN, "Failed allocation of %lu bytes.\n", 
	     (unsigned long) sz);
    error(errmsg);
    abort();
  }

  return p;
}

char *xstrdup(const char *str)
{
  char *dstr = strdup(str);

  if (dstr == NULL) {
    snprintf(errmsg, ERRMSGLEN, "Failed dup of %lu-character string.\n", 
	     (unsigned long) strlen(str));
    error(errmsg);
    abort();
  }

  return dstr;
}

char *now_string(void)
{
  time_t t;

  t = time(NULL);
  return ctime(&t);
}
