/*
    Copyright (C) 2008-2010 Stefan Haller

    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 3 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, see <http://www.gnu.org/licenses/>.
*/

#include <config.h>
#include <dlfcn.h>
#include "module.h"

struct library_entry * load_module(const gchar * filename)
{
	void * lib = dlopen(filename, RTLD_NOW);
	gboolean need_free = TRUE;
	struct library_entry * lib_ent = NULL;
	if (lib == NULL)
	{
		g_warning("Error while opening module: %s", dlerror());
	}
	else
	{
		const gchar * (*func_version) (void);
		func_version = dlsym(lib, "module_get_gw_version");
		if (func_version != NULL)
		{
			if (g_strcmp0((*func_version)(), VERSION) == 0)
			{
				lib_ent = g_new(struct library_entry, 1);
				lib_ent->lib = lib;
				lib_ent->filename = NULL;

				void (*init)() = dlsym(lib, "module_init");
				if (init != NULL)
					(*init)();

				lib_ent->active = FALSE;	
				lib_ent->name = dlsym(lib, "module_get_name");
				lib_ent->version = dlsym(lib, "module_get_version");
				lib_ent->description = dlsym(lib, "module_get_description");
				lib_ent->author = dlsym(lib, "module_get_author");
				lib_ent->homepage = dlsym(lib, "module_get_homepage");
				lib_ent->change_wallpaper = dlsym(lib, "module_change_wallpaper");
				lib_ent->hook_list_files = dlsym(lib, "module_hook_list_files");

				/* check basic functions */
				if ((lib_ent->name != NULL) &&
				    (lib_ent->version != NULL) &&
				    (lib_ent->description != NULL) &&
				    (lib_ent->author != NULL) &&
				    (lib_ent->homepage != NULL) &&
				    (lib_ent->change_wallpaper != NULL))
				{
					need_free = FALSE;
				}
				else
				{
					g_free(lib_ent);
					lib_ent = NULL;
				}
			}
			else
			{
				g_warning("The module \"%s\" has a wrong version! Program: " \
				          "%s  Module: %s", filename,
				          VERSION, (*func_version)());
			}
		}
		else
		{
			g_warning("Error while checking version (\"%s\"): %s",
			          filename, dlerror());
		}
	}

	if ((need_free) && (lib != NULL))
	{
		dlclose(lib);
	}

	return lib_ent;
}

