#!/bin/bash
# 40add_email
#  add e-mail address to users
#
# Depends: ucs-school-import
#
# Copyright (C) 2014 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

[ $# -ne 2 ] && echo "USAGE: $(basename $0) FILE DN" && exit 1

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

set -e
set -u

dn="$2"
eval "$(ucr shell ldap/base hostname domainname lmz/import/set_mail)"

OU=$(awk -F '\t' '{print $4}' "$1")
ou=$(echo "$OU"|tr '[:upper:]' '[:lower:]')

username="$(awk -F '\t' '{print $2}' "$1")"
email="$(awk -F '\t' '{print $8}' "$1")"

if [ -z "${email}" ]; then
	if is_ucr_true lmz/import/set_mail; then
		echo "$(basename $0): Setting e-mail for user ${username}."
		udm users/user modify --dn "${dn}" --set mailPrimaryAddress="${username}@${domainname}" \
			--set mailHomeServer="${hostname}.${domainname}"
	else
		echo "$(basename $0): Autogeneration of email address disabled, see UCR variable lmz/import/set_mail."
	fi
else
	echo "$(basename $0): Setting mail home server for user ${username}."
	udm users/user modify --dn "${dn}" --set mailHomeServer="${hostname}.${domainname}"
fi
