#!/usr/bin/env bash
# Switch the Document Server to NATIVE mode: stop the container, then bring
# the native stack back under systemd. The exact reverse of use-docker —
# without it, switching to docker was a one-way door (nginx stayed disabled,
# so the DS never came back after a reboot). Root-owned, sudoers-whitelisted,
# fixed logic, no arguments (except --check).
set -uo pipefail
[ "${1:-}" = "--check" ] && exit 0

echo "== stopping the docker Document Server (mutual exclusion on ports)"
docker stop onlyoffice 2>/dev/null || true

# One owner per service. A pre-systemd install leaves /etc/supervisor/conf.d/
# ds.conf behind; once systemd is enabled the .deb also installs ds-*.service,
# and BOTH spawn docservice — the loser crash-loops on :8000 forever.
if [ -d /run/systemd/system ] && [ -f /etc/supervisor/conf.d/ds.conf ]; then
  echo "== retiring stale supervisor ds.conf (systemd owns the DS units now)"
  supervisorctl stop ds-docservice ds-converter 2>/dev/null
  mv /etc/supervisor/conf.d/ds.conf /etc/supervisor/conf.d/ds.conf.disabled
  supervisorctl reread 2>/dev/null
  supervisorctl update 2>/dev/null
fi

# The .deb ships allowPrivateIPAddress=false, so the DS refuses to fetch the
# document from the engine on http://127.0.0.1:<port> ("DNS lookup 127.0.0.1
# is not allowed. Because, It is private IP address") and the editor shows
# "download failed". The docker image allows it; the package never has. A
# reinstall resets local.json, so re-assert it on every switch to native.
if [ -f /etc/onlyoffice/documentserver/local.json ]; then
  python3 - <<'PY' || echo "!! could not patch local.json — private-IP downloads may fail"
import json, shutil
p = '/etc/onlyoffice/documentserver/local.json'
d = json.load(open(p))
co = d.setdefault('services', {}).setdefault('CoAuthoring', {})
rfa = co.get('request-filtering-agent') or {}
if not (rfa.get('allowPrivateIPAddress') and rfa.get('allowMetaIPAddress')):
    shutil.copy(p, p + '.bak')
    co['request-filtering-agent'] = {'allowPrivateIPAddress': True, 'allowMetaIPAddress': True}
    json.dump(d, open(p, 'w'), indent=2)
    print('== allowed private-IP downloads (engine runs on 127.0.0.1)')
else:
    print('== private-IP downloads already allowed')
PY
fi

echo "== enabling the native stack (survives a reboot / WSL restart)"
# use-docker disabled these; `enable` is what makes them come back at boot.
# The DS postinst only ever *starts* nginx, it never enables it.
systemctl enable --now postgresql rabbitmq-server 2>/dev/null
systemctl enable --now nginx 2>/dev/null

for unit in ds-docservice ds-converter ds-metrics ds-example; do
  systemctl list-unit-files "$unit.service" >/dev/null 2>&1 || continue
  systemctl enable "$unit" 2>/dev/null
done
systemctl restart ds-converter ds-docservice 2>/dev/null

sleep 5
if curl -sf http://127.0.0.1/healthcheck >/dev/null 2>&1; then
  echo "== NATIVE MODE ACTIVE — Document Server is up"
else
  echo "== native stack enabled; server still warming up (check again in ~30s)"
fi
