#!/bin/bash

eval "$(ucr shell)"

if [ "$connector_debug_level" != 4 ]; then
	ucr set connector/debug/level='4'; /etc/init.d/univention-s4-connector restart; sleep 5;
fi

## Prepare test fixture
lastUidNumber=$(univention-ldapsearch '(&(objectClass=univentionLastUsed)(cn=uidNumber))' univentionLastUsedValue | sed -n 's/^univentionLastUsedValue: //p')

groupdn=$(univention-ldapsearch -LLL -o ldif-wrap=no '(&(cn=group1)(objectClass=univentionGroup))' entryDN | sed -n 's/^entryDN: //p')
if [ -z "$groupdn" ]; then
	groupdn=$(udm groups/group create --set name=group1 | sed -n 's/^Object created: //p')
fi

position1="cn=groups,$ldap_base"
position2="cn=users,$ldap_base"
domain_users="cn=Domain Users,cn=groups,$ldap_base"

## Create and move a user and then greate another user to make the S4-Connector update the additional group ("Domain Users") again:
uid1="user$((lastUidNumber + 1))"
uid2="user$((lastUidNumber + 2))"
udm users/user create --position "$position1" --set username="$uid1" --set lastname=last1 --set password=univention --set primaryGroup="$groupdn" --set groups="$domain_users"
udm users/user move --dn uid="$uid1","$position1" --position "$position2"
udm users/user create --position "$position2" --set username="$uid2" --set lastname=last2 --set password=univention --set primaryGroup="$groupdn" --set groups="$domain_users"
sleep 5

## Assert there are no rejects:
if univention-s4connector-list-rejected | grep -q "UCS DN: cn=Domain Users"; then
	echo "ERROR: Rejects for  cn=Domain Users after moving $uid1"
	exit 1
fi

echo "Sleeping a bit"
sleep 10

echo "And trying it again wth two new users"
## And do it again with two new users
uid1="user$((lastUidNumber + 3))"
uid2="user$((lastUidNumber + 4))"
udm users/user create --position "$position1" --set username="$uid1" --set lastname=last1 --set password=univention --set primaryGroup="$groupdn" --set groups="$domain_users"
udm users/user move --dn uid="$uid1","$position1" --position "$position2"
udm users/user create --position "$position2" --set username="$uid2" --set lastname=last2 --set password=univention --set primaryGroup="$groupdn" --set groups="$domain_users"
sleep 5

## Assert there are no rejects:
if univention-s4connector-list-rejected | grep -q "UCS DN: cn=Domain Users"; then
	echo "ERROR: Rejects for  cn=Domain Users after moving $uid1"
	exit 1
fi
