; ldapsearch.el
;
; v0.1
;
; Copyright 1998 Owen S. Dunn
;
; 

 (defun ldap-search (host base filter)
  "Perform an LDAP search"
  (if (fboundp 'exec-to-string)
      (exec-to-string (concat "ldapsearch -L -h " host " -b " base " '" filter "' "))
    (shell-command (concat "ldapsearch -L -h " host " -b " base " '" filter "' mail") "*LDAP Search Trace*")
    (save-excursion
      (set-buffer "*Shell Command Output*")
      (buffer-substring-no-properties (point-min) (point-max)))
))

(defun ldap-generate-result-alist (result)
  "Turn an LDIF result into an alist."
  (setq ldap-result-alist nil)
  (setq start nil)
    (while (setq start (string-match ".*: " result start))
      (setq ldap-result-alist
	    (cons (cons (substring result start (match-end 0))
			(substring result (match-end 0)
				   (string-match "\n" result (match-end 0))))
		  ldap-result-alist))
      (setq start (match-end 0))))

(defun ldapexpand ()
  (interactive)
  "Expand word at point from LDAP server"
  (setq ldap-query (ldap-search "ldap" "\"\"" (concat "(|(cn=*" (current-word) "*)(mail=*" (current-word) "*))")))
  (ldap-generate-result-alist ldap-query)
  (forward-word -1)
  (mark-word 1)
  (delete-region (point-marker) (mark-marker))
  (insert
   (concat
    (cdr (assoc "cn: " ldap-result-alist))
    " <"
    (cdr (assoc "mail: " ldap-result-alist))
    ">")

   )
)
