#include <nan.h>
#include "error.h"
#include "libagent.h"
#include "nodeagent.h"
#include "table.h"
#include "timer.h"
#include "transaction.h"
#include <errno.h>
#include <dlfcn.h>
#include <stdio.h>
#include <unistd.h>

Libagent::Libagent(void *handle) : handle(handle) {}

Libagent::~Libagent() {
  if (dlclose(handle) != 0)
    error_code(errno, "failed to dlclose: libagent");
};

/**
 * Return system architecture.
 *
 * TODO: only returns "x86_64".
 */
const char *Libagent::get_arch() {
  return "x86_64";
}

/**
 * Return operating system.
 *
 * TODO: only returns Linux operating systems.
 */
const char *Libagent::get_os() {
  static char command[] = "ldd --version 2>&1 | head -n1 | grep -q musl";
  int ret = system(command);
  if (WEXITSTATUS(ret) == 0)
    return "Linux-musl";
  else
    return "Linux-gnu";
}

/**
 * Load the shared object into a new `Libagent` instance or NULL if not found.
 */
Libagent *Libagent::load(const char *base) {
  const char *arch = get_arch();
  const char *os = get_os();

  static char so[PATH_MAX];
  sprintf(so, "%s/libagent/libagent-%s-%s.so", base, arch, os);

  void *handle = dlopen(so, RTLD_LAZY);
  if (handle == NULL) {
    error_code(errno, "failed to dlopen: %s", so);
    return NULL;
  }

  return new Libagent(handle);
}

NAN_MODULE_INIT(Init) {
  Agent::Init(target);
  Transaction::Init(target);
  Table::Init(target);
  Timer::Init(target);

  Nan::Set(target, Nan::New("LOG_ERROR").ToLocalChecked(), Nan::New(LIBAGENT_LOG_ERROR));
  Nan::Set(target, Nan::New("LOG_WARN").ToLocalChecked(), Nan::New(LIBAGENT_LOG_WARN));
  Nan::Set(target, Nan::New("LOG_INFO").ToLocalChecked(), Nan::New(LIBAGENT_LOG_INFO));
  Nan::Set(target, Nan::New("LOG_DEBUG").ToLocalChecked(), Nan::New(LIBAGENT_LOG_DEBUG));
  Nan::Set(target, Nan::New("LOG_TRACE").ToLocalChecked(), Nan::New(LIBAGENT_LOG_TRACE));
}

NODE_MODULE(libagent, Init)
