/* $Id: dump_db.pc 3956 2010-01-05 20:56:56Z zacheiss $
 *
 * 	This program dumps the Moira database to a series of output files
 * which can be later read back into Moira in the event of a crash.
 *
 * Copyright (C) 1988-1998 by the Massachusetts Institute of Technology.
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 */

#include <mit-copyright.h>
#include <moira.h>
#include "dump_db.h"

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

EXEC SQL INCLUDE sqlca;

RCSID("$HeadURL: svn+ssh://svn.mit.edu/moira/trunk/moira/backup/dump_db.pc $ $Id: dump_db.pc 3956 2010-01-05 20:56:56Z zacheiss $");

EXEC SQL BEGIN DECLARE SECTION;
char *db = "moira";
EXEC SQL END DECLARE SECTION;

int main(int argc, char **argv)
{
  char *prefix;

  if (argc != 2)
    {
      fprintf(stderr, "Usage: %s prefix\n", argv[0]);
      exit(1);
    }
  prefix = argv[1];

  EXEC SQL CONNECT :db IDENTIFIED BY :db;

  do_backups(prefix);

  EXEC SQL COMMIT;
  exit(0);
}

void dump_int(FILE *f, int n)
{
  char buf[1024];
  sprintf(buf, "%d", n);
  dump_str(f, buf);
}

void wpunt(void)
{
  punt("can't write backup file");
}

void dump_str(FILE *f, char *str)
{
  unsigned char *ibp, c;
  int t;

  for (ibp = str; (c = *ibp); ibp++)
    {
      if (c < 32 || c > 126 || c == SEP_CHAR || c == '\\')
	{
	  if (putc('\\', f) < 0)
	    wpunt();
	  t = ((c >> 6) & 7) + '0';
	  if (putc(t, f) < 0)
	    wpunt();
	  t = ((c >> 3) & 7) + '0';
	  if (putc(t, f) < 0)
	    wpunt();
	  t = (c & 7) + '0';
	  if (putc(t, f) < 0)
	    wpunt();
	}
      else
	{
	  if (putc(c, f) < 0)
	    wpunt();
	}
    }
}

void safe_close(FILE *stream)
{
  if (fflush(stream) == EOF)
    punt("Unable to fflush");
  if (fsync(fileno(stream)) != 0)
    punt("Unable to fsync");
  fclose(stream);
}

FILE *open_file(char *prefix, char *suffix)
{
  char name[BUFSIZ];
  int fd;
  FILE *f;

  strcpy(name, prefix);
  strcat(name, suffix);

  fd = open(name, O_CREAT|O_WRONLY|O_EXCL, 0644);
  if (fd < 0)
    punt(name);
  f = fdopen(fd, "w");
  if (!f)
    {
      fprintf(stderr, "fdopen of ");
      punt(name);
    }
  fprintf(stderr, "Working on %s\n", name);
  return f;
}

/*
 * Trim whitespace off the tail end of a string
 */
char *endtrim(char *save)
{
  char *t, *s;

  s = save;
  for (t = s; *t; t++)
    continue;
  while (t > s)
    {
      --t;
      if (!isspace(*t))
	{
	  t++;
	  break;
	}
    }
  if (*t)
    *t = '\0';
  return s;
}
