/*
** SellaNMS
** $Id: loader.cxx,v 1.16 2006/01/24 07:08:10 sella Exp $
** Copyright (c) 2001-2005 Digital Genesis Software, LLC. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
*/

static const char rcsid[] = "$Id: loader.cxx,v 1.16 2006/01/24 07:08:10 sella Exp $";

#include "loader.h"
#include "connection_pool.h"
#include <errno.h>
#include <stdio.h>
#include <unistd.h>

pthread_mutex_t __libstorage_global_mutex;
bool __libstorage_initialized = false;
ConnectionPool* pool = NULL;

int libstorage_count = 0;

void init(void) {
	if (libstorage_count++ != 0) {
		return;
	}

	pthread_mutex_init(&__libstorage_global_mutex, NULL);

	LMSG("libstorage is using %s", dbi_version());

	pool = new ConnectionPool;
	if (pool == NULL) {
		LMSG("Failed to allocate memory for ConnectionPool.");
		abort();
	}
}

void fini(void) {
	if (--libstorage_count != 0) {
		return;
	}

	/* Free our connection pool. Deconstructor will disconnect. */
	SAFE_DELETE(pool);

	LMSG("libstorage shutting down connections");

	pthread_mutex_lock(&__libstorage_global_mutex);

	if (__libstorage_initialized) {
		/* Closes all open connections and unloads all drivers. */
		dbi_shutdown();
		__libstorage_initialized = false;
	}

	pthread_mutex_unlock(&__libstorage_global_mutex);

   while (EBUSY == pthread_mutex_destroy(&__libstorage_global_mutex)) {
      LMSG("libstorage - _fini(): Initialize mutex is locked. Waiting for unlock.");
      usleep(USLEEP_NORMLOOP_TIME);
   }
}

#if 0
void __attrute__ ((constructor)) my_init(void) {
	init();
}

void __attrute__ ((destructor)) my_fini(void) {
	fini();
}

void _init() {
	init();
}

void _fini() {
	fini();
}
#endif

/*
** Local Variables:
** c-basic-offset: 3
** tab-width: 3
** End:
** vim:
** vim: noet ts=3 sw=3
*/
