/*
  getdb.c

  Rob Funk <funk+@osu.edu>
  2 July 1996

  Get the data associated with a key in a specified .db file

  Usage:  getdb file key

  Requires Berkeley db library; compile with "-ldb".

*/

#include <sys/types.h>
#include <errno.h>
#include <compat.h>
#include <db.h>
#include <stdio.h>
#include <string.h>

void main(int argc, char **argv)
{
  DB *db;
  DBT *key, *data;
  char *output;
  int res, i;
  DBTYPE type[] = { DB_BTREE, DB_HASH, DB_RECNO };

  /* check call syntax */
  if (argc != 3) {
    fprintf(stderr,"Usage:  %s file key\n",argv[0]);
    exit(-1);
  }

  /* allocate structure for key, to send to db->get */
  key = (DBT *)malloc(sizeof(DBT));
  if (key == NULL) {
    perror(argv[0]);
    exit(-1);
  }
  /* stuff given info into key structure */
  key->data = argv[2];
  key->size = strlen(argv[2]);

  /* try to open the file with each type */
  db = NULL; errno=EFTYPE;
  for (i=0 ; (i<3) && (db==NULL) && (errno==EFTYPE) ; i++)
    db = dbopen(argv[1], 0, 0, type[i], NULL);
  /* none of the types worked */
  if (db == NULL) {
    perror(argv[0]);
    exit(-1);
  }

  /* allocate structure for data */
  data = (DBT *)malloc(sizeof(DBT));
  if (data == NULL) {
    perror(argv[0]);
    exit(-1);
  }

  /* now get the data associated with the key */
  res = (db->get)(db, key, data, 0);
  if (res < 0) {
    perror(argv[0]);
    exit(-1);
  } else if (res > 0) {
    fprintf(stderr,"Key not found\n");
    exit(1);
  }

  output = (char *)malloc(1+data->size); /* allocate space for output */
  strncpy(output, data->data, data->size); /* copy data to output */
  output[data->size] = '\0'; /* don't forget to terminate the string */

  puts(output); /* spit it out on stdout, with a newline */

  /* exit successfully */
  exit(0);
}

