#include "CModule.h"

CModule::CModule (CBot *bot, c_char file) : filename (file, PATH_MAX), b (bot)
{
  initialized = 0;
  handle = NULL;
  module = NULL;

  if (filename[0] == '/')		// if an absolute path was specified
    handle = dlopen (filename, RTLD_LAZY);
  else					// else build it
    {
      char *cwd = getcwd (NULL, PATH_MAX);
      if (cwd == NULL)
        return;
      size_t len = strlen (cwd) + filename.getlen () + 10;
      char *path = (char *)my_malloc (len+1);
      snprintf (path, len, "%s/%s", cwd, (char *)filename);
      free (cwd);
      handle = dlopen (path, RTLD_LAZY);
      free (path);
    }
  if (handle == NULL)
    {
      b->write_botlog ("ERROR: dlopen() returned: %s", dlerror ());
      return;
    }
  module = (struct module_type *)dlsym (handle, "module");
  if (module == NULL)
    {
      module = (struct module_type *)dlsym (handle, "_module");
      if (module == NULL)
        {
          b->write_botlog ("ERROR: dlsym() returned: %s", dlerror ());
          return;
        }
    }
  if (module->version != MODULE_VERSION)
    {
      b->write_botlog ("ERROR: module was compiled with another version of mbot, recompile it");
      return;
    }

  if (module->start != NULL)
    module->start (this);

  initialized = 1;
}

CModule::~CModule (void)
{
  if (module != NULL)
    if (module->stop != NULL)
      module->stop (this);
  if (handle != NULL)
    dlclose (handle);
}

