#!/bin/bash
# <https://forge.univention.org/bugzilla/show_bug.cgi?id=40731>
set -e -u

python -c '
import univention.admin.syntax
import inspect
print(", ".join([x for x,y in inspect.getmembers(univention.admin.syntax, lambda m: inspect.isclass(m) and issubclass(m, univention.admin.syntax.IStates))]))
'

LB="$(ucr get ldap/base)"

silent () {
	local out
	out="$("$@" 2>&1)" ||
		die "$out"
}

silent udm container/cn create --ignore_exists \
	--position "$LB" \
	--set name='bug40731'
DN="cn=bug40731,$LB"

ea () {
	echo "$2"
	local ea="ea$2" la="univentionFreeAttribute$1"
	# shellcheck disable=SC2191
	declare -a args=(
		--set name="$ea"
		--set shortDescription="$ea"
		--set translationShortDescription="\"de_DE\" \"$ea\""
		--set longDescription="$ea"
		--set translationLongDescription="\"de_DE\" \"$ea\""
		--set module='container/cn'
		--set objectClass='univentionFreeAttributes'
		--set ldapMapping="$la"
		--set syntax="$2"
		--set mayChange='1'
		--set tabName='General'
		--set translationTabName='"de_DE" "Allgemein"'
		--set groupName='Bug#40731'
		--set translationGroupName='"de_DE" "Bug#40731"'
		--set groupPosition='1'
		--set tabPosition="$1"
	)
	silent udm settings/extended_attribute create --ignore_exists \
		--position "cn=custom attributes,cn=univention,$LB" \
		"${args[@]}"
	pkill -f /usr/share/univention-directory-manager-tools/univention-cli-server

	shift 2

	for arg in "$@"
	do
		py="${arg%=*}"
		ldap="${arg#*=}"

		if [ $# -eq 2 ]
		then
			# boolean: checkbox in UMC -> true/false in JSON -> True/False for --eval
			umc="$py"
		else
			# tri-state: combobox in UMC -> str in JSON -> str with --eval
			umc="\"$ldap\""
		fi
		silent umc-command --username Administrator --password univention --flavor navigation udm/put --eval-option --option "[{\"object\":{\"\$dn\$\":\"$DN\",\"$ea\":$umc}}]"
		validate 'umc'

		silent udm container/cn modify --dn "$DN" --set "$ea=$ldap"
		validate 'udm'
	done

	echo
}

validate () {
	local val
	val="$(univention-ldapsearch -LLLo ldif-wrap=no -s base -b "$DN" '(objectClass=*)' "$la" | sed -ne "s/^$la: //p")"
	printf ' %s py=%s\texpected=%s\tldap=%s\n' "$1" "$py" "$ldap" "$val"
	[ "$ldap" = "$val" ] || die "FAIL"
}

ea 1 AllowDeny      None='' True='allow' False='deny'
ea 2 booleanNone    None='' True='yes'   False='no'
ea 3 TrueFalse      None='' True='true'  False='false'
ea 4 TrueFalseUpper None='' True='TRUE'  False='FALSE'
ea 5 TrueFalseUp            True='TRUE'  False='FALSE'
ea 6 OkOrNot                True='OK'    False='Not'
ea 7 ddnsUpdates    None='' True='on'    False='off'
