#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Check whether container can be recursively removed 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


#                 Container3
#                /
#      Container1--User
#     /
# Base

# shall become

# Base

RETRYREJECTED="$(ucr get connector/ad/retryrejected)"
ad_set_retry_rejected 2

CONTAINER1="$(random_chars)1"
AD_CONTAINER1_DN="CN=$CONTAINER1,$(ad_get_base)"
CONTAINER3="$(random_chars)3"
AD_CONTAINER3_DN="CN=$CONTAINER3,CN=$CONTAINER1,$(ad_get_base)"
USER="$(random_chars)"
AD_USER_DN="CN=$USER,CN=$CONTAINER1,$(ad_get_base)"
UDM_users_user_username="$USER"
UDM_users_user_lastname="$(random_chars)"
# If the password doesn't adhere the configured Windows-Password-Guidelines
# weird things might happen when the user is synced to AD.
UDM_users_user_password="U$(random_chars)123"

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

section "Create initial Tree structure"

UDM_container_cn_name="$CONTAINER1"
udm_create "container/cn" || fail_test 110
UDM_container_cn_name="$CONTAINER3"
udm_create "container/cn" "" "" "cn=$CONTAINER1,$ldap_base" || fail_test 110
UDM_users_user_username="$USER"
udm_create "users/user" "" "" "cn=$CONTAINER1,$ldap_base" || fail_test 110

ad_wait_for_synchronization; fail_bool 0 110

UDM_container_cn_name="$CONTAINER1"
udm_exists "container/cn"; fail_bool 0 110
ad_exists "$AD_CONTAINER1_DN"; fail_bool 0 110
UDM_container_cn_name="$CONTAINER3"
udm_exists "container/cn" "" "" "cn=$CONTAINER1,$ldap_base"; fail_bool 0 110
ad_exists "$AD_CONTAINER3_DN"; fail_bool 0 110
udm_exists "users/user" "" "" "cn=$CONTAINER1,$ldap_base"; fail_bool 0 110

section "Recursively remove $CONTAINER1"

UDM_container_cn_name="$CONTAINER1"
udm_remove "container/cn" || fail_test 110

ad_wait_for_synchronization; fail_bool 0 110

UDM_container_cn_name="$CONTAINER1"
udm_exists "container/cn"; fail_bool 1 110
ad_exists "$AD_CONTAINER1_DN"; fail_bool 1 110
UDM_container_cn_name="$CONTAINER3"
udm_exists "container/cn" "" "" "cn=$CONTAINER1,$ldap_base"; fail_bool 1 110
ad_exists "$AD_CONTAINER3_DN"; fail_bool 1 110
udm_exists "users/user" "" "" "cn=$CONTAINER1,$ldap_base"; fail_bool 1 110

ad_set_retry_rejected "$RETRYREJECTED"
ad_set_sync_mode "$SYNCMODE"

exit "$RETVAL"
