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


static int l_openshlib(lua_State *L) {
	char errbuf[2000];
	void *shlib_handle= dlopen(lua_tostring(L,-1), RTLD_NOW);
	if (!shlib_handle) {
		snprintf(errbuf,sizeof(errbuf),"opening libluaodbc.so: %s\n",dlerror());
		goto err_openlib;
	}
	{
		void (*initf)(lua_State *L);
		initf= dlsym(shlib_handle,"luashlib_entry");
		if (!initf) {
			snprintf(errbuf,sizeof(errbuf),"can't find luashlib_entry in libluaodbc.so\n");
			goto err_entry;
		}
		(*initf)(L);
	}
	lua_pushnumber(L,1);
	return 1;
err_entry:
	dlclose(shlib_handle);
err_openlib:
	lua_pushnil(L);
	lua_pushstring(L,errbuf);
	return 2;
}


int main(int argc,char **argv) {
	lua_State *Lua= lua_open();
	luaopen_base(Lua);
	luaopen_io(Lua);
	luaopen_string(Lua);
	luaopen_table(Lua);

	lua_register(Lua, "open_sh_lib", l_openshlib);

	if (!luaL_loadfile(Lua,argv[1])) {
		if (lua_pcall(Lua,0,0,0))
			fprintf(stderr,"error in lua code: %s\n",lua_tostring(Lua,-1));
	} else
		fprintf(stderr,"error loading %s: %s\n",argv[1],lua_tostring(Lua,-1));
	return 0;
}
