#!/usr/share/ucs-test/runner bash 
# shellcheck shell=bash
## desc: "Move an UCS-user into the User-Ignore-Subtree in write-mode"
## exposure: dangerous
## packages:
## - univention-s4-connector
## versions:
##  3.0-0: skip
## bugs:
##  - 18504

# 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
test -n "$connector_s4_ldap_host" || exit 137
connector_running_on_this_host || exit 137

UDM_users_user_username="$(random_chars)"
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"
AD_USER_DN="CN=$UDM_users_user_username,CN=Users,$(ad_get_base)"

SYNCMODE="$(ad_get_sync_mode)"

ad_set_sync_mode "write"

section "Create new container"

CONTAINER_NAME="$(random_chars)"
udm container/cn create --set name="$CONTAINER_NAME" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

section "Modify User-Ignore-Subtree"

invoke-rc.d univention-s4-connector stop



connector_mapping_adjust 'user' "cn=$CONTAINER_NAME,$ldap_base"

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

section "Create user"

udm_create "users/user" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

udm_exists "users/user"; fail_bool 0 110
ad_exists "$AD_USER_DN"; fail_bool 0 110

section "Move user to ignored subtree"

udm users/user move --dn "uid=$UDM_users_user_username,cn=users,$ldap_base" \
	--position "cn=$CONTAINER_NAME,$ldap_base" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

udm_exists "users/user"; fail_bool 1 110
udm_exists "users/user" "" "" "cn=$CONTAINER_NAME,$ldap_base"; fail_bool 0 110
ad_exists "CN=$UDM_users_user_username,CN=$CONTAINER_NAME,$(ad_get_base)"; fail_bool 1 110
ad_exists "$AD_USER_DN"; fail_bool 1 121 "See #18504"

section "Clean up"

udm_remove "users/user" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

ad_exists "$AD_USER_DN"; fail_bool 1 110
udm_exists "users/user"; fail_bool 1 110

udm container/cn remove --dn "cn=$CONTAINER_NAME,$ldap_base"

invoke-rc.d univention-s4-connector stop
connector_mapping_restore
ad_set_sync_mode "$SYNCMODE"
invoke-rc.d univention-s4-connector start

exit "$RETVAL"
