#!/bin/bash
#
# Convert an UDM object to the command line creating it
# Philipp Hahn
#
ldap_base="$(/usr/sbin/ucr get ldap/base)"

module () {
	local dn="$1"
	{
		univention-ldapsearch -xLLLb "$dn" univentionObjectType ||
			echo 'univentionObjectType: ...'
	} | sed -ne 's,univentionObjectType: ,,p'
}

ldap () {
	local value="$1"
	case "$value" in
	*"$ldap_base") printf '%q%s' "${value%$ldap_base}" '"$(ucr get ldap/base)"' ;;
	*) printf '%q' "$value" ;;
	esac
}

parse_key () {
	local key="$1" value="$2"
	case "$key" in
	"") ;;
	DN) printf 'udm %q create \\\n  --position %s' "$(module "$value")" "$(ldap "${value#*,}")" ;;
	ARG) ;;
	*) parse_value "$key" "$value"
	esac
}

declare -a VALUES=()
parse_value () {
	local key="$1" value="$2"
	case "$value" in
	None) ;;
	0) ;;
	*) printf ' \\\n  --set %q=%q' "$key" "$value" ;;
	esac
}

junk=1
while IFS=": " read key value
do
	[ -n "$junk" ] && [[ "$key" = *=* ]] && continue
	junk=
	parse_key "$key" "$value"
done
printf '\n'
