#!/bin/bash

# Coturn TURN Server Setup Script for Ubuntu
# Run on your Ubuntu server (VPS or same machine as chat backend).
# Chat backend uses /api/turn-credentials with TURN_SERVER and TURN_SECRET env vars.

set -e  # Exit on error

echo "🚀 Starting Coturn TURN Server Setup (Ubuntu)..."

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ Please run as root: sudo ./setup_coturn.sh"
    exit 1
fi

# Update system
echo "📦 Updating system packages..."
apt-get update -y

# Install Coturn
echo "📥 Installing Coturn..."
apt-get install -y coturn

# Ubuntu/Debian: enable coturn (disabled by default)
if [ -f /etc/default/coturn ]; then
    if grep -q '^#*TURNSERVER_ENABLED=0' /etc/default/coturn 2>/dev/null; then
        sed -i 's/^#*TURNSERVER_ENABLED=0/TURNSERVER_ENABLED=1/' /etc/default/coturn
        echo "✅ Enabled coturn in /etc/default/coturn"
    elif ! grep -q 'TURNSERVER_ENABLED=1' /etc/default/coturn 2>/dev/null; then
        echo "TURNSERVER_ENABLED=1" >> /etc/default/coturn
        echo "✅ Added TURNSERVER_ENABLED=1 to /etc/default/coturn"
    fi
fi

# Get server's public and private IP (for NAT/VPS: bind to private, advertise public)
echo "🌐 Detecting server IPs..."
PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null || true)
PRIVATE_IP=$(hostname -I 2>/dev/null | awk '{print $1}')
[ -z "$PRIVATE_IP" ] && PRIVATE_IP=$(ip -4 route get 8.8.8.8 2>/dev/null | grep -oP 'src \K[^ ]+' || echo "0.0.0.0")
echo "   Public IP: $PUBLIC_IP"
echo "   Private IP: $PRIVATE_IP"

# Generate random secret
echo "🔐 Generating secret key..."
SECRET=$(openssl rand -hex 32)
echo "   Secret: $SECRET"

# Backup original config
if [ -f /etc/turnserver.conf ]; then
    cp /etc/turnserver.conf /etc/turnserver.conf.backup
    echo "✅ Backed up original config"
fi

# Create Coturn configuration (NAT-safe: bind private, advertise public)
echo "⚙️  Creating Coturn configuration..."
cat > /etc/turnserver.conf << EOF
# Coturn TURN Server Configuration
# Auto-generated by setup script (NAT-safe)

# Listening ports
listening-port=3478
listening-ip=0.0.0.0
tls-listening-port=5349

# Server IPs: internal/external so coturn binds to private IP but advertises public
external-ip=$PRIVATE_IP/$PUBLIC_IP
relay-ip=$PRIVATE_IP

# Enable fingerprinting
fingerprint

# Use long-term credentials with shared secret
lt-cred-mech
use-auth-secret
static-auth-secret=$SECRET

# Realm (domain or IP)
realm=$PUBLIC_IP

# Logging
verbose
log-file=/var/log/turnserver.log

# Performance settings
total-quota=100
bps-capacity=0

# Enable TCP relay (critical for mobile)
tcp-relay

# Disable UDP relay (optional - force TCP only)
# no-udp

# Allowed peer IPs (optional - uncomment to restrict)
# denied-peer-ip=0.0.0.0-255.255.255.255
# allowed-peer-ip=YOUR_APP_SERVER_IP

# User database (optional - for static users)
# user=username:password
EOF

echo "✅ Configuration created"

# Configure firewall
echo "🔥 Configuring firewall..."
ufw allow 3478/tcp
ufw allow 3478/udp
ufw allow 5349/tcp
ufw allow 5349/udp
ufw allow 49152:65535/udp
ufw reload
echo "✅ Firewall configured"

# Enable and start Coturn
echo "🚀 Starting Coturn service..."
systemctl enable coturn
systemctl daemon-reload
systemctl start coturn

# Wait for service to start
sleep 2

# Check status
if systemctl is-active --quiet coturn; then
    echo "✅ Coturn is running!"
else
    echo "❌ Coturn failed to start. Check logs:"
    echo "   sudo journalctl -u coturn -n 50"
    exit 1
fi

# Save credentials to file
CREDS_FILE="/root/turn_credentials.txt"
cat > $CREDS_FILE << EOF
=================================
TURN Server Credentials
=================================

Server IP: $PUBLIC_IP
Secret Key: $SECRET

TURN URLs:
- turn:$PUBLIC_IP:3478
- turn:$PUBLIC_IP:3478?transport=tcp
- turns:$PUBLIC_IP:5349?transport=tcp

Add these to your backend server.ts:
const TURN_SERVER = '$PUBLIC_IP';
const TURN_SECRET = '$SECRET';

=================================
EOF

echo ""
echo "✅ Setup Complete!"
echo ""
echo "📋 Credentials saved to: $CREDS_FILE"
echo ""
echo "🔍 View credentials:"
echo "   cat $CREDS_FILE"
echo ""
echo "📊 Check status:"
echo "   sudo systemctl status coturn"
echo ""
echo "📝 View logs:"
echo "   sudo tail -f /var/log/turnserver.log"
echo ""
echo "🧪 Test TURN server:"
echo "   https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/"
echo ""
echo "⚠️  Set these in your CHAT BACKEND (Render / .env):"
echo "   TURN_SERVER=$PUBLIC_IP"
echo "   TURN_SECRET=$SECRET"
echo ""
