#!/bin/bash

set -e

DOMAIN=$(relation-get domain) || exit 1
URL="$(relation-get url)" || exit 1
PROTO="${URL%%://*}"

trusted_domains="$(
    compose -q --no-relations --no-init occ "$MASTER_BASE_SERVICE_NAME" \
         config:system:get trusted_domains)"

occ_opts=(
    ## necessary as nextcloud do not detect correctly those, and behind
    ## a proxy, it will generate a lot of URL that are not detected
    ## by means of ``ReverseProxyPass`` on apache for instance

    config:system:set overwritehost --value="$DOMAIN" \;
    config:system:set overwriteprotocol --value="$PROTO"
)
if ! [[ $'\n'"$trusted_domains"$'\n' == *$'\n'"$MASTER_BASE_SERVICE_NAME"$'\n'* ]]; then
    trusted_index=$(echo "$trusted_domains" | wc -l)
    debug "Adding $MASTER_TARGET_SERVICE_NAME to ${WHITE}trusted_domains${NORMAL}."
    occ_opts+=( \; config:system:set trusted_domains "$trusted_index" --value="$MASTER_BASE_SERVICE_NAME")
fi
compose --no-relations --no-init occ "$MASTER_BASE_SERVICE_NAME" "${occ_opts[@]}"