#!/bin/sh
# Merge autoAssembly into the running OnlyOffice container's local.json.
# Do NOT bind-mount deploy/onlyoffice/local.json — it replaces the auto-generated
# config (postgres, JWT, rabbitmq) and prevents Document Server from starting.
set -e

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"

INTERVAL="${ONLYOFFICE_AUTO_ASSEMBLY_INTERVAL:-1m}"
STEP="${ONLYOFFICE_AUTO_ASSEMBLY_STEP:-1m}"

if ! docker compose --env-file .env.resolved \
  -f deploy/docker-compose.yml \
  -f deploy/onlyoffice/docker-compose.onlyoffice.yml \
  ps onlyoffice 2>/dev/null | grep -q onlyoffice; then
  echo "OnlyOffice container not found. Start the stack first:" >&2
  echo "  ./deploy/compose-up.sh up -d onlyoffice" >&2
  exit 1
fi

echo "Enabling OnlyOffice autoAssembly (interval=${INTERVAL}, step=${STEP})…"

docker compose --env-file .env.resolved \
  -f deploy/docker-compose.yml \
  -f deploy/onlyoffice/docker-compose.onlyoffice.yml \
  exec -T onlyoffice python3 - "$INTERVAL" "$STEP" <<'PY'
import json
import sys

interval, step = sys.argv[1], sys.argv[2]
path = "/etc/onlyoffice/documentserver/local.json"

with open(path, encoding="utf-8") as f:
    data = json.load(f)

co = data.setdefault("services", {}).setdefault("CoAuthoring", {})
co["autoAssembly"] = {"enable": True, "interval": interval, "step": step}

with open(path, "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)
    f.write("\n")

print("Updated", path)
PY

docker compose --env-file .env.resolved \
  -f deploy/docker-compose.yml \
  -f deploy/onlyoffice/docker-compose.onlyoffice.yml \
  exec -T onlyoffice supervisorctl restart ds:docservice ds:converter

echo "OnlyOffice autoAssembly enabled."
