#!/bin/bash
# -*- indent-tabs-mode: t; tab-width: 4; -*-

[ -e /etc/mailinabox.conf ] && source /etc/mailinabox.conf
[ -e /etc/cloudinabox.conf ] && source /etc/cloudinabox.conf

source setup/functions.sh || exit 1 # load our functions



create_turnserver_conf() {
	if [ ! -e "$STORAGE_ROOT/voip/turnserver.conf" ]; then
		mkdir -p "$STORAGE_ROOT/voip"
		cat > "$STORAGE_ROOT/voip/turnserver.conf" <<EOF
STATIC_AUTH_SECRET='$(generate_password 64)'
TURNSERVER_HOSTNAME=
EOF
	fi
	. "$STORAGE_ROOT/voip/turnserver.conf"
}



# install coturn
#
# Note: visit this page to see if you get a valid repose from the
# server
# https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/
#

echo "Installing coturn (voip server)"
apt_install coturn

if [ ! -e /etc/turnserver.conf.orig ]; then
	cp /etc/turnserver.conf /etc/turnserver.conf.orig
fi

# create a conf in user-data to keep track of the secret, which will
# be reused if we need to restore from backup
create_turnserver_conf

# enable the server
tools/editconf.py /etc/default/coturn "TURNSERVER_ENABLED=1"

# set the coturn configuration
cat >/etc/turnserver.conf <<EOF
# Generated file - generated by in-a-box mods
#
# see /etc/turnserver.conf.orig for descriptions of the options
# see Nextcloud's install script:
#  https://github.com/nextcloud/vm/blob/master/apps/talk.sh
#
verbose
tls-listening-port=5349
fingerprint
lt-cred-mech
use-auth-secret
static-auth-secret=$STATIC_AUTH_SECRET
realm=${TURNSERVER_HOSTNAME:-$PRIMARY_HOSTNAME}
total-quota=100
bps-capacity=0
#stale-nonce=1200
stale-nonce
cert=$STORAGE_ROOT/ssl/ssl_certificate.pem
pkey=$STORAGE_ROOT/ssl/ssl_private_key.pem
dh-file=$STORAGE_ROOT/ssl/dh2048.pem
cipher-list="ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384"
no-loopback-peers
no-multicast-peers
no-tlsv1
no-tlsv1_1
no-stdout-log
simple-log
log-file=/var/log/turn/coturn.log

#max-bps=512
no-cli
proc-user=turnserver
proc-group=turnserver
# tls and dtls only
no-udp
#no-tcp

# listening-ip=$PRIVATE_IP
# relay-ip=$PRIVATE_IP
# stun requires the system have 2 ip address
# no-stun
EOF

chmod 640 /etc/turnserver.conf
mkdir -p /var/log/turn

# rotate the turnserver log
cat >/etc/logrotate.d/coturn <<EOF
/var/log/turn/coturn.log {
	compress
	weekly
	missingok
	rotate 26
	notifempty
	postrotate
	   rm /var/log/turn_*.log
	   systemctl restart coturn
	endscript
}
EOF

ufw allow 5349
systemctl restart coturn