#!/bin/sh
# Configure the OnlyOffice Nextcloud connector for server-side document/PDF previews.
# Idempotent — safe to run on every container start (before-starting hook).
set -e

case "$(printf '%s' "${ONLYOFFICE_ENABLED:-false}" | tr '[:upper:]' '[:lower:]')" in
  1|true|yes|on) ;;
  *)
    echo "OnlyOffice disabled — skipping Nextcloud connector configuration."
    exit 0
    ;;
esac

OCC="php /var/www/html/occ"

if ! $OCC status 2>/dev/null | grep -q "installed: true"; then
  echo "Nextcloud not installed yet — skipping OnlyOffice configuration."
  exit 0
fi

if ! $OCC app:list 2>/dev/null | grep -qE 'onlyoffice:'; then
  echo "Installing OnlyOffice Nextcloud app…"
  $OCC app:install onlyoffice || true
fi
$OCC app:enable onlyoffice || true

if ! $OCC app:list --enabled 2>/dev/null | grep -qE 'onlyoffice:'; then
  echo "OnlyOffice app unavailable — skipping connector configuration."
  exit 0
fi

DS_INTERNAL="${ONLYOFFICE_URL:-http://onlyoffice}"
DS_PUBLIC="${ONLYOFFICE_PUBLIC_URL:-$DS_INTERNAL}"
# OnlyOffice fetches files via the edge nginx. StorageUrl replaces the host part of
# Nextcloud absolute URLs; nginx routes /index.php/* to Nextcloud (see default.conf.template).
STORAGE="${NC_ONLYOFFICE_STORAGE_URL:-http://nginx}"
JWT="${ONLYOFFICE_JWT_SECRET:-}"

# Trailing slash required by the connector.
case "$DS_PUBLIC" in */) ;; *) DS_PUBLIC="${DS_PUBLIC}/" ;; esac
case "$DS_INTERNAL" in */) ;; *) DS_INTERNAL="${DS_INTERNAL}/" ;; esac
case "$STORAGE" in */) ;; *) STORAGE="${STORAGE}/" ;; esac

$OCC config:app:set onlyoffice DocumentServerUrl --value="$DS_PUBLIC"
$OCC config:app:set onlyoffice DocumentServerInternalUrl --value="$DS_INTERNAL"
$OCC config:app:set onlyoffice StorageUrl --value="$STORAGE"
$OCC config:app:set onlyoffice advanced --value="true"
$OCC config:app:set onlyoffice preview --value="true"
$OCC config:app:set onlyoffice demo --value="false"

if [ -n "$JWT" ]; then
  $OCC config:app:set onlyoffice jwt_secret --value="$JWT"
fi

$OCC config:system:set enable_previews --value=true --type=boolean
$OCC config:system:set preview_max_x --value=2048 --type=integer
$OCC config:system:set preview_max_y --value=2048 --type=integer

echo "OnlyOffice connector configured (document preview enabled)."

if $OCC onlyoffice:documentserver --check 2>/dev/null; then
  echo "OnlyOffice Document Server connection OK."
else
  echo "OnlyOffice Document Server not reachable yet — previews will work once it is healthy."
fi
