#!/bin/bash

if [ "$EUID" -ne 0 ]; then
    echo "Please run as root or with sudo"
    exit 1
fi

setup_permissions() {
    local DOMAIN=$1
    
    # Create secure directory for coturn certs
    mkdir -p /etc/coturn/certs
    
    # Copy certificates with proper permissions
    cp /etc/letsencrypt/live/${DOMAIN}/fullchain.pem /etc/coturn/certs/
    cp /etc/letsencrypt/live/${DOMAIN}/privkey.pem /etc/coturn/certs/
    
    # Set proper ownership and permissions
    chown -R turnserver:turnserver /etc/coturn/certs
    chmod 600 /etc/coturn/certs/*.pem
}

wait_for_apt() {
    while fuser /var/lib/dpkg/lock >/dev/null 2>&1 || fuser /var/lib/apt/lists/lock >/dev/null 2>&1 || fuser /var/cache/apt/archives/lock >/dev/null 2>&1 || fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1; do
        echo "Waiting for other apt processes to finish..."
        sleep 5
    done
}

configure_ssl() {
    local DOMAIN=$1
    
    # Check if port 80 is in use
    if netstat -tuln | grep ':80 '; then
        echo "Warning: Port 80 is in use. Stopping potentially conflicting services..."
        systemctl stop nginx 2>/dev/null || true
        systemctl stop apache2 2>/dev/null || true
    fi
    
    # Install certbot if needed
    if ! command -v certbot >/dev/null; then
        echo "Installing certbot..."
        wait_for_apt
        apt-get install certbot -y
    fi
    
    # Verify domain points to this server
    LOCAL_IP=$(curl -s https://api.ipify.org)
    DOMAIN_IP=$(dig +short "$DOMAIN")
    
    echo "Verifying domain configuration..."
    echo "Server IP: $LOCAL_IP"
    echo "Domain IP: $DOMAIN_IP"
    
    if [ "$LOCAL_IP" != "$DOMAIN_IP" ]; then
        echo "Warning: Domain $DOMAIN does not point to this server's IP ($LOCAL_IP)"
        read -p "Continue anyway? (y/N): " CONTINUE
        if [ "${CONTINUE,,}" != "y" ]; then
            return 1
        fi
    fi
    
    # Try to get the cert
    if ! certbot certonly --standalone --preferred-challenges http -d "$DOMAIN"; then
        echo "Failed to obtain SSL certificate. Trying alternative method..."
        if ! certbot certonly --standalone --preferred-challenges tls-alpn-01 -d "$DOMAIN"; then
            return 1
        fi
    fi
    
    # Update turnserver.conf with SSL settings
    cat >> /etc/turnserver.conf << EOL
cert=/etc/coturn/certs/fullchain.pem
pkey=/etc/coturn/certs/privkey.pem
tls-listening-port=443
EOL
    
    # Setup permissions after getting certificates
    setup_permissions "$DOMAIN"
    
    # Update the renewal hook to copy new certs
    mkdir -p /etc/letsencrypt/renewal-hooks/deploy
    cat > /etc/letsencrypt/renewal-hooks/deploy/coturn-reload << EOL
#!/bin/bash
cp /etc/letsencrypt/live/${DOMAIN}/fullchain.pem /etc/coturn/certs/
cp /etc/letsencrypt/live/${DOMAIN}/privkey.pem /etc/coturn/certs/
chown turnserver:turnserver /etc/coturn/certs/*.pem
chmod 600 /etc/coturn/certs/*.pem
systemctl --signal=SIGUSR2 kill coturn
EOL
    chmod +x /etc/letsencrypt/renewal-hooks/deploy/coturn-reload
    
    # Restart coturn to apply SSL configuration
    systemctl restart coturn
    
    return 0
}

# Main installation function
install_coturn() {
    local DOMAIN=$1
    local USERNAME=$2
    local PASSWORD=$3
    
    # Install required packages
    apt-get update
    apt-get install coturn curl dnsutils -y
    
	# Configure system limits
	echo "fs.file-max = 65535" >> /etc/sysctl.conf
	sudo sysctl -p
	# Add permanent ulimit settings
	echo "* soft nofile 65535" >> /etc/security/limits.conf
	echo "* hard nofile 65535" >> /etc/security/limits.conf
	echo "root soft nofile 65535" >> /etc/security/limits.conf
	echo "root hard nofile 65535" >> /etc/security/limits.conf
    
    # Enable TURN server
    echo "TURNSERVER_ENABLED=1" > /etc/default/coturn
    
    # Generate base turnserver configuration
    cat > /etc/turnserver.conf << EOL
listening-port=3478
alt-listening-port=0
fingerprint
lt-cred-mech
min-port=49152
max-port=65535
user=${USERNAME}:${PASSWORD}
stale-nonce=600
realm=${DOMAIN}
server-name=${DOMAIN}
no-multicast-peers
no-stdout-log
EOL
    
    # Set proper permissions for binding to privileged ports
    setcap cap_net_bind_service=+ep /usr/bin/turnserver
    
    # Configure journald log limits
    mkdir -p /etc/systemd/journald.conf.d/
    cat > /etc/systemd/journald.conf.d/coturn.conf << EOL
[Journal]
SystemMaxUse=50M
RuntimeMaxUse=50M
EOL

    # Restart journald to apply changes
    systemctl restart systemd-journald

    # Start services
    systemctl daemon-reload
    systemctl enable coturn
    systemctl start coturn
}

# Swap setup
echo "Increasing swap memory to 16GB"
if [ -f /swapfile ]; then
    sudo swapoff -a
    sudo rm /swapfile
fi
sudo fallocate -l 16G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
if ! grep -q '/swapfile none swap sw 0 0' /etc/fstab; then
    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
fi

# Main script execution
echo "TURN Server Installation and Configuration"
echo "----------------------------------------"

# Get or verify domain
while true; do
    read -p "Enter your domain (e.g., turn.example.com): " DOMAIN
    echo "Verifying domain..."
    if dig +short "$DOMAIN" >/dev/null; then
        break
    else
        echo "Warning: Domain $DOMAIN does not appear to be configured. Please verify DNS settings."
        read -p "Try a different domain? (Y/n): " RETRY
        if [ "${RETRY,,}" = "n" ]; then
            break
        fi
    fi
done

read -p "Enter username for TURN: " USERNAME
read -s -p "Enter password for TURN: " PASSWORD
echo

# Install base TURN server
install_coturn "$DOMAIN" "$USERNAME" "$PASSWORD"

# Configure SSL if desired
read -p "Do you want to enable SSL/TLS support? (y/N): " ENABLE_SSL
if [ "${ENABLE_SSL,,}" = "y" ]; then
    if ! configure_ssl "$DOMAIN"; then
        echo "SSL configuration failed. You can retry SSL setup later by running:"
        echo "certbot delete"
        echo "certbot certonly --standalone -d $DOMAIN"
        echo "Then restart coturn: systemctl restart coturn"
    fi
fi

# Display status
systemctl status coturn

echo "Installation complete!"
echo "----------------------------------------"
echo "Domain: $DOMAIN"
echo "Username: $USERNAME"
echo "STUN/TURN ports: 3478 (default)"
if [ "${ENABLE_SSL,,}" = "y" ]; then
    echo "TLS enabled on port 443"
    echo "SSL certificates will automatically renew via certbot"
fi
