#!/bin/bash
#
# Univention
#  listener module: creating mailboxes and sieve scripts
#
# Copyright 2008-2012 Univention GmbH (http://www.univention.de/)
#
# and 
#     iKu Systems & Services GmbH & Co. KG
#
# http://www.iku-systems.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/>.

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

# OX install-script for UCS 2

eval `univention-config-registry shell`

OXADMINMASTER="oxadminmaster"
OXDBUSER="openexchange"

OXSECRETPATH="/etc/ox-secrets"
mkdir -m 700 "$OXSECRETPATH" 2>/dev/null
OXPATH="/opt/open-xchange"
OXADMINBIN="$OXPATH/sbin"
OXMASTERSECRETFILE="$OXSECRETPATH/master.secret"
OXDBSECRETFILE="$OXSECRETPATH/dbuser.secret"

## Tests: Verbindungen zu mysql, join-status
if ! test -e "/usr/share/univention-join/.joined"; then
	echo "The server has not joined yet"
	exit 1
fi

CONTEXTNUM=10
OXCONTEXTNAME=context$CONTEXTNUM

if univention-ldapsearch cn="$OXCONTEXTNAME" | grep -q "^cn: $OXCONTEXTNAME"; then
	echo "Context10 already exsists. Not installing."
	exit 0
fi

MYSQLOPTIONS=()

if [ "$OXDB" -o "$OXDBPW" ]; then
	MYSQLOPTIONS+=(-h "$OXDB")
	MYSQLOPTIONS+=(-u "$OXDBUSER")
	MYSQLOPTIONS+=(--password="$OXDBPW")
	if ! echo | mysql -h "$OXDB" -u "$OXDBUSER" --password="$OXDBPW" >/dev/null 2>&1; then
		echo "Connection to MySQL server failed."
		echo "Please check env. variables 'OXDB' and 'OXDBPW'."
		exit 1
	fi
else
	if [ -e /etc/mysql.secret ]; then
		MYSQLOPTIONS+=(-u root)
		MYSQLOPTIONS+=(--password="$(cat /etc/mysql.secret)")
		if ! echo | mysql -u "root" --password="$(cat /etc/mysql.secret)" >/dev/null 2>&1; then
			echo "Connection to MySQL server failed. Aborting"
			exit 1
		fi
	else
		if ! echo | mysql; then
			echo "Connection to MySQL server failed. Aborting"
			exit 1
		fi
	fi
fi

if [ ! -f "$OXMASTERSECRETFILE" ]; then
	SERVERNAME="localhost"
	OXFILESTORE="/var/oxfilestore"

	mkdir -p "$OXFILESTORE" 2>/dev/null
	chmod 700 "$OXFILESTORE"
	chown open-xchange "$OXFILESTORE"
	OXFILESTORESIZE=$( expr $(df -P -k "$OXFILESTORE" | tail -1 | awk '{ print $4 }') / 1126)

	OXADMINMASTERPW=$("$OXPATH/sbin/genpw.sh")
	if [ "$OXDB" -a "$OXDBPW" ]; then
		OXDBUSERPW="$OXDBPW"
		CONFIGDBHOST="$OXDB"
	else
		OXDBUSERPW=$("$OXPATH/sbin/genpw.sh")
		CONFIGDBHOST=localhost
	fi
	
	##########################
	### Baseconf-Variablen ###
	##########################
	
	touch "$OXMASTERSECRETFILE"
	chmod 600 "$OXMASTERSECRETFILE"
	echo "$OXADMINMASTERPW" > "$OXMASTERSECRETFILE"
	
	touch "$OXDBSECRETFILE"
	chmod 600 "$OXDBSECRETFILE"
	echo "$OXDBUSERPW" > "$OXDBSECRETFILE"
	
	##########################
	### MySQL - Bootstrap  ###
	##########################
	if ! [ "$OXDB" ]; then
		mysql "${MYSQLOPTIONS[@]}" << EOF
