#!/bin/bash
set -e

echo "Installing Nextcloud Talk app..."
php /var/www/html/occ app:install spreed
echo "Nextcloud Talk installed successfully!"

echo "Enabling Nextcloud Talk..."
php /var/www/html/occ app:enable spreed
echo "Nextcloud Talk enabled successfully!"

echo "Configuring Nextcloud Talk HPB..."

if [ -z "${TALK_DOMAIN}" ]; then
    echo "Warning: TALK_DOMAIN not set, skipping Talk HPB configuration."
    exit 0
fi

# STUN server
php /var/www/html/occ --no-warnings talk:stun:add "${TALK_DOMAIN}:3478"

# TURN server
if [ -n "${TALK_TURN_SECRET}" ]; then
    php /var/www/html/occ --no-warnings talk:turn:add turn "${TALK_DOMAIN}:3478" udp,tcp --secret="${TALK_TURN_SECRET}"
else
    echo "Warning: TALK_TURN_SECRET not set, skipping TURN configuration."
fi

# High Performance Backend (signaling server)
if [ -n "${TALK_SIGNALING_SECRET}" ]; then
    php /var/www/html/occ --no-warnings talk:signaling:add "https://${TALK_DOMAIN}" "${TALK_SIGNALING_SECRET}"
else
    echo "Warning: TALK_SIGNALING_SECRET not set, skipping HPB signaling configuration."
fi

echo "Nextcloud Talk configuration completed!"
echo "STUN/TURN/HPB configured for: ${TALK_DOMAIN}"
