#!/bin/bash
#
# Univention open-xchange integration
#
# Copyright (C) 2016-2017 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/>.

. /usr/share/univention-ox/ox-lib.sh || exit 1

eval "$(univention-config-registry shell)"

check_params () {
	BINDARGS=()
	while [ $# -ge 1 ]
	do
		case "$1" in
		--help|-h) usage ; exit 0 ;;
		--context) CONTEXTNUM="${2:?missing context number}" ; shift 2 ;;
		--password) CONTEXTADMINPW="${2:?missing context admin password}" ; shift 2 ;;
		--dont-wait) DONT_WAIT=1; shift;;
		--bind*) BINDARGS+=("$1" "$2") ; shift 2 ;;
		*) die 2 "Unknown option: $1" ;;
		esac
	done
	if [ -z "$CONTEXTNUM" -o -z "$CONTEXTADMINPW" ]; then
		msg "Missing information."
		usage
		exit 2
	fi
	case "$server_role" in
		domaincontroller_master|domaincontroller_backup) ;;
		domaincontroller_slave|memberserver) [ -n "$BINDARGS" ] || die 2 "Missing LDAP credentials." ;;
		*) die "Unknown server role '$server_role'." ;;
	esac
	OXCONTEXTNAME="context${CONTEXTNUM}"
	FORCE_CONTEXTADMINPW="$CONTEXTADMINPW"
}

usage () {
	cat <<-__USAGE__
	usage: ${0##*/} [options]

	Options:
	 --help, -h           Show this help
	 --context NUM        Context number
	 --password STR       Password for context admin
	 --binddn STR         LDAP bind DN
	 --bindpwd STR        LDAP bind password

	 The username will be "oxadmin-context<ID>".
	__USAGE__
}

main() {
	prepare_oxadmin_secret

	if list_context
	then
		msg "Context '$OXCONTEXTNAME' already exists; re-using."
	elif create_context
	then
		msg "$OXCONTEXTNAME has been created successfully."
		msg "The username is \"$CONTEXTADMIN\", the password is stored in \"$CONTEXTSECRETFILE\"."
	else
		die 1 "Failed to create context '$OXCONTEXTNAME'."
	fi

	register_oxcontext
}

check_params "$@"
setup_vars

# overwrite settings from setup_vars()
CONTEXTADMINPW="$FORCE_CONTEXTADMINPW"
CONTEXTADMINMAIL="$CONTEXTADMIN@$CONTEXTDOMAIN"

main
exit $?
