#!/bin/bash

# Local Coturn TURN Server Setup (for testing on localhost)
# Run this on your development machine (Ubuntu/Linux)

set -e

echo "🚀 Setting up Coturn LOCALLY for testing..."

# Check if running on Linux
if [[ "$OSTYPE" != "linux-gnu"* ]]; then
    echo "❌ This script is for Linux. For Mac, use: brew install coturn"
    exit 1
fi

# Install Coturn
echo "📦 Installing Coturn..."
sudo apt-get update -y
sudo apt-get install -y coturn

# Get local IP (for same network testing)
LOCAL_IP=$(hostname -I | awk '{print $1}')
echo "🌐 Your local IP: $LOCAL_IP"

# Generate secret
SECRET=$(openssl rand -hex 16)
echo "🔐 Generated secret: $SECRET"

# Backup original config
if [ -f /etc/turnserver.conf ]; then
    sudo cp /etc/turnserver.conf /etc/turnserver.conf.backup
fi

# Create simple local config
echo "⚙️  Creating local Coturn configuration..."
sudo tee /etc/turnserver.conf > /dev/null << EOF
# Local Coturn Configuration for Testing

# Listening ports
listening-port=3478

# Local IP
listening-ip=$LOCAL_IP
relay-ip=$LOCAL_IP

# Simple authentication
lt-cred-mech
user=test:test123

# Realm
realm=localhost

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

# Enable TCP relay
tcp-relay

# Allow loopback (for local testing)
no-loopback-peers
EOF

echo "✅ Configuration created"

# Open firewall (if ufw is active)
if command -v ufw &> /dev/null; then
    echo "🔥 Configuring firewall..."
    sudo ufw allow 3478/tcp
    sudo ufw allow 3478/udp
fi

# Start Coturn
echo "🚀 Starting Coturn..."
sudo systemctl enable coturn
sudo systemctl restart coturn

# Wait and check status
sleep 2

if systemctl is-active --quiet coturn; then
    echo ""
    echo "✅ Coturn is running locally!"
    echo ""
    echo "================================================"
    echo "LOCAL TURN SERVER CREDENTIALS"
    echo "================================================"
    echo ""
    echo "Server IP: $LOCAL_IP"
    echo "Port: 3478"
    echo "Username: test"
    echo "Password: test123"
    echo ""
    echo "TURN URLs:"
    echo "  turn:$LOCAL_IP:3478"
    echo "  turn:$LOCAL_IP:3478?transport=tcp"
    echo ""
    echo "================================================"
    echo ""
    echo "📝 Update your webrtc.ts with:"
    echo ""
    echo "export const GOOGLE_STUN_SERVERS: RTCIceServer[] = ["
    echo "  { urls: 'stun:stun.l.google.com:19302' },"
    echo "  {"
    echo "    urls: 'turn:$LOCAL_IP:3478?transport=tcp',"
    echo "    username: 'test',"
    echo "    credential: 'test123',"
    echo "  },"
    echo "];"
    echo ""
    echo "================================================"
    echo ""
    echo "🧪 Test with both phones on SAME WiFi network"
    echo ""
    echo "📊 Check status: sudo systemctl status coturn"
    echo "📝 View logs: sudo tail -f /var/log/turnserver.log"
    echo ""
else
    echo "❌ Coturn failed to start"
    echo "Check logs: sudo journalctl -u coturn -n 50"
    exit 1
fi
