#!/bin/sh
# Let Asterisk read the phone system out of the database.
#
# Everything nuxpbx knows lives in PostgreSQL, and Asterisk reads it through
# res_config_odbc: no endpoint, no trunk registration and no queue exists in
# any file. Debian's own modules.conf ships with
#
#     noload => res_config_odbc.so
#
# which is a reasonable default for a plain Asterisk and fatal for this one:
# the machine comes up, answers on every port, and serves nothing, because
# every realtime lookup ends in "the engine is not available". Nothing else
# says so, and the first anybody hears of it is a phone that will not
# register.
#
# So the line is commented out here, once, and the reason written beside it.
# Run at the first boot and again on every upgrade, because installations
# made before this existed are in exactly that state.
#
# The exit status says whether anything changed, and nothing else: zero only
# when this run rewrote the file. The postinst restarts Asterisk on that
# answer, and answering zero for "there was nothing to do" cut every call in
# progress on every ordinary package upgrade.
set -eu

conf=${1:-/etc/asterisk/modules.conf}
# No such file is nothing changed, not success.
[ -f "$conf" ] || exit 1

# Only what is ours to change: a noload line, turned into a comment. A
# machine where somebody has already dealt with it is left alone.
grep -qE '^[[:space:]]*noload[[:space:]]*=>[[:space:]]*res_config_odbc\.so' "$conf" || exit 1

tmp=$(mktemp)
sed -E 's|^([[:space:]]*noload[[:space:]]*=>[[:space:]]*res_config_odbc\.so.*)$|; nuxpbx keeps the phone system in the database and reads it through this\n; module, so it cannot be left out. The line as Debian ships it:\n;\1|' \
	"$conf" >"$tmp"
cat "$tmp" >"$conf"
rm -f "$tmp"
echo "asterisk: the database is readable again (res_config_odbc was switched off in $conf)"
