#!/bin/bash

# ucr set connector/s4/mapping/gpo/ntsd=yes
# service univention-s4-connector restart
# samba-tool gpo create gpo1 -UAdministrator%univention

ldif=$(ldbsearch -H /var/lib/samba/private/sam.ldb '(&(objectClass=groupPolicyContainer)(displayName=gpo1))' nTSecurityDescriptor 2>/dev/null | ldapsearch-wrapper)

dn=$(sed -n 's/^dn: //p' <<<"$ldif")
ntsd_orig=$(sed -n 's/^nTSecurityDescriptor: //p' <<<"$ldif")
ntsd_mod1="$ntsd_orig(A;CI;RPLCLORC;;;DU)"
ntsd_mod2="$ntsd_orig(A;CI;RPLCLORC;;;DU)(A;CI;RPLCLORC;;;PA)"


tail -f /var/log/univention/connector-s4.log &
tail_pid=$!
cleanup() {
	kill "$tail_pid"
}

trap cleanup EXIT

eval "$(ucr shell connector/s4/poll/sleep)"

for run in $(seq 25 -2 5); do
	delay=$(python -c "print 0.1*$run")

	echo "Change NTSD"
	ldbmodify -H /var/lib/samba/private/sam.ldb >/dev/null 2>&1 <<-%EOF
	dn: $dn
	changetype: modify
	replace: nTSecurityDescriptor
	nTSecurityDescriptor: $ntsd_mod1
	%EOF

	# ldif=$(ldbsearch -H /var/lib/samba/private/sam.ldb '(&(objectClass=groupPolicyContainer)(displayName=gpo1))' nTSecurityDescriptor 2>/dev/null | ldapsearch-wrapper)
	# ntsd1=$(sed -n 's/^nTSecurityDescriptor: //p' <<<"$ldif")

	echo "Wait $delay"
	sleep $delay

	echo "Change NTSD again"
	ldbmodify -H /var/lib/samba/private/sam.ldb >/dev/null 2>&1 <<-%EOF
	dn: $dn
	changetype: modify
	replace: nTSecurityDescriptor
	nTSecurityDescriptor: $ntsd_mod2
	%EOF

	# ldif=$(ldbsearch -H /var/lib/samba/private/sam.ldb '(&(objectClass=groupPolicyContainer)(displayName=gpo1))' nTSecurityDescriptor 2>/dev/null | ldapsearch-wrapper)
	# ntsd2=$(sed -n 's/^nTSecurityDescriptor: //p' <<<"$ldif")

	echo "Wait $delay"
	sleep $delay


	echo "Change NTSD back"
	ldbmodify -H /var/lib/samba/private/sam.ldb >/dev/null 2>&1 <<-%EOF
	dn: $dn
	changetype: modify
	replace: nTSecurityDescriptor
	nTSecurityDescriptor: $ntsd_orig
	%EOF

	sleep $(($connector_s4_poll_sleep * 2))
	ldif=$(ldbsearch -H /var/lib/samba/private/sam.ldb '(&(objectClass=groupPolicyContainer)(displayName=gpo1))' nTSecurityDescriptor 2>/dev/null | ldapsearch-wrapper)
	ntsd3=$(sed -n 's/^nTSecurityDescriptor: //p' <<<"$ldif")

	if [ "$ntsd3" != "$ntsd_orig" ]; then
		echo FAIL
		exit 1
	fi
done

