#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: Checking whether failed.ldif is created with right permissions.
## tags:
##  - replication
## roles:
##  - domaincontroller_backup
##  - domaincontroller_slave
## packages:
##  - univention-config
##  - univention-directory-manager-tools
##  - ldap-utils
## exposure: dangerous

# shellcheck source=../../lib/base.sh
. "$TESTLIBPATH/base.sh" || exit 137
# shellcheck source=../../lib/ucr.sh
. "$TESTLIBPATH/ucr.sh" || exit 137
# shellcheck source=../../lib/undo.sh
. "$TESTLIBPATH/undo.sh" || exit 137

undo ucr_restore
ucr set listener/ldap/retries=0
ucr set	replication/ldap/retries=0
undo systemctl restart univention-directory-listener
systemctl restart univention-directory-listener

testldif () {
	[ -f "$1" ] || return

	declare -i PERM="$(stat -c %a "$1")"
	local OWNER="$(stat -c %U "$1")"
	declare -i GROUP_PERM="${PERM:1:1}"
	declare -i OTHERS_PERM="${PERM:2:1}"

	[ "$GROUP_PERM" -eq 0 ] ||
		fail_test 1 "File '$1' has group permissions: $PERM"
	[ "$OTHERS_PERM" -eq 0 ] ||
		fail_test 1 "File '$1' has world permissions: $PERM"
	[ "$OWNER" = "root" ] ||
		[ "$OWNER" = "listener" ] ||
		fail_test 1 "File '$1' not owned by root or listener: $OWNER"
}

#check if master ldap-server can be reached
univention-ldapsearch -H "ldap://$ldap_master:$ldap_master_port" uid=Administrator |
	grep -q "# numEntries: 1" ||
	exit 120

wait_for_replication

#START TEST
ldif_path="/var/lib/univention-directory-replication"
ldif="$ldif_path/failed.ldif"

/etc/init.d/slapd stop

# modify $server_role to create failed.ldif file (because slapd is off)
univention-directory-manager "computers/$server_role" modify \
	--binddn "$ldap_hostdn" \
	--bindpwdfile "/etc/machine.secret" \
	--dn "$ldap_hostdn" \
	--set password="$(cat /etc/machine.secret)" ||
	fail_test 1

echo "Wait until failed.ldif is created. Should take max. 6 min..."
# "replication.py" --> "time.sleep(10)" --> (approx. 30*10 seconds) 5 min. waiting for failed.ldif plus 1 minute of tolerance
count=0
while [ $count -le 360 -a ! -e "$ldif" ]
do
	sleep 1s
	count=`expr $count + 1`
done

if ! [ -e "$ldif" ] #failed ldif not exists
then
	fail_test 1 "File not created"
else
	testldif "$ldif"
fi

/etc/init.d/slapd start

wait_for_replication

for replayed in "$ldif_path"/replayed.ldif_*
do
	testldif "$replayed"
done

# Workaround for Bug #33050
#  https://forge.univention.org/bugzilla/show_bug.cgi?id=33050
ucr commit /etc/samba/smb.conf
for srv in samba winbind; do
	if [ -x /etc/init.d/$srv ]; then
		invoke-rc.d $srv restart
	fi
done

exit "$RETVAL"
