#!/bin/sh

postprocess() {
	test -z "$*" && cat && return
	awk -F '::* ' 'BEGIN { fcount=split("'"$*"'", fields, " "); }
		/^#/ { next; }
		NF>=2 { obj[$1] = obj[$1] ? obj[$1] ";" $2 : $2; next; }
		NF==0 {
			if (! "dn" in obj) next;
			line=obj[fields[1]];
			for(i = 2; i <= fcount; i++)
				line = line "|" obj[fields[i]];
			if (line !~ /^\|*$/) print line;
			delete obj; next; }
		1'
}

LDAPCMD=ldapsearch
if test -n "$SSHPROXY"; then
	LDAPCMD="ssh -t $SSHPROXY $LDAPCMD"
else
	LDAPCMD="eval $LDAPCMD"
fi
test -z "$BINDURL" && echo "Define BINDURL in environment" 1>&2 && exit 1
test -z "$BASEDN" && echo "Define BASEDN in environment" 1>&2 && exit 1
test -n "$LDAPUSER" && BINDDN="uid=$LDAPUSER,ou=Users,$BASEDN"
test -z "$BINDDN" && echo "Define BINDDN in environment" 1>&2 && exit 1
test -z "$SEARCHBASE" && SEARCHBASE="$BASEDN"
if test -z "$BINDPW"; then
	PW="-W"
else
	PW="-w$BINDPW"
fi
FILTER="$1"; shift
echo "$FILTER" | grep -q '=' || FILTER="cn=*$FILTER*"

$LDAPCMD -x -H "'$BINDURL'" -D "'$BINDDN'" "'$PW'" -b "'$SEARCHBASE'" \
	"'($FILTER)'" "$@" \
  | perl -MMIME::Base64 -n -00 -e 's/\r//g;s/\n //g;
	s/(?<=:: )(\S+)/quotemeta(decode_base64($1))/eg;
	s/(\\[\n\r])+/\\\\n/g;
	s/\\(.)/\1/g;print' \
  | postprocess "$@"

