/* Copyright 1993 - Matti Aarnio, Turku University, Turku, Finland
   This will be free software, but only when it is finished.

   The way the Zmailer uses DBM entries is by using strings with
   their terminating NULL as keys, and as data..  Thus the length
   is strlen(string)+1, not strlen(string) !
*/

#include "hostenv.h"
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <fcntl.h>
#ifdef HAVE_NDBM
#include <ndbm.h>
#else
#ifdef HAVE_GDBM
#include <gdbm.h>
#else
	error:error:Only NDBM and GDBM supported! (NDBM primarily)
#endif
#endif

#include <errno.h>	/* This usually defines the following three.. */
     /* extern int errno;
	extern char *sys_errlist[];
	extern int sys_nerr	*/;

extern void create_dbase();

void
usage(prog,err,errno)
char *prog, *err;
int errno;
{
  fprintf(stderr,"Usage: %s database.name key\n",prog);
#ifdef HAVE_NDBM
  fprintf(stderr,"  (NDBM appends  .pag, and .dir  into actual db file names..)\n");
#else /* GDBM.. */
  fprintf(stderr,"  (GDBM DOES NOT append .pag, nor .dir  into actual db file names..)\n");
#endif
  fprintf(stderr," Error now: %s",err);
  if (errno > 0 && errno < sys_nerr)
    fprintf(stderr,", errno=%d (%s)",errno,sys_errlist[errno]);
  fprintf(stderr,"\n");
  exit (1);
}

int
main(argc,argv)
int argc;
char *argv[];
{
  char *dbasename = NULL;
  FILE *infile = NULL;
  datum key;
  datum result;
#ifdef HAVE_NDBM
  DBM *dbmfile;
#else
  GDBM_FILE dbmfile;
#endif

  if (argc != 3) usage(argv[0],"wrong number of arguments",0);
  dbasename = argv[1];
#ifdef HAVE_NDBM
  dbmfile = dbm_open(dbasename, O_RDONLY, 0644);
#else
  dbmfile = gdbm_open(dbasename, 0, GDBM_READER, 0);
#endif
  if (dbmfile == NULL)
    usage(argv[0],"Can't open dbase file",errno);

  key.dptr = argv[2];
  key.dsize = strlen(argv[2]) +1;

#ifdef HAVE_NDBM
  result = dbm_fetch(dbmfile,key);
#else
  result = gdbm_fetch(dbmfile,key);
#endif
  if (result.dptr == NULL) {
    fprintf(stderr,"Key %s not found\n",argv[2]);
    return 2;
  }
  printf("siz:%d, dat: %s\n",result.dsize,result.dptr);

#ifdef HAVE_NDBM
  dbm_close(dbmfile);
#else
  gdbm_close(dbmfile);
#endif

  return 0;
}
