#include "nameserver.h"
#include <iostream>
#include <pwd.h>

std::string NameServer::get_name (uint32_t id) {
  std::map<std::string, uint32_t>::iterator it;
  for(it = cache.begin(); it != cache.end(); it++) {
    if(it->second == id) return it->first;
  }
  struct passwd* pwd = getpwuid(id);
  if (!pwd) {
    return "???";
  }
  cache[pwd->pw_name] = id;
  std::cerr << "Did reverse LDAP lookup on " << pwd->pw_name << "\n";
  return pwd->pw_name;
}

uint32_t NameServer::get_id (std::string name) {
  std::map<std::string, uint32_t>::iterator it = cache.find(name);

  if(it != cache.end())
    return it->second;

  std::cerr << "Doing LDAP lookup for \"" << name << "\".\n";
  struct passwd* pwd = getpwnam(name.c_str());
  if(!pwd) {
    // TODO: oh fuck???
    return 0;
  }

  cache[name] = pwd->pw_uid;
  return cache[name];
}

NameServer ns;