GRANT ALL PRIVILEGES ON *.* TO '$OXDBUSER'@'localhost' IDENTIFIED BY '$OXDBUSERPW' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EOF

	fi

	if [ ! -e /etc/mysql.secret ]; then
		tmp=$(mktemp)
		makepasswd --nocrypt > $tmp
		passwd=$(cat $tmp)
		hash=$(mkpasswd --hash=md5 -s < $tmp)
		touch /etc/mysql.secret
		chmod 600 /etc/mysql.secret
		echo $passwd > /etc/mysql.secret
		chown root /etc/mysql.secret
		rm -f $tmp
		# set passwd for database user reservation
		/usr/bin/mysqladmin -u root password "$passwd"
		unset passwd
	fi

	$OXADMINBIN/initconfigdb \
		--configdb-user="$OXDBUSER" \
		--configdb-pass="$OXDBUSERPW" \
		--configdb-host="$CONFIGDBHOST" 
	
	##########################
	### Vorbereitung OX    ###
	##########################
	
	$OXADMINBIN/oxinstaller \
		--servername=$SERVERNAME \
		--configdb-pass="$OXDBUSERPW" \
		--master-pass="$OXADMINMASTERPW" \
		--configdb-readhost="$CONFIGDBHOST" \
		--configdb-writehost="$CONFIGDBHOST" \
		--master-user=$OXADMINMASTER \
		--object-link-hostname="$(hostname -f)/ox6" \
		--servermemory="$(ucr get ox/java/mem)" \
		--no-license 
	
	##########################
	### Konfig. LDAPauth   ###
	##########################


	ucr set ox/cfg/AdminUser.properties/USERNAME_CHANGEABLE=true \
		ox/cfg/AdminUser.properties/CHECK_USER_UID_FOR_NOT_ALLOWED_CHARS=false \
		ox/cfg/AdminUser.properties/PRIMARY_MAIL_UNCHANGEABLE=false

	ucr set ox/cfg/Group.properties/CHECK_GROUP_UID_FOR_NOT_ALLOWED_CHARS=false

	ucr set "ox/cfg/mailfilter.properties/SIEVE_LOGIN_TYPE=user" \
	        "ox/cfg/mailfilter.properties/SIEVE_CREDSRC=imapLogin"
	
	ucr set ox/cfg/foldercache.properties/ENABLE_INTERNAL_USER_EDIT=false
	
	ucr set ox/cfg/mail.properties/com.openexchange.mail.adminMailLoginEnabled=true
	
	ucr set ox/cfg/configjump.properties/URL="https://$ldap_master/umc"
	
	ucr set ox/cfg/sessiond.properties/com.openexchange.sessiond.maxSessionPerUser=1000
	
	ucr set ox/cfg/cache.ccf/jcs.auxiliary.LTCP.attributes.UdpDiscoveryEnabled=false
	
	ucr set "ox/cfg/imap.properties/com.openexchange.imap.spamHandler=SpamAssassin"

	ucr set ox/cfg/cache.ccf/jcs.auxiliary.LTCP.attributes.TcpServers='127.0.0.1:57461'

	ucr set "ox/cfg/imap.properties/com.openexchange.imap.spamHandler=SpamAssassin"

	ucr set ox/cfg/push-udp.properties/com.openexchange.push.udp.senderAddress="$hostname.$domainname"
	
	
	##########################
	### (Re-)Start Dienste ###
	##########################

	
	invoke-rc.d open-xchange restart

	echo -n "Waiting for Open-Xchange daemons to be started ."
	while ! "$OXPATH/sbin/allpluginsloaded" >/dev/null 2>&1; do
		sleep 5
		echo -n "."
	done
	echo
	
	/etc/init.d/apache2 restart

	##########################
	### Erzeugen OX-env.   ###
	##########################
	
	$OXADMINBIN/registerdatabase \
		--name="$SERVERNAME" \
		--dbpasswd="$OXDBUSERPW" \
		--master=true \
		--hostname="$CONFIGDBHOST" \
		-A "$OXADMINMASTER" \
		-P "$OXADMINMASTERPW"
	
	$OXADMINBIN/registerserver \
		--name="$SERVERNAME" \
		-A "$OXADMINMASTER" \
		-P "$OXADMINMASTERPW"
	
	$OXADMINBIN/registerfilestore \
		--storepath=file://$OXFILESTORE \
		--storesize="$OXFILESTORESIZE" \
		-A "$OXADMINMASTER" \
		-P "$OXADMINMASTERPW"
fi
/usr/sbin/ox-register-to-ucs-domain $@ || exit 1
	
	## for debug
	# univention-config-registry set listener/debug/level=3
