#!/bin/sh
# Write Asterisk the files nuxpbx owns, again.
#
# They are rendered once, at the first boot, which means a machine installed
# before a file existed never gets it. The security log fail2ban reads is one
# of those: the jail ships with the package, the log it watches is written by
# a logger.conf that only a fresh install ever received, so the bans on an
# upgraded machine watch an empty file for ever.
#
# Every file this writes says in its first line that nuxpbx wrote it and that
# changes are overwritten, so writing them again costs nothing. Asterisk's own
# files, the ones we only ever read, are not touched.
set -eu

env_file=${NUXPBX_ENV_FILE:-/etc/nuxpbx/nuxpbx.env}
[ -s "$env_file" ] || exit 0

# Line by line, the way systemd reads it: NUXPBX_DB is a connection string
# with spaces in it and no quotes around it, and `.` would turn
# "host=x port=y" into five assignments of which only the first is ours.
while IFS= read -r line; do
	case "$line" in '' | '#'*) continue ;; esac
	export "$line"
done <"$env_file"

nuxpbx config write "${NUXPBX_ASTERISK_CONFIG:-/etc/asterisk}"

# Asterisk reads a changed logger.conf only when told to. A reload rather
# than a restart: this runs on a machine that may be carrying a call.
if command -v asterisk >/dev/null 2>&1; then
	asterisk -rx 'logger reload' >/dev/null 2>&1 || true
	asterisk -rx 'module reload res_pjsip.so' >/dev/null 2>&1 || true
fi
