#!/bin/bash
#
# App join script
#
# Copyright 2022 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

VERSION="2"

. /usr/share/univention-lib/all.sh || exit 1
. /usr/share/univention-appcenter/joinscripthelper.sh || exit 1



APP_ID="intercom-service"

joinscript_init

ucs_addServiceToLocalhost "$APP_ID" "$@"

eval "$(ucr shell)"
# domainname="$(ucr get domainname)"
keycloak_url="$intercom_service_keycloak_url"
realm_name="$intercom_service_keycloak_realm_name"
# hostname="$(ucr get hostname)"


# Check and warn in case provided URLs are not reachable
warning_msg="was not reachable during installation, please review. Installation will continue."
curl --fail "$intercom_service_nextcloud_url" -o /dev/null -s || \
    >&2 echo "$intercom_service_nextcloud_url $warning_msg"
curl --head --fail "$intercom_service_matrix_nordeck_url" -s | head -n 1 | grep -q 404 || \
    >&2 echo "$intercom_service_matrix_nordeck_url $warning_msg"
curl --fail "$intercom_service_portal_url" -o /dev/null -s || \
    >&2 echo "$intercom_service_portal_url $warning_msg"

if [[ -z "${intercom_service_settings_issuer_base_url}" ]]; then
    ucr set \
        $APP_ID/settings/issuer-base-url="$keycloak_url/auth/realms/$realm_name"

    curl --fail "$intercom_service_keycloak_url/auth/realms/$intercom_service_keycloak_realm_name" -o /dev/null -s || \
        >&2 echo "$intercom_service_keycloak_url/auth/realms/$intercom_service_keycloak_realm_name $warning_msg"
else
    curl --fail "$intercom_service_settings_issuer_base_url" -o /dev/null -s || \
        >&2 echo "$intercom_service_portal_url $warning_msg"
fi

# set firewall rule
univention-config-registry set \
  "security/packetfilter/package/$APP_ID/tcp/8008/all=ACCEPT" \
  "security/packetfilter/package/$APP_ID/tcp/8008/en=$APP_ID"

joinscript_save_current_version
exit 0
