#include <sys/param.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "config.h"
#include "uid.h"

#ifndef HAVE_GETHOSTNAME_PROTO
extern "C" int gethostname(char*, int);
#endif

#ifdef HAVE_GETHOSTID
#ifndef HAVE_GETHOSTID_PROTO
extern "C" long gethostid(void);
#endif
#endif

#ifndef HAVE_GETPID_PROTO
extern "C" pid_t getpid(void);
#endif

#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 1000
#endif

char const* uid_new() {
    static int   inited = 0;
    static char  hostname[MAXHOSTNAMELEN+1];
    static char  buffer[MAXHOSTNAMELEN+1000];
    static int   hostid = 0;
    static pid_t pid = 0;
    static int   counter = 0;

    if (! inited) {
	if (gethostname(hostname, MAXHOSTNAMELEN+1) < 0) {
	    // Error?
	    strcpy(hostname, "unknownhost");
	}
#ifdef HAVE_GETHOSTID
	hostid = gethostid();
#else
	hostid = 0;
#endif
	pid = getpid();
	counter = 0;
	inited = 1;
    }

    sprintf(buffer, "%s_%x_%x_%x", hostname, hostid, pid, counter);
    counter++;

    char* id = new char[strlen(buffer)+1];
    strcpy(id, buffer);
    return id;
}

implementOpenHashSet(UidSet,char const*,hash_string,equal_uid)
