#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>


#include <lber.h>
#include <ldap.h>

int main( int argc, char *argv[] ) {
  LDAP *ld;
  int res;
  LDAPMessage *ldap_message_set, *ldap_one_message;
  char *attributes[4] = {"sn",
			 "ou",
			 "title",
			 NULL};

  char *attribute;
  char **values;
  BerElement *ber_element_ptr;
  int i;

  int  authmethod = LDAP_AUTH_SIMPLE;
  
  char *ldap_host = "localhost";

  char *user_dn = "cn=root, o=stixen.co.uk, c=uk";
  char *user_pw = "secret";
  
  char *base_dn = "o=stixen.co.uk, c=uk";
  char *filter = "(objectClass=Person)";


  if ((ld = ldap_init(ldap_host, LDAP_PORT)) == NULL ) {
    perror( "Failure of ldap_init" );
    exit( EXIT_FAILURE );
  }

  if (ldap_bind_s(ld, user_dn, user_pw, authmethod) != LDAP_SUCCESS ) {
    ldap_perror( ld, "Failure of ldap_bind" );
    exit( EXIT_FAILURE );
  }
  
  res = ldap_search_s(ld, base_dn, LDAP_SCOPE_SUBTREE, filter, attributes, 0, &ldap_message_set);
  if (res != LDAP_SUCCESS) {
    ldap_perror( ld, "Failure of ldap_search_s" );
    exit( EXIT_FAILURE );
  }

  printf("There were %d objects found\n", ldap_count_entries(ld, ldap_message_set));

  res = ldap_sort_entries(ld, &ldap_message_set, "sn", strcmp);
  if (res != LDAP_SUCCESS) {
    ldap_perror( ld, "Failure of ldap_sort_entries" );
  }


  ldap_one_message = ldap_first_entry(ld, ldap_message_set);
  while (ldap_one_message) {
    char *dn_str;
    dn_str = ldap_get_dn(ld, ldap_one_message);
    printf("Found DN %s\n", dn_str);
    free(dn_str);

    attribute = ldap_first_attribute(ld, ldap_one_message, &ber_element_ptr);

    while (attribute != NULL) {
      if ((values = ldap_get_values(ld, ldap_one_message, attribute)) != NULL) {
	for (i=0; values[i] != NULL; i++) {
	  printf("%s: %s\n", attribute, values[i]);
	}
	ldap_value_free(values);
      }
      attribute = ldap_next_attribute(ld, ldap_one_message, ber_element_ptr);
    }

    ldap_one_message = ldap_next_entry(ld, ldap_one_message);
    printf("\n");
  }
  (void)ldap_msgfree(ldap_message_set);
  
  res = ldap_unbind_s(ld);
  if (res != 0) {
    fprintf(stderr, "ldap_unbind_s failed: %s\n", ldap_err2string(res));
    exit( EXIT_FAILURE );
  }

  return EXIT_SUCCESS;
} /* main */








