#include <lua.h>                               
#include <lauxlib.h>                           
#include <lualib.h>

#include <stdio.h>
#include <dlfcn.h>

#include <unistd.h>

typedef void Register(lua_State*);

int load_as_global (lua_State *L){
	const char* libpath = lua_tostring(L, 1);
	void* lib;
	lib = dlopen(libpath,  RTLD_NOW | RTLD_GLOBAL/* | RTLD_DEEPBIND*/);
	if(!lib)
        {
                lua_pushnil(L);
		lua_pushstring(L, (const char*)dlerror());
                return 2;
        }
	
	const char* openFunctionName = lua_tostring(L, 2);
	Register* loadFunc = (Register*)dlsym(lib, openFunctionName);
	if(!loadFunc)
        {
                lua_pushnil(L);
                lua_pushstring(L, (const char*)dlerror());
                return 2;
        }
        loadFunc(L);
	lua_pushboolean(L, 1);
        return 1;
}

int luaopen_genericloader (lua_State *L){
/*
        void* lib;

	lib = dlopen("/home/msv/ericaflr/sga-slurm/drmaa.so", RTLD_LAZY | RTLD_GLOBAL | RTLD_DEEPBIND);
	if(!lib)
	{
        	printf("%s\n", dlerror());
		return 1;
	}
	Register* loadFunc = (Register*)dlsym(lib, "luaopen_drmaa");
	if(!loadFunc)
        {
        	printf("%s\n", dlerror());
		return 1;
	}
	loadFunc(L);
	return 0;
*/
	lua_register(L, "load_as_global", load_as_global);
}
