#include <unistd.h>
#include "strerr.h"
#include "cdb.h"
#include "scan.h"
#include "str.h"
#include "buffer.h"

#define USAGE " key [skip]"
#define FATAL "cdbget: fatal: "

#define BUFSIZE 1024

const char *progname;
static struct cdb c;

void usage() { strerr_die4x(100, "usage: ", progname, USAGE, "\n"); }

int main(int argc, char **argv) {
  char *key;
  uint32 keylen;
  uint32 datalen;
  uint32 datapos;
  uint32 len;
  unsigned long skip;
  char buf[BUFSIZE];

  progname =*argv++;
  if (!(key =*argv++) || !*key) usage();
  if (*argv) {
    if ((*argv)[scan_ulong(*argv, &skip)]) usage();
    if (*++argv) usage();
  }
  else skip =0;

  /* initialize cdb read */
  cdb_init(&c, 0);
  cdb_findstart(&c);
  /* find data for key, optionally skip entries */
  keylen =str_len(key);
  for (++skip; skip; --skip) {
    switch(cdb_findnext(&c, key, keylen)) {
    case 0: _exit(100);
    case -1: strerr_die2sys(111, FATAL, "unable to read input: ");
    }
  }
  /* key found */
  datapos =cdb_datapos(&c);
  datalen =cdb_datalen(&c);
  /* write data to stdout */
  while (datalen) {
    len =datalen < BUFSIZE ? datalen : BUFSIZE;
    if (cdb_read(&c, buf, len, datapos) == -1)
      strerr_die2sys(111, FATAL, "unable to read input: ");
    if (buffer_put(buffer_1, buf, len) == -1)
      strerr_die2sys(111, FATAL, "unable to write output: ");
    datapos +=len; datalen -=len;
  }
  if (buffer_flush(buffer_1) == -1)
    strerr_die2sys(111, FATAL, "unable to flush output: ");
  _exit(0);
}
