#!/bin/bash
set -e

echo "Installing Nextcloud Office (richdocuments) app..."
php /var/www/html/occ app:install richdocuments
echo "Nextcloud Office installed successfully!"

echo "Enabling Nextcloud Office..."
php /var/www/html/occ app:enable richdocuments
echo "Nextcloud Office enabled successfully!"

echo "Configuring Nextcloud Office with Collabora Online..."

# Set the WOPI URL (Collabora server URL)
if [ -n "${COLLABORA_DOMAIN}" ]; then
    echo "Setting WOPI URL to https://${COLLABORA_DOMAIN}"
    php /var/www/html/occ --no-warnings config:app:set richdocuments wopi_url --value="https://${COLLABORA_DOMAIN}"
else
    echo "Warning: COLLABORA_DOMAIN not set, skipping WOPI URL configuration"
fi

# Disable certificate verification (set to 'yes' only for development/self-signed certs)
php /var/www/html/occ --no-warnings config:app:set richdocuments disable_certificate_verification --value="no"

# Allow list for WOPI requests (optional, for additional security)
if [ -n "${COLLABORA_DOMAIN}" ]; then
    php /var/www/html/occ --no-warnings config:app:set richdocuments wopi_allowlist --value="${COLLABORA_DOMAIN}"
fi

# Enable the built-in CODE server option (if using built-in Collabora)
# Uncomment if you want to use the built-in CODE server instead of external Collabora
# php /var/www/html/occ --no-warnings config:app:set richdocuments use_built_in_code_server --value="yes"

echo "Nextcloud Office configuration completed!"
echo "Collabora Online should now be available at: https://${COLLABORA_DOMAIN}"
