#!/usr/bin/env bash
set -euo pipefail

# Установка coturn с REST-auth (временные credentials по shared-secret).
# Запускать НА TURN-сервере под root.
#
# Пример:
#   sudo bash scripts/setup_turn_coturn.sh --secret "CHANGE_ME_LONG_SECRET" --realm "shineup.me"

SECRET=""
REALM="shineup.me"
MIN_PORT="49160"
MAX_PORT="49200"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --secret)
      SECRET="${2:-}"
      shift 2
      ;;
    --realm)
      REALM="${2:-}"
      shift 2
      ;;
    --min-port)
      MIN_PORT="${2:-49160}"
      shift 2
      ;;
    --max-port)
      MAX_PORT="${2:-49200}"
      shift 2
      ;;
    *)
      echo "Неизвестный аргумент: $1" >&2
      exit 1
      ;;
  esac
done

if [[ -z "${SECRET}" ]]; then
  echo "Нужно передать --secret" >&2
  exit 1
fi

export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y coturn

PUBLIC_IP="$(hostname -I | awk '{print $1}')"
if [[ -z "${PUBLIC_IP}" ]]; then
  echo "Не удалось определить public ip автоматически, укажите вручную в /etc/turnserver.conf" >&2
  PUBLIC_IP="0.0.0.0"
fi

cat >/etc/turnserver.conf <<EOF
listening-port=3478
fingerprint
lt-cred-mech
use-auth-secret
static-auth-secret=${SECRET}
realm=${REALM}
total-quota=200
stale-nonce=600
no-multicast-peers
no-loopback-peers
no-cli
simple-log

external-ip=${PUBLIC_IP}
listening-ip=0.0.0.0
relay-ip=${PUBLIC_IP}

min-port=${MIN_PORT}
max-port=${MAX_PORT}
EOF

if [[ -f /etc/default/coturn ]]; then
  sed -i 's/^#\?TURNSERVER_ENABLED=.*/TURNSERVER_ENABLED=1/' /etc/default/coturn || true
fi

systemctl enable coturn
systemctl restart coturn
systemctl --no-pager --full status coturn

echo
echo "coturn настроен."
echo "Откройте firewall: 3478/tcp, 3478/udp, ${MIN_PORT}-${MAX_PORT}/udp"
echo "Для SHiNE-сервера задайте такой же shared-secret в параметре:"
echo "  -Dcall.ice.turn.sharedSecret=${SECRET}"
