#!/bin/bash

. /usr/share/univention-lib/base.sh

eval "$(ucr shell)"

set -x

uid="$(custom_username Administrator)"
dn="$(univention-ldapsearch uid=$uid dn | sed -ne 's|dn: ||p')"

# create initial mail domain object(s) if missing
if ! udm mail/domain list --binddn "$dn" --bindpwdfile /tmp/joinpwd | grep -q "^DN:" ; then
	# no mail domain object found

        # Default; create new object with $domainname as mail domain
	# can be overridden by mail/default/domains
	domain_list="$domainname"
	if [ "$mail_default_domains" ] ; then
		domain_list="$mail_default_domains"
	fi

	# create required containers
	udm container/cn create --binddn "$dn" --bindpwdfile /tmp/joinpwd --ignore_exists --position "$ldap_base" --set name="mail" || exit 1
	udm container/cn create --binddn "$dn" --bindpwdfile /tmp/joinpwd --ignore_exists --position "cn=mail,$ldap_base" --set name="domain" || exit 1

	# create new object
	for domain in $domain_list ; do
                echo "Create new maildomain for $domain."
		udm mail/domain create --binddn "$dn" --bindpwdfile /tmp/joinpwd --ignore_exists \
			--position "cn=domain,cn=mail,$ldap_base" \
			--set name="$domain" || exit 1
	done
fi

existing_address="$(univention-ldapsearch -s base -b "$dn" mailPrimaryAddress | grep "^mailPrimaryAddress:")"
udm users/user modify --binddn "$dn" --bindpwdfile /tmp/joinpwd \
	--dn "$dn" \
	--set seafileActivated=TRUE || exit 1
if [ -z "$existing_address" ]; then
	admin_address="admin@$domainname"
	udm users/user modify --binddn "$dn" --bindpwdfile /tmp/joinpwd \
		--dn "$dn" \
		--set mailPrimaryAddress="$admin_address" || exit 1
fi

exit 0
