/**********************************************************************
 *
 * tdbget -- retrieve a single value from the TDB database
 *
 * A component of the Greenstone digital library software
 * from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * Copyright (C) 2011  The New Zealand Digital Library Project
 *
 * 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 of the License, 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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *********************************************************************/

#if defined(GSDL_USE_OBJECTSPACE)
#include <ospace\std\iostream>
#elif defined(GSDL_USE_IOS_H)
#include <iostream.h>
#else
#include <iostream>
#endif

#include <cstdlib>
#include <cstring>

#include <fcntl.h>
#include "tdb.h"

// use the standard namespace
#if !defined (GSDL_NAMESPACE_BROKEN)
#if defined(GSDL_USE_OBJECTSPACE)
using namespace ospace::std;
#else
using namespace std;
#endif
#endif

/**
 */
void
printUsage (char *program_name)
{
  cerr << "usage: " << program_name << " <database_path> <key>" << endl << endl;
}
/** printUsage() **/

/**
 */
int
main (int argc, char *argv[])
{
  // sanity check
  if (argc != 3)
  {
    printUsage(argv[0]);
    exit (-1);
  }

  char *dbname = argv[1];

  int hash_size = 0;
  int tdb_flags = TDB_DEFAULT; // Default = 0
  int open_flags = O_RDONLY;
  TDB_CONTEXT *tdb = tdb_open(dbname, hash_size, tdb_flags, open_flags, 0664);
  if (!tdb)
  {
    cerr << "couldn't create " << dbname << endl;
    exit (0);
  }

  TDB_DATA key;
  key.dsize = strlen(argv[2]);
  key.dptr = (unsigned char*)argv[2];

  TDB_DATA value = tdb_fetch (tdb, key);

  if (value.dsize > 0)
  {
    for (int i = 0; i < value.dsize; i++)
    {
      cout << value.dptr[i];
    }
    cout << endl; // used to be printf("\n");
    // caller responsible for freeing this memory
    free(value.dptr);
  }
  else
  {
    cout << endl; // used to be printf("\n");
  }

  tdb_close (tdb);
  return 0;
}
/** main() **/

