#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Create an UCS-User and change its name in sync-mode"
## exposure: dangerous
## 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
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"
UDM_users_user_firstname="$(random_chars)"
UDM_groups_group_name="$(random_chars)"
AD_USER_DN="CN=$UDM_users_user_username,CN=Users,$(ad_get_base)"
AD_GROUP_DN="CN=$UDM_groups_group_name,CN=groups,$(ad_get_base)"
UDM_GROUP_DN="cn=$UDM_groups_group_name,cn=groups,$ldap_base"

SYNCMODE="$(ad_get_sync_mode)"

ad_set_sync_mode "sync"

udm_create "users/user" || fail_test 110
udm_create "groups/group" || fail_test 110
udm_modify "users/user" "" "" "" "" \
	--append groups="$UDM_GROUP_DN" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

OTHER_USER_NAME="$(random_chars)other"
udm_modify "users/user" "" "" "" "" \
	--set username="$OTHER_USER_NAME" || fail_test 110
UDM_users_user_username="$OTHER_USER_NAME"
AD_USER_DN="CN=$UDM_users_user_username,CN=Users,$(ad_get_base)"
ad_wait_for_synchronization; fail_bool 0 110

udm_verify_udm_attribute "username" "$UDM_users_user_username" "users/user"; fail_bool 0 110
ad_verify_attribute	"$AD_USER_DN" "sAMAccountName" "$UDM_users_user_username"; fail_bool 0 110

udm_verify_multi_value_udm_attribute_contains "users" \
	"uid=$UDM_users_user_username,cn=users,$ldap_base" "groups/group"; fail_bool 0 110
udm_verify_multi_value_udm_attribute_contains "groups" \
	"cn=$UDM_groups_group_name,cn=groups,$ldap_base" "users/user"; fail_bool 0 110
ad_verify_multi_value_attribute_contains "$AD_GROUP_DN" "member" "$AD_USER_DN"; fail_bool 0 110
ad_verify_multi_value_attribute_contains "$AD_USER_DN" "memberOf" "$AD_GROUP_DN"; fail_bool 0 110

section "Clean up"

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

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

ad_set_sync_mode "$SYNCMODE"

exit "$RETVAL"
