#!/bin/bash
if [ -f "/root/twistd.pid" ]; then
	rm "/root/twistd.pid"
fi

MDS_MODE=0
XIVO_CONFGEND_FILE="/etc/xivo/xivo-confgend.conf"

if [ -n "${MDS_PEERNAME}" -a -n "${MDS_PEERSECRET}" -a -n "${XIVO_VOIP_HOST}" ]; then
	MDS_MODE=1
fi

cat > $XIVO_CONFGEND_FILE << EOF
[confgend]
listen=0.0.0.0
port=8669

; cache path
cache=/var/lib/xivo-confgend

; Database connection informations.
db_uri=postgresql://asterisk:proformatique@db/asterisk

[asterisk]
contextsconf=/etc/xivo/xivo-confgend/asterisk/contexts.conf

EOF

if [ $MDS_MODE -eq 1 ]; then
	cat >> $XIVO_CONFGEND_FILE <<-EOF
	; MDS configuration
	[mds]
	peername=${MDS_PEERNAME}
	peersecret=${MDS_PEERSECRET}
	xmainip=${XIVO_VOIP_HOST}
	EOF
fi


/usr/bin/twistd -n -o -y /usr/local/bin/xivo-confgend --logfile=/var/log/xivo-confgend.log
