#!/usr/bin/env bash
# Switch the Document Server to DOCKER mode: stop + disable the native stack
# so the container can own the ports (80, 5432, 5672, 8000...). Root-owned,
# sudoers-whitelisted, fixed logic, no arguments (except --check).
set -uo pipefail
[ "${1:-}" = "--check" ] && exit 0

echo "== stopping native Document Server stack"
systemctl stop ds-docservice ds-converter ds-metrics ds-example 2>/dev/null
systemctl disable ds-docservice ds-converter ds-metrics ds-example 2>/dev/null
supervisorctl stop all 2>/dev/null

echo "== stopping native nginx / postgres / rabbitmq (dedicated to the DS)"
systemctl stop nginx postgresql rabbitmq-server 2>/dev/null
systemctl disable nginx postgresql rabbitmq-server 2>/dev/null

# This is a REVERSIBLE switch, not a one-way door: anvilterm-office-use-native
# re-enables everything above. Leave a breadcrumb so a human reading a broken
# boot ("why is nginx disabled?") finds the way back.
mkdir -p /var/lib/anvilterm
cat > /var/lib/anvilterm/office-mode <<'EOF'
mode=docker
# The native stack (nginx, postgresql, rabbitmq-server, ds-*) was stopped and
# DISABLED so the host-networked container can own ports 80/5432/5672/8000.
# To go back:  sudo /usr/local/sbin/anvilterm-office-use-native
EOF

echo "== native stack disabled — ports are free for the container"
echo "== reverse with: sudo /usr/local/sbin/anvilterm-office-use-native"
