#!/sbin/openrc-run
# The phone system's own service. Everything it needs is in the environment
# file the first boot wrote, secrets included, which is why that file is
# readable by this user and nobody else.

description="nuxpbx, the phone system"
command="/usr/bin/nuxpbx"
command_user="nuxpbx:nuxpbx"
# Port 443 is privileged, and the service is not root. This one capability
# is what lets https open it, from the first steps or the environment file.
capabilities="^cap_net_bind_service"
# Supervised: the daemon exits on purpose when its database connection
# drops (a PostgreSQL backend killed for memory, a restart), trusting that
# something starts it again, the way systemd's Restart=always does on the
# deb. Without this OpenRC wrote it down as crashed and the phones stayed
# without wake, call records and callbacks until somebody logged in.
supervisor=supervise-daemon
respawn_delay=2
respawn_max=0
# A socket per open connection, and the dial plan's loopback CURLs share the
# public listener: at the default 1024 a burst of idle connections fills the
# table inside the header timeout and Asterisk can no longer reach it.
rc_ulimit="-n 65536"
output_log="/var/log/nuxpbx.log"
error_log="/var/log/nuxpbx.log"

depend() {
	need postgresql
	after asterisk net
	use dns
}

start_pre() {
	if [ ! -s /etc/nuxpbx/nuxpbx.env ]; then
		eerror "/etc/nuxpbx/nuxpbx.env is missing: the first boot has not run, or failed"
		return 1
	fi
	checkpath -f -m 0640 -o nuxpbx:nuxpbx /var/log/nuxpbx.log
	# Line by line, the way systemd reads it and the way nuxpbx-render and
	# the nightly backup already read it. Not sourced: NUXPBX_DB is a
	# connection string with spaces in it and no quotes around it, so `.`
	# turned it into "host=127.0.0.1" and four stray variables, and the
	# daemon then reached PostgreSQL as its own process user with no
	# password at all. It worked because a fresh Alpine cluster trusts
	# local connections, and the password this machine generated for
	# itself was never used by anything.
	while IFS= read -r line; do
		case "$line" in '' | '#'*) continue ;; esac
		export "$line"
	done </etc/nuxpbx/nuxpbx.env
}
