#!/bin/bash

if [[ ! $# -ge 1 ]]; then
    echo "Missing input parameters. Usage xivo-edge-gen-turn-cred <SECRET> [<TTL>]"
    exit 2
fi

SECRET=$1
RTP_PATH="/etc/asterisk/rtp.d/01-xivo-edge-turn-cred.conf"

time=$(date +%s)
expiry=${2:-1576800000}
username=$(( "$time" + "$expiry" ))
password=$(echo -n $username | openssl dgst -binary -sha1 -hmac "$SECRET" | openssl base64)

echo
echo Generating TURN credential valid for "$expiry" secs in $RTP_PATH
echo

echo "turnusername=$username" > $RTP_PATH
echo "turnpassword=$password" >> $RTP_PATH

echo Reloading Asterisk\'s RTP module

asterisk -rvx "module reload res_rtp_asterisk.so"
