/* Copyright (c) 1999 Thorsten Kukuk
   Author: Thorsten Kukuk <kukuk@suse.de>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#define _GNU_SOURCE

#include <string.h>
#include <stdio.h>
#include <rpc/xdr.h>
#include <rpcsvc/nis.h>

#include "db_private.h"
#include "xdb.h"

bool_t
xdb_set_log_present (FILE *fp, xdb_header *header)
{
  XDR xdrs;

  fseek (fp, 0, SEEK_SET);
  header->log_present = TRUE;
  xdrstdio_create (&xdrs, fp, XDR_ENCODE);
  if (!xdr_xdb_header (&xdrs, header))
    {
      xdr_destroy (&xdrs);
      return FALSE;
    }
  xdr_destroy (&xdrs);
  return TRUE;
}

bool_t
xdb_read_header (const char *path, xdb_header *header)
{
  XDR xdrs;
  char *path_log, *cp;
  FILE *fp;
  int failed = 0;

  if (path == NULL || strlen (path) == 0)
    abort ();

  path_log = alloca (strlen (path) + 5);
  cp = stpcpy (path_log, path);
  strcpy (cp, ".log");

  fp = fopen (path_log, "rb+");
  if (fp != NULL)
    {
      __close_on_exit (&fp);

      /* Read the header of the log file */
      memset (header, 0, sizeof (xdb_header));
      xdrstdio_create (&xdrs, fp, XDR_DECODE);
      if (!xdr_xdb_header (&xdrs, header))
	failed = 1;
      xdr_destroy (&xdrs);
      fclose (fp);
    }
  else
    failed = 1;

  if (failed)
    {
      fp = fopen (path, "rb+");
      if (fp == NULL)
	return FALSE;
      __close_on_exit (&fp);

      /* Read the header of the log file */
      memset (header, 0, sizeof (xdb_header));
      xdrstdio_create (&xdrs, fp, XDR_DECODE);
      if (xdr_xdb_header (&xdrs, header))
	failed = 0; /* This time we have success ! */
      xdr_destroy (&xdrs);
      fclose (fp);
      if (failed)
	return FALSE;
    }

  if (header->vers != XDB_VERSION ||
      strncmp (header->identifier, XDB_VER_STRING,
	       strlen (XDB_VER_STRING)) != 0)
    return FALSE;

  return TRUE;
}
