#!/bin/bash

set -e

KEY=$(relation-get secret) || true

if [ -z "$KEY" ]; then
    KEY=$(gen_password 64)
fi

## XXXvlab: we really need to have a state based cache thingy, because
## setting the same password each time is really time consumming.
compose --no-relations --no-init \
        occ "$MASTER_TARGET_SERVICE_NAME" \
        app:install onlyoffice \; \
        config:system:set onlyoffice DocumentServerInternalUrl --value="http://$MASTER_BASE_SERVICE_NAME/" \; \
        config:system:set onlyoffice StorageUrl --value="http://$MASTER_TARGET_SERVICE_NAME/" \; \
        config:app:set onlyoffice jwt_secret --value="$KEY" \; \
        config:system:set allow_local_remote_servers --type=boolean --value=true \; \
        app:enable onlyoffice

## Got:
# $ ./occ app:enable onlyoffice
# App "ONLYOFFICE" cannot be installed because it is not compatible with this version of the server.
#
## Should
# $ ./occ app:update onlyoffice
# onlyoffice new version available: 7.5.4
# Error: Database error when running migration 070400Date20220607111111 for app onlyoffice
# An exception occurred while executing a query: SQLSTATE[42P07]: Duplicate table: 7 ERROR:  relation "share_id_index" already exists
#
## Then patch it, and re-update (no error should be done)


if [ -e "$DATASTORE"/"$TARGET_SERVICE_NAME/var/www/html/custom_apps/onlyoffice/lib/Migration/Version070400Date20220607111111.php" ]; then
    (
        cd "$DATASTORE"/"$TARGET_SERVICE_NAME/var/www/html/custom_apps/onlyoffice/"
        patch="$CHARM_PATH/src/patch/00-onlyoffice-nextcloud.patch"
        if patch -Np1 --dry-run < "$patch"; then
            patch -Np1 < "$patch"
        fi
    )
fi

ONLYOFFICE_CFG="$SERVICE_CONFIGSTORE/etc/onlyoffice/documentserver/local.json"
out=$(jq ".services.CoAuthoring.token.enable.browser = true |
          .services.CoAuthoring.token.enable.request.inbox = true |
          .services.CoAuthoring.token.enable.request.outbox = true |
          .services.CoAuthoring.secret.inbox.string = \"$KEY\" |
          .services.CoAuthoring.secret.outbox.string = \"$KEY\" |
          .services.CoAuthoring.secret.session.string = \"$KEY\"" \
              "$ONLYOFFICE_CFG")

H1=$(cat "$ONLYOFFICE_CFG" | hash_get)
H2=$(echo "$out" | hash_get)
if [ "$H1" != "$H2" ]; then
    echo "$out" > "$ONLYOFFICE_CFG"

    ## XXXvlab: onlyoffice need to be restarted if already running and local.json changed.
    ## it is about docker exec $SERVICE_NAME supervisor restart ...
    for container_id in $(get_running_containers_for_service "$SERVICE_NAME"); do
        ## restarting all as documented here: https://api.onlyoffice.com/editors/signature/
        docker exec "$container_id" supervisorctl restart all
    done
    relation-set secret "$KEY"

fi