#!/bin/bash
#
# CoTurn Service

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

config_coturn() {
  echo -ne "\n* Configuring /federated/apps/coturn container.."

  if [ ! -d "/federated/apps/coturn" ]; then
    mkdir -p /federated/apps/coturn/data/etc
    mkdir -p /federated/apps/coturn/data/var/lib/coturn
    chown nobody /federated/apps/coturn/data/var/lib/coturn
  fi

cat > /federated/apps/coturn/docker-compose.yml <<EOF
services:
  coturn:
    image: coturn/coturn:\${IMAGE_VERSION}
    container_name: coturn
    hostname: coturn.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.35
    env_file:
      - ./.env
    volumes:
      - ./data/etc/turnserver.conf:/etc/turnserver.conf:ro
      - ./data/var/lib/coturn:/var/lib/coturn
    ports:
      - 3478:3478
      - 3478:3478/udp
      - 3479:3479
      - 3479:3479/udp

networks:
  core:
    external: true
EOF

cat > /federated/apps/coturn/.env <<EOF
IMAGE_VERSION="$(current_version coturn)"
LOG_FILE=stdout
PORT=3478
ALT_PORT=3479
TLS_PORT=5349
TLS_ALT_PORT=5350
JSON_CONFIG='{"config":["no-auth"]}'
EOF
chmod 600 /federated/apps/coturn/.env

COTURN_SECRET=$(create_password);
COTURN_MATRIX_SECRET=$(grep turn_shared_secret: /federated/apps/matrix/data/matrix/homeserver.yaml | awk -F\" '{ print $2 }')

cat > /federated/apps/coturn/data/etc/turnserver.conf <<EOF
realm=coturn.$DOMAIN

user=coturn:$COTURN_SECRET
lt-cred-mech

use-auth-secret
static-auth-secret=$COTURN_MATRIX_SECRET

listening-ip=0.0.0.0
listening-port=3478

# Relay port range limit
min-port=49160
max-port=49200
EOF
 
echo -ne "done."
}
start_coturn() {
  # Start service with command to make sure it's up before proceeding
  start_service "coturn" "nc -z 192.168.0.35 3478 &> /dev/null" "7"

  echo -ne "done."
}
