#!/usr/share/ucs-test/runner bash
## desc: univention-admingrp-user-passwordreset (ldapdiff)
## roles:
##  - domaincontroller_master
##  - domaincontroller_backup
## packages:
##  - univention-admingrp-user-passwordreset
## exposure: dangerous


. "$TESTLIBPATH/base.sh" || exit 137
. "$TESTLIBPATH/user.sh" || exit 137
. "$TESTLIBPATH/group.sh" || exit 137
. "$TESTLIBPATH/maildomain.sh" || exit 137
. "$TESTLIBPATH/ucr.sh" || exit 137
. "$TESTLIBPATH/undo.sh" || exit 137
. "$TESTLIBPATH/samba.sh" || exit 137

create_mail_domain "$domainname" && undo delete_mail_domain "$domainname"

# create helpdesk group
G_HELPDESK=$(group_randomname)
group_create "$G_HELPDESK" &&
	undo group_remove "$G_HELPDESK" ||
	fail_fast 140 "cannot create G_HELPDESK group $G_HELPDESK"
# create new user
U_HELPDESK=$(user_randomname)
user_create "$U_HELPDESK" &&
	undo user_remove "$U_HELPDESK" ||
	fail_fast 140 "cannot create U_HELPDESK user $U_HELPDESK"

# add user to corresponding group
udm-test groups/group modify \
	--dn "$(group_dn "$G_HELPDESK")" \
	--append users="$(user_dn "$U_HELPDESK")"

# create new protected test user
U_PROT=$(user_randomname)
user_create "$U_PROT" &&
	undo user_remove "$U_PROT" ||
	fail_fast 140 "cannot create U_PROT user $U_PROT"

wait_for_LDAP_replication_of_domain_sambaSid "$U_PROT"

tmpdir=$(mktemp -d)
undo rm -rf "$tmpdir"
LDIF_ANON_A="$tmpdir/anon_a.ldif"
LDIF_ANON_B="$tmpdir/anon_b.ldif"
LDIF_ADMIN_A="$tmpdir/admin_a.ldif"
LDIF_ADMIN_B="$tmpdir/admin_b.ldif"

# backup
undo /etc/init.d/slapd crestart # reversed order
undo ucr_restore

# deactivate LDAP ACL
if [ -n "$(ucr dump | grep ^ldap/acl/user/passwordreset/accesslist/groups | cut -d: -f1)" ] ; then
	ucr unset $(ucr dump | grep ^ldap/acl/user/passwordreset/accesslist/groups | cut -d: -f1)
fi
/etc/init.d/slapd restart

# dump ldapq
echo "==> Dumping LDAP without active ACL"
ldapsearch -xLLL >"$LDIF_ANON_A"
ldapsearch -xLLL -D "cn=admin,$ldap_base" -y /etc/ldap.secret >"$LDIF_ADMIN_A"

# activate LDAP ACL
ucr set ldap/acl/user/passwordreset/accesslist/groups/dn="$(group_dn "$G_HELPDESK")" \
	ldap/acl/user/passwordreset/protected/uid="Administrator,$U_PROT"
/etc/init.d/slapd restart

# dump ldap
echo "==> Dumping LDAP with active ACL"
ldapsearch -xLLL >"$LDIF_ANON_B"
ldapsearch -xLLL -D "cn=admin,$ldap_base" -y /etc/ldap.secret >"$LDIF_ADMIN_B"

echo "==> Comparing output"
if ! ldiff "$LDIF_ANON_A" "$LDIF_ANON_B" ; then
	fail_test 1 "==> ERROR: anonymous LDAP dump differs"
fi

if ! ldiff "$LDIF_ADMIN_A" "$LDIF_ADMIN_B" ; then
	fail_test 1 "==> ERROR: admin LDAP dump differs"
fi

exit "$RETVAL"
