#!/bin/bash
#
# Open-Xchange
#  unjoin script
#
# Copyright (C) 2013-2020 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/>.

## joinscript api: bindpwdfile

# Don't hide errors within pipes
set -o pipefail

VERSION=1
APP_ID="ox-connector"
SERVICE="ox"

. /usr/share/univention-lib/base.sh
. /usr/share/univention-lib/ldap.sh
. /usr/share/univention-join/joinscripthelper.lib

joinscript_init

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

purge_ox () {
  purge_ea "${@}"
  purge_user_template "${@}"
  purge_umc "${@}"
}
purge_ea () {
  # For App Center apps it is recommended to remove all extended
  # attributes upon removal of the app.
  univention-directory-manager container/cn remove "${@}" \
    --recursive \
    --dn "cn=open-xchange,cn=custom attributes,cn=univention,${ldap_base}"
}
purge_user_template () {
  univention-directory-manager settings/usertemplate remove "${@}" \
    --dn "cn=open-xchange groupware account,cn=templates,cn=univention,${ldap_base}"
}
purge_umc () {
  univention-directory-manager settings/umc_operationset remove "${@}" \
    --dn "cn=udm-oxcontext,cn=operations,cn=UMC,cn=univention,${ldap_base}"
  univention-directory-manager settings/umc_operationset remove "${@}" \
    --dn "cn=udm-oxresources,cn=operations,cn=UMC,cn=univention,${ldap_base}"
}

ucs_removeServiceFromLocalhost "${SERVICE}" "${@}"
if ucs_isServiceUnused "${SERVICE}" "${@}"; then
  purge_ox "${@}"
  stop_udm_cli_server
fi

joinscript_remove_script_from_status_file "${APP_ID}"

exit 0
