/* $Id$
******************************************************************************

   LibGIC - Init/Exit functions

   Copyright (C) 1999 Andreas Beck	[becka@ggi-project.org]

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   THE AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************************
*/

#include "config.h"
#include <stdlib.h>
#include <string.h>

#include <ggi/gg.h>
#include <ggi/internal/gic.h>
#include <ggi/internal/gic_debug.h>

#include <ggi/internal/gg_replace.h>	/* for snprintf() */


/* Exported variables */
uint32_t _gicDebug = 0;


/* Global variables */
void *_gic_global_lock = NULL;
void *_gicconfhandle = NULL;

/* Static variables */
static int _gicLibIsUp = 0;
static char gicconfstub[512] = GICCONFDIR;
static char *gicconfdir = gicconfstub + GICTAGLEN;


/* 
 * Returns the directory wher global config files are kept
 */

static const char *gicGetConfDir(void)
{
#if defined(__WIN32__) && !defined(__CYGWIN__)
	/* On Win32 we allow overriding of the compiled in path. */
	const char *envdir = getenv("GGI_CONFDIR");
	if (envdir)
		return envdir;
#endif
	return gicconfdir;
}


void _giigicInitBuiltins(void);
void _giigicExitBuiltins(void);


/*
 * Initialize the structures for the library
 */

int gicInit(void)
{
	int err = 0;
	const char *str, *confdir;
	char *conffile;


	_gicLibIsUp++;
	if (_gicLibIsUp > 1)
		return 0;	/* Initialize only at first call. */

	err = ggInit();
	if (err != GGI_OK) {
		fprintf(stderr, "LibGIC: unable to initialize LibGG\n");
		goto err0;
	}
	
	str = getenv("GIC_DEBUGSYNC");
	if (str != NULL) {
		_gicDebug |= DEBUG_SYNC;
	}
	
	str = getenv("GIC_DEBUG");
	if (str != NULL) {
		_gicDebug |= atoi(str) & DEBUG_ALL;
		DPRINT_CORE("%s Debugging=%d\n",
			    DEBUG_ISSYNC ? "sync" : "async",
			    _gicDebug);
	}
	
	confdir = gicGetConfDir();
	conffile = malloc(strlen(confdir) + 1 + strlen(GICCONFFILE) + 1);
	if (!conffile) {
		fprintf(stderr,
			"LibGIC: unable to allocate memory for config filename.\n");
		err = GGI_ENOMEM;
		goto err1;
	}

	snprintf(conffile,
		 strlen(confdir) + strlen(GICCONFFILE) + 2,
		 "%s/%s", confdir, GICCONFFILE);

	err = ggLoadConfig(conffile, &_gicconfhandle);
	free(conffile);
	if (err == GGI_OK) {
		_giigicInitBuiltins();
		return GGI_OK;
	}

	fprintf(stderr,
		"LibGIC: fatal error - could not load %s\n",
		conffile);

err1:
	ggExit();
err0:
	_gicLibIsUp--;
	return err;
}

int gicExit(void)
{
	DPRINT_CORE("gicExit() called\n");
	if (!_gicLibIsUp)
		return GGI_ENOTALLOC;

	if (_gicLibIsUp > 1) {
		/* Exit only last call */
		_gicLibIsUp--;
		return _gicLibIsUp;
	}


	_giigicExitBuiltins();

	DPRINT_CORE("gicExit: really destroying.\n");

	ggFreeConfig(_gicconfhandle);
	_gicconfhandle = NULL;
	ggExit();
	_gicLibIsUp = 0;

	DPRINT_CORE("gicExit: done!\n");
	return 0;
}


#define GIC_SYMNAME_MAX		255
#define GIC_SYMNAME_PREFIX	"GICdl_"


gic_handle *gicOpen(const char *drivers, ...)
{
	gic_handle *rc;

	char symname[GIC_SYMNAME_MAX+1];
	const char *nameptr;
	char *extptr;

	struct gg_target_iter target;
	struct gg_location_iter match;


	DPRINT_LIBS("_gicOpen(\"%s\",...) called \n",
		       drivers ? drivers : "(null)");

	if (!drivers)
		drivers = "default";

	rc = (gic_handle *)malloc(sizeof(gic_handle));
	if (!rc) return NULL;

	rc->input = NULL;
	rc->reclist = NULL;

	DPRINT_LIBS("_gicOpen(\"%s\",...) called \n",
		       drivers ? drivers : "(null)");

	target.input = drivers;
	target.config = _gicconfhandle;
	ggConfigIterTarget(&target);
	GG_ITER_FOREACH(&target) {
		gg_scope handle;
		gic_recognizerdriver *(*init) (void);
		gic_recognizerdriver *driver;

		DPRINT_LIBS("target match says: %s:(%s)\n",
			target.target, target.options);

		handle = NULL;

		match.name = target.target;
		match.config = _gicconfhandle;
		ggConfigIterLocation(&match);
		GG_ITER_FOREACH(&match) {
			DPRINT_LIBS("location match says: %s(%s)\n",
				match.location, match.symbol);

			handle = ggGetScope(match.location);

			DPRINT_LIBS("handle=%p\n", handle);
			if (handle != NULL) break;
		}
		GG_ITER_DONE(&match);

		if (handle == NULL) continue;

		if (match.symbol == NULL) {
			nameptr = (const char *)strrchr(match.location, '/');
			if (!nameptr) {
				nameptr = match.location;
			} else {
				nameptr++;
			}

			snprintf(symname, GIC_SYMNAME_MAX+1, "%s%s",
				GIC_SYMNAME_PREFIX, nameptr);
			extptr = strchr(symname, '.');
			if (extptr) *extptr = '\0';
		} else {
			ggstrlcpy(symname, match.symbol, sizeof(symname));
		}

		DPRINT_LIBS("get symbol '%s'\n", symname);

		init = (gic_recognizerdriver *)ggFromScope(handle, symname);

		DPRINT_LIBS("init=%p\n", init);

		if (init == NULL) {
			ggFreeModule(handle);
			continue;
		}

		driver = init();
		DPRINT_LIBS("driver=%p\n", driver);
		if (driver == NULL) {
			ggFreeModule(handle);
			continue;
		}

		_gicRecognizerDriverRegister(rc, driver, handle);
	}
	GG_ITER_DONE(&target);

	return rc;
}


int gicClose(gic_handle_t hand)
{
	free(hand);
	return 0;
}


int gicInputRegister(gic_handle_t hand, gii_input_t inp)
{
	hand->input = inp;
	return 0;
}
