#!/bin/sh -e

. shell-error
. /etc/cl-user.conf

[ "$#" -eq 1 ] || fatal "more arguments required"
db="$1"; shift

[ -n "$bindpw" ] && bindpw="-w $bindpw" || bindpw="-W"

if [ "$bindpw" = "-W" ]; then
	echo -n "Enter LDAP Password: "
	read -es passwd
	echo
	bindpw="-w '$passwd'"
fi

ldap_search_groups()
{
	local key
	local value
	local cn
	local gid
	local found
	
	ldapsearch -b "$base" -D "$binddn" $bindpw -x -H "ldap://${host:-localhost}" "objectClass=posixGroup" cn gidNumber | \
		while read key value; do
			if [ "$key" = "dn:" -o "$key" = "result:" ]; then
				if [ ! -z "$found" ]; then
					[ -n "$cn" -a -n "$gid" ] && echo "$cn:x:$gid:"
					cn=
					gid=
				fi
				found=1
			fi
			[ "$key" = "cn:" ] && cn="$value"
			[ "$key" = "gidNumber:" ] && gid="$value"
		done
}

ldap_search_group_users()
{
	local key
	local value
	local list
	local found
	local gid="$1"	
	
	ldapsearch -b "$base" -D "$binddn" $bindpw -x -H "ldap://${host:-localhost}" "(&(objectClass=posixGroup)(gidNumber=$gid))" memberUid | \
		while read key value; do
			if [ "$key" = "dn:" -o "$key" = "result:" ]; then
				if [ ! -z "$found" ]; then
					[ -n "$list" ] && echo "$list"
					list=
				fi
				found=1
			fi
			if [ "$key" = "memberUid:" ]; then
				if [ -n "$list" ]; then
					list="$list,$value"
				else
					list="$value"
				fi
			fi
		done
}

ldap_search_users()
{
	local key
	local value
	local cn
	local gid
	local found

	ldapsearch -b "$base" -D "$binddn" $bindpw -x -H "ldap://${host:-localhost}" "objectClass=posixAccount" cn  userPassword uidNumber gidNumber homeDirectory loginShell uid | \
		while read key value; do
			if [ "$key" = "dn:" -o "$key" = "result:" ]; then
				if [ ! -z "$found" ]; then
					echo "$userid:x:$uid:$gid:$cn:$home:$shell"
					userid=
					uid=
					gid=
					cn=
					home=
					shell=
				fi
				found=1
			fi
			[ "$key" = "uid:" ] && userid="$value"
			[ "$key" = "uidNumber:" ] && uid="$value"
			[ "$key" = "gidNumber:" ] && gid="$value"
			[ "$key" = "cn:" ] && cn="$value"
			[ "$key" = "homeDirectory:" ] && home="$value"
			[ "$key" = "loginShell:" ] && shell="$value"
		done
}

case "$db" in
		"group")
			ldap_search_groups | \
				while IFS=: read cn x gid tail; do
					echo -n "$cn:$x:$gid:"
					users="$(ldap_search_group_users $gid)"
					echo "$users"
				done
			break;;
		"passwd")
			ldap_search_users
			break;;
esac

