#!/bin/sh
#
# List mail addresses found under base DN $1 (defaults to dc=ungleich,dc=ch)

set -e

# Hardcoded parameters.
LDAP_SERVER="ldaps://ldap1.ungleich.ch"
LDAP_BIND_DN="cn=manager,dc=ungleich,dc=ch"

if [ "$1" != "" ]; then
	LDAP_SEARCH_BASE="$1"
else
	LDAP_SEARCH_BASE="dc=ungleich,dc=ch"
fi

# Read secrets from environment.
if [ "$LDAP_BIND_PASSWD" = "" ]; then
	echo "You have to define LDAP_BIND_PASSWD before launching this script." >&2
	exit 1
fi

# Extract mail addresses from LDAP directory.
ldap_search_result="$(
	ldapsearch -x -H "$LDAP_SERVER" \
		-D "$LDAP_BIND_DN" \
		-w "$LDAP_BIND_PASSWD" \
		-b "$LDAP_SEARCH_BASE" mail
	)"

echo "$ldap_search_result" | grep 'mail:' | cut -d ' ' -f 2 -