#!/bin/bash

set -e

echo "=== TeamSpeak 3 Auto Installer ==="

TS3_URL="https://trex.emeraldteam.ir/Apps/teamspeak3-server_linux_amd64-3.13.7.tar.bz2"
TS3_FILE="teamspeak3-server.tar.bz2"
TS3_DIR="/opt/teamspeak"
TS3_USER="teamspeak"

# Update system
echo "[+] Updating system..."
apt update && apt upgrade -y

# Install dependencies
echo "[+] Installing dependencies..."
apt install -y bzip2 tar wget curl

# Create user
echo "[+] Creating TS3 user..."
id -u $TS3_USER &>/dev/null || useradd -m -d $TS3_DIR -s /bin/bash $TS3_USER

# Create directory
echo "[+] Creating install directory..."
mkdir -p $TS3_DIR

# Download file
echo "[+] Downloading TeamSpeak..."
wget -O /tmp/$TS3_FILE $TS3_URL

# Extract
echo "[+] Extracting..."
tar -xjf /tmp/$TS3_FILE -C /tmp

EXTRACTED_DIR=$(find /tmp -maxdepth 1 -type d -name "teamspeak3-server_linux_amd64*" | head -n 1)

cp -r $EXTRACTED_DIR/* $TS3_DIR

# Accept license
echo "[+] Accepting license..."
touch $TS3_DIR/.ts3server_license_accepted

# Set permissions
echo "[+] Setting permissions..."
chown -R $TS3_USER:$TS3_USER $TS3_DIR

# Create systemd service
echo "[+] Creating systemd service..."

cat <<EOF > /etc/systemd/system/teamspeak.service
[Unit]
Description=TeamSpeak 3 Server
After=network.target

[Service]
WorkingDirectory=$TS3_DIR
User=$TS3_USER
Group=$TS3_USER
Type=forking
ExecStart=$TS3_DIR/ts3server_startscript.sh start
ExecStop=$TS3_DIR/ts3server_startscript.sh stop
ExecReload=$TS3_DIR/ts3server_startscript.sh restart
PIDFile=$TS3_DIR/ts3server.pid
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd
systemctl daemon-reexec
systemctl daemon-reload

# Enable & start
echo "[+] Starting TeamSpeak..."
systemctl enable teamspeak
systemctl start teamspeak

# Wait and show status
sleep 3
systemctl status teamspeak --no-pager

# Print admin token hint
echo ""
echo "========================================"
echo " Server installed successfully!"
echo "========================================"
echo " Get admin token with:"
echo " journalctl -u teamspeak -n 100 --no-pager"
echo ""