#!/bin/sh -e

. cl-config

[ "$#" -ge 1 ] || fatal "more arguments required"
config="$1"
shift

if [ -n "$1" ]; then
	filter="(&(objectClass=posixAccount)(uid=$1))"
else
	filter="objectClass=posixAccount"
fi

cl_slapd_config "$config"

base64=0
ldapsearch -b "$base" -x "$filter" cn userPassword uidNumber gidNumber homeDirectory loginShell uid | \
		while IFS=':' read key value tail; do
				# skip comments
				[ "${key#\#}" = "$key" ] || continue
				# append line continue
				if [ "${key#[[:space:]]}" != "$key" ]; then
					string="$string$key"
				else
					# decode string if base64 detected
					[ $base64 -eq 0 ] || string="$(echo $string|base64 -d -i)"
					# set getent fields
					case "$attribute" in
						uid) user="$string" ;;
						uidNumber) uid="$string" ;;
						gidNumber) gid="$string" ;;
						cn) gecos="$string" ;;
						homeDirectory) home="$string" ;;
						loginShell) shell="$string" ;;
						# print the entry on new one begining or on the command end
						dn|result)
							[ -z "$user" -o -z "$uid" -o -z "$gid" ] || \
								echo "$user:x:$uid:$gid:$gecos:$home:$shell"
							;;
						*)
					esac
					# get the attribute name
					attribute="$key"
					# detect base64 by two colons ::
					# remove leading space from attribute value
					if [ "$value" = "" ]; then
						string="${tail#[[:space:]]}"
						base64=1
					else
						string="${value#[[:space:]]}"
						base64=0
					fi
				fi
		done
