#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <aa0client.h>
#include "ldap.h"


LDAP * ldap_open(const char *host, int port)
{
  LDAP * ld = (void*) malloc(sizeof(*ld));
  ld->dummy = NULL;
  return ld;
}

int ldap_simple_bind_s(LDAP *ld, char *binddn, char *passwd)
{
  if (aa_locate(binddn, (void*)&ld->dummy, "QUERY", 0) == 0) {
    return -1;
  }
  aa0clearerror(ld->dummy);
  return LDAP_SUCCESS;
}

int ldap_search_s(LDAP *ld, char *base, int scope,
		  char *filter, char **attrs, int attrsonly,
		  LDAPMessage **msgp)
{
  int rc;
  char aa0result[9000];
  LDAPMessage *msg;

  rc = aa0get(ld->dummy, filter, aa0result);
  if (rc != AA0RET_OK && rc != AA0RET_NODATA) {
    return -1;
  }
  *msgp = NULL;
  if (rc == AA0RET_NODATA)
    return LDAP_SUCCESS;

  msg = malloc(sizeof(*msg));
  msg->result = strdup(aa0result);
  *msgp = msg;
  return LDAP_SUCCESS;
}

LDAPMessage * ldap_first_entry __((LDAP *ld, LDAPMessage *msg))
{
  return msg;
}

char ** ldap_get_values __((LDAP *ld, LDAPMessage *entry, char *attr))
{
  char **ss;
  if (!entry || !entry->result) return NULL;
  ss = malloc(sizeof(char*));
  ss[0] = entry->result;
  return ss;
}

void ldap_value_free(char **vals)
{
  free(vals);
}

void ldap_msgfree(LDAPMessage *msg)
{
  if (msg && msg->result)
    free(msg->result);
  free(msg);
}

void ldap_unbind_s(LDAP *ld)
{
  if (ld && ld->dummy)
    aa0close(ld->dummy);
  free(ld);
}

