/*
 * uri.c:
 *
 * Copyright (c) 2000 James McKenzie <james@fishsoup.dhs.org>,
 * All rights reserved.
 *
 */

static char rcsid[] = "$Id: uri.c,v 1.11 2001/10/12 13:51:11 root Exp $";

/*
 * $Log: uri.c,v $
 * Revision 1.11  2001/10/12 13:51:11  root
 * #
 *
 * Revision 1.10  2001/10/04 18:21:16  root
 * #
 *
 * Revision 1.9  2001/01/30 06:16:18  root
 * #
 *
 * Revision 1.8  2000/12/01 04:42:10  root
 * #
 *
 * Revision 1.7  2000/11/23 23:45:19  root
 * #
 *
 * Revision 1.6  2000/10/07 18:30:03  root
 * #
 *
 * Revision 1.5  2000/09/24 01:58:26  root
 * #
 *
 * Revision 1.4  2000/09/24 01:58:21  root
 * #
 *
 * Revision 1.3  2000/09/24 01:46:04  root
 * #
 *
 * Revision 1.2  2000/09/24 01:44:47  root
 * #
 *
 * Revision 1.1  2000/09/19 03:53:27  root
 * #
 *
 */

#include "project.h"

static DB *uridb = NULL;

/*Initialize the inode -> name database*/
static void uri_init(char *name)
{
  int ret;

  if (uridb)
    return;

  ret = db_create(&uridb, NULL, 0);
  if (ret) {
    fprintf(stderr, "db_create: %s\n", db_strerror(ret));
    uridb = NULL;
    return;
  }

  ret = uridb->open(uridb, name, NULL, DB_BTREE, DB_CREATE, 0x600);

  if (ret) {
    uridb->err(uridb, ret, "uridb");
    uridb->close(uridb, 0);
    uridb = NULL;
  }

}

/* ensure uridb is initialized */
#define DOINIT  { if (!uridb) uri_init(NULL); };

INTERNAL void uri_add(Eweid e, const char *s)
{
  DBT key = { 0 };
  DBT data = { 0 };
  int ret;

  key.data = e->e;
  key.size = sizeof(e->e);

  data.data = (char *) s;
  data.size = strlen(s);

  DOINIT;

  ret = uridb->put(uridb, NULL, &key, &data, 0);

  if (ret) {
    uridb->err(uridb, ret, "DB->put");
  }
}



INTERNAL char *eweid_to_uri(Eweid e)
{
  DBT key = { 0 };
  DBT data = { 0 };
  int ret;
  char *r;

  key.data = e->e;
  key.size = sizeof(e->e);

  DOINIT;

  ret = uridb->get(uridb, NULL, &key, &data, 0);

  if (ret == DB_NOTFOUND)
    return NULL;

  if (ret) {
    uridb->err(uridb, ret, "DB->get");
    return NULL;
  }

  r = (char *) malloc(data.size + 1);

  bcopy(data.data, r, data.size);
  r[data.size] = 0;

  return r;
}
