#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Check whether the OU-Ignore-Subtree is respected on ucs-side in sync-mode"
## exposure: dangerous
## packages:
## - univention-ad-connector
## tags:
##  - skip_admember

# 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

. "adconnector.sh" || exit 137
test -n "$connector_ad_ldap_host" || exit 137


OU1="$(random_chars)"
OU2="$(random_chars)"

SYNCMODE="$(ad_get_sync_mode)"
ad_set_sync_mode "sync"

UDM_container_ou_name="$OU1"
AD_OU_DN="OU=$UDM_container_ou_name,$(ad_get_base)"
udm_create "container/ou" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

udm_exists "container/ou"; fail_bool 0 110
ad_exists "$AD_OU_DN"; fail_bool 0 110

section "Modify OU-Ignore-Subtree"

invoke-rc.d univention-ad-connector stop

connector_mapping_adjust 'ou' "ou=$OU1,$ldap_base"

ad_set_sync_mode "sync"
invoke-rc.d univention-ad-connector start

section "Create ou"
UDM_container_ou_name="$OU2"
AD_OU_DN="OU=$UDM_container_ou_name,OU=$OU1,$(ad_get_base)"

udm_create "container/ou" "" "" "ou=$OU1,$ldap_base" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

udm_exists  "container/ou" "" "" "ou=$OU1,$ldap_base"; fail_bool 0 110
ad_exists "$AD_OU_DN"; fail_bool 1 110

section "Clean up"

udm_remove "container/ou" "" "" "ou=$OU1,$ldap_base" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

ad_exists "$AD_OU_DN"; fail_bool 1 110
udm_exists  "container/ou" "" "" "ou=$OU1,$ldap_base"; fail_bool 1 110

invoke-rc.d univention-ad-connector stop
connector_mapping_restore
ad_set_sync_mode "sync"
invoke-rc.d univention-ad-connector start

UDM_container_ou_name="$OU1"
AD_OU_DN="OU=$UDM_container_ou_name,$(ad_get_base)"
udm_remove "container/ou" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

ad_exists "$AD_OU_DN"; fail_bool 1 110
udm_exists  "container/ou"; fail_bool 1 110

ad_set_sync_mode "$SYNCMODE"

exit "$RETVAL"
