#!/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"
command_background=true
pidfile="/run/nuxpbx.pid"
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
}
