#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Test nested groups with umlauts in sync-mode"
## exposure: dangerous
## roles:
## - domaincontroller_master
## - domaincontroller_backup
## packages:
## - univention-s4-connector


# shellcheck source=../../lib/base.sh
. "$TESTLIBPATH/base.sh" || exit 137
# shellcheck source=../../lib/udm.sh
. "$TESTLIBPATH/udm.sh" || exit 137
# shellcheck source=../../lib/random.sh
. "$TESTLIBPATH/random.sh" || exit 137

. "s4connector.sh" || exit 137
[ -n "${connector_s4_ldap_host:-}" ] || exit 137
connector_running_on_this_host || exit 137

SYNCMODE="$(ad_get_sync_mode)"

invoke-rc.d univention-s4-connector stop

ucr set --force directory/manager/web/modules/groups/group/properties/name/syntax=string
pkill -f univention-cli-server

invoke-rc.d univention-s4-connector start

groupname1="a$(random_chars)ö1"
groupname2="a$(random_chars)ä2"

udm-test groups/group create --position "cn=groups,$ldap_base" --set name="$groupname1"

udm-test groups/group create --position "cn=groups,$ldap_base" --set name="$groupname2"

# read DN from LDAP to get the exact case
grp1_dn=$(univention-ldapsearch "cn=$groupname1" 1.1 | dn1)
grp2_dn=$(univention-ldapsearch "cn=$groupname2" 1.1 | dn1)

# Use ldapmodify, see Bug #33656
ldapmodify -x -D "cn=admin,$ldap_base" -y /etc/ldap.secret -H "ldap://${ldap_master:?}:${ldap_master_port:?}" <<EOF
dn: $grp1_dn
changetype: modify
add: uniqueMember
uniqueMember: $grp2_dn
EOF

ad_wait_for_synchronization; fail_bool 0 110

AD_GROUP_DN1="CN=$groupname1,CN=Groups,$(ad_get_base)"
AD_GROUP_DN2="CN=$groupname2,CN=Groups,$(ad_get_base)"
univention-s4search "cn=$groupname1"
univention-s4search "cn=$groupname2"

ad_verify_multi_value_attribute_contains "$AD_GROUP_DN1" "member" "$AD_GROUP_DN2"; fail_bool 0 110

udm-test groups/group remove --dn "cn=$groupname1,cn=groups,$ldap_base"
udm-test groups/group remove --dn "cn=$groupname2,cn=groups,$ldap_base"

ad_wait_for_synchronization; fail_bool 0 110

ad_exists "$AD_GROUP_DN1"; fail_bool 1 110
ad_exists "$AD_GROUP_DN2"; fail_bool 1 110

ucr unset --force directory/manager/web/modules/groups/group/properties/name/syntax
pkill -f univention-cli-server

ad_set_sync_mode "$SYNCMODE"

exit "$RETVAL"
