#!/bin/sh
#
# metadata_begin
# recipe: Teamspeak
# tags: alma,centos9,centos9-stream,debian10,debian11,debian12,fedora,oracle,rocky,ubuntu2004,ubuntu2204,ubuntu2404
# revision: 4
# description_ru: Teamspeak 3 сервер. Информацию можно найти в файле /root/Teamspeak-final.txt
# description_en: Teamspeak 3 server. Information placed in file /root/Teamspeak-final.txt
# metadata_end
#
RNAME=Teamspeak

set -x

LOG_PIPE=/tmp/log.pipe.$$
mkfifo ${LOG_PIPE}
LOG_FILE=/root/${RNAME}.log
touch ${LOG_FILE}
chmod 600 ${LOG_FILE}
tee < ${LOG_PIPE} ${LOG_FILE} &
exec > ${LOG_PIPE}
exec 2> ${LOG_PIPE}

killjobs() {
    test -n "$(jobs -p)" && kill $(jobs -p) || :
}
trap killjobs INT TERM EXIT

echo
echo "== Recipe ${RNAME} started at $(date) =="
echo

# Переменные
TSVER="3.13.7"
TS_HOME="/home/teamspeak"
ARCH="amd64"
TS_URL="https://files.teamspeak-services.com/releases/server/${TSVER}/teamspeak3-server_linux_${ARCH}-${TSVER}.tar.bz2"
TS_ISP="http://download.ispsystem.com/external/ts3cp.tar.gz"

# Определение IP-адресов и сетевой карты
ipv4Addr=$(ip route get 1 | grep -Po '(?<=src )[^ ]+')

# Информация об ОС
. /etc/os-release
osLike="${ID_LIKE}"
[ "${ID}" = "debian" ] && osLike="debian"
echo ${ID_LIKE} | grep -q "rhel\|fedora" && osLike="rhel"
[ "${ID}" = "fedora" ] && osLike="rhel"
unaID=$(echo ${VERSION_ID} | sed -r 's/\..+//')

# Определение имени демона и конфирационного каталога Apache2
[ "${osLike}" = "debian" ] && { webServer="apache2" ; webServerSiteDir="/etc/apache2/sites-available/" ; }
[ "${osLike}" = "rhel" ] && { webServer="httpd" ; webServerSiteDir="/etc/httpd/conf.d/" ; }
[ -z "${webServer}" ] && exit 1
[ -z "${webServerSiteDir}" ] && exit 1

# Определение имени пользователя Apache2
[ "${osLike}" = "debian" ] && webUser="www-data"
[ "${osLike}" = "rhel" ] && webUser="apache"
[ -z "${webUser}" ] && exit 1

# Определение пакетного менеджера
DNF="/usr/bin/yum"
[ -f /usr/bin/dnf ] && DNF="/usr/bin/dnf"
[ -f /usr/bin/apt ] && { export DEBIAN_FRONTEND=noninteractive ; DNF="apt_Installer" ; }
[ -n "${DNF}" ] || exit 1

# Финальный текст
final_text() {
cat > /root/${RNAME}-final.txt <<- EOF
=========================
Работа скрипта ${RNAME} успешно завершена.
Логин, пароль и токен можно найти в файле /root/ts3_login_data
Журнал выполнения вы можете посмотреть в файле /root/${RNAME}.log
Панель TeamSpeak3 доступна по адресу:
http://${ipv4Addr}/index.php
=========================

=========================
The ${RNAME} script completed successfully.
Login, password and token placed in file /root/ts3_login_data
You can see the execution log in /root/${RNAME}.log.
The TeamSpeak3 panel is available at:
http://${ipv4Addr}/index.php
=========================
EOF
}

# Определяем инсталятор apt и его опции. Обходим фоновые задачи установки и одновления ОС
apt_Installer() {
while ps uxaww | grep -v grep | grep -Eq 'apt|dpkg|unattended' ; do echo "waiting..." ; sleep 5 ; done && \
/usr/bin/apt -o Dpkg::Options::="--force-confold" -o Dpkg::Options::="--force-confdef" -q --allow-downgrades --allow-remove-essential --allow-change-held-packages $@
}

# Установка основных программ и подготовка базовых репозиториев
install_soft() {
if [ "${osLike}" = "debian" ]; then
	[ $(systemctl is-active unattended-upgrades.service 2>/dev/null) = "active" ] && { systemctl stop unattended-upgrades.service && unattServ="1" ; }
	${DNF} update && ${DNF} -y install lsb-release ca-certificates gnupg2 bsdutils sqlite3
fi

[ "${osLike}" = "rhel" ] && { ${DNF} -y install policycoreutils-python-utils ; ${DNF} -y update libmodulemd ; ${DNF} -y install sqlite ; }
${DNF} -y install bzip2 openssl bzip2 wget curl tar
${DNF} -y install tuned
systemctl enable --now tuned 2>/dev/null
}

# Определение и настройка фаервола
config_firewall() {
if [ -f /usr/sbin/ufw ] && $(ufw status | grep -i "Status" | grep -qi " active\|enable"); then
	ufw allow http
	ufw allow ssh
	ufw allow 9987/udp
	ufw allow 30033/tcp
	ufw allow 10011/tcp
fi
if [ -f /usr/sbin/firewalld -a $(systemctl is-active firewalld.service 2>/dev/null) = "active" ]; then
	firewalldZone="$(firewall-cmd --get-default-zone)"
	[ ! -f /usr/lib/firewalld/services/teamspeak.xml ] && \
	cat << 'EOF' > /etc/firewalld/services/teamspeak.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>teamspeak</short>
  <description>TeamSpeak rule</description>
  <port protocol="udp" port="9987"/>
  <port protocol="tcp" port="30033"/>
  <port protocol="tcp" port="10011"/>
</service>
EOF
	chmod 644 /etc/firewalld/services/teamspeak.xml
	firewall-cmd --reload
	firewall-cmd --permanent --zone=${firewalldZone} --remove-service=dhcpv6-client 2>&1 >/dev/null || return 0
	firewall-cmd --permanent --zone=${firewalldZone} --add-service=http
	firewall-cmd --permanent --zone=${firewalldZone} --add-service=teamspeak
	firewall-cmd --reload
fi
}

# Установка Apache2
install_web() {
${DNF} -y install ${webServer}
[ "${osLike}" = "debian" ] && rm -rf /usr/share/apache2/default-site/index.html || return 0
}

# Установка PHP
install_php() {
case "${osLike}" in
	rhel )
		[ "${ID}" = "fedora" ] && { ${DNF} -y install https://mirror.hoztnode.net/remi/fedora/remi-release-${unaID}.rpm ; } || \
		{ ${DNF} -y install https://mirror.hoztnode.net/remi/enterprise/remi-release-${unaID}.rpm ; }
		sed -i 's/rpms.remirepo.net/mirror.hoztnode.net\/remi/ ; s/^mirrorlist/#mirrorlist/ ; s/^#baseurl/baseurl/' /etc/yum.repos.d/remi*.repo
		${DNF} -y module list reset php
		${DNF} -y module enable php:remi-7.4
		${DNF} -y install php
		;;
	debian )
		if [ "${ID}" = "ubuntu" -a ${unaID} -ge 22 ]; then
			${DNF} -y install software-properties-common
			LC_ALL=C.UTF-8 add-apt-repository -y ppa:ondrej/php
			${DNF} update
			${DNF} -y install php7.4 libapache2-mod-php7.4
		elif [ "${ID}" = "debian" -a ${unaID} -ge 12 ]; then
			${DNF} -y install apt-transport-https
			wget -O /etc/apt/trusted.gpg.d/php.gpg https://mirror.hoztnode.net/mirrors/deb.sury.org/apt.gpg
			echo "deb [signed-by=/etc/apt/trusted.gpg.d/php.gpg] https://mirror.hoztnode.net/mirrors/deb.sury.org/php/ ${VERSION_CODENAME} main" | tee /etc/apt/sources.list.d/php.list
			${DNF} update
			${DNF} -y install php7.4 libapache2-mod-php7.4
		else
			${DNF} -y install php
			${DNF} -y install libapache2-mod-php
		fi
		;;
esac
}

# Настройка Apache2
config_apache() {
systemctl enable ${webServer}.service
systemctl restart ${webServer}.service
}

install_ts() {
useradd teamspeak
mkdir -p ${TS_HOME}/ts3
wget --no-check-certificate -O ${TS_HOME}/teamspeak3-server.tar.bz2 ${TS_URL}
tar --strip-components=1 -xpf ${TS_HOME}/teamspeak3-server.tar.bz2 -C ${TS_HOME}/ts3 && \
rm -rf ${TS_HOME}/teamspeak3-server.tar.bz2
touch ${TS_HOME}/ts3/.ts3server_license_accepted
chown -R teamspeak:teamspeak ${TS_HOME}
}

config_ts() {
cd ${TS_HOME}/ts3
/usr/bin/su teamspeak -c "/bin/bash ./ts3server_startscript.sh start" > /root/credits.txt 2>&1
sleep 5
local login=serveradmin
local password=$(cat /root/credits.txt | sed -r -n 's/.+password=\s*"(.+)"/\1/p')
local token=$(cat /root/credits.txt | sed -r -n 's/.+token=\s*"*?(.+)"*?/\1/p')
local apikey=$(cat /root/credits.txt | sed -r -n 's/.+apikey=\s*"*?(.+)"*?/\1/p')
chmod 600 /root/credits.txt

cat > /root/ts3_login_data << EOF
login=${login}
password=${password}
token=${token}
apikey=${apikey}
EOF
chmod 600 /root/ts3_login_data
rm -f /root/credits.txt
}

systemd_ts() {
cat > /etc/systemd/system/teamspeak.service <<- EOF
[Unit]
Description=Teamspeak Service
Wants=network.target

[Service]
WorkingDirectory=${TS_HOME}
User=teamspeak
ExecStart=${TS_HOME}/ts3/ts3server_minimal_runscript.sh
ExecStop=${TS_HOME}/ts3/ts3server_startscript.sh stop
ExecReload=${TS_HOME}/ts3/ts3server_startscript.sh restart
Restart=always
RestartSec=15
SyslogIdentifier=teamspeak

[Install]
WantedBy=multi-user.target
EOF
chmod 644 /etc/systemd/system/teamspeak.service
systemctl daemon-reload
/usr/bin/su teamspeak -c "/bin/bash ./ts3server_startscript.sh stop" 2>&1
sleep 5
systemctl start teamspeak.service
systemctl enable teamspeak.service
}

config_web_ts() {
[ -d /var/www/html ] && { WEB_ROOT="/var/www/html/" ; } || { WEB_ROOT="/var/www/" ; }
wget --no-check-certificate ${TS_ISP} -O ${WEB_ROOT}/ts3cp.tar.gz
tar --strip-components=1 -xpf ${WEB_ROOT}/ts3cp.tar.gz -C ${WEB_ROOT}
rm -rf ${WEB_ROOT}/ts3cp.tar.gz

mkdir -p ${WEB_ROOT}/templates_c ${WEB_ROOT}/icons
#echo >> ${WEB_ROOT}/motd.txt
echo "You can find login data in file /root/ts3_login_data" > ${WEB_ROOT}/motd.txt

mv ${WEB_ROOT}/config.php ${WEB_ROOT}/config.orig.php
cat << 'EOF' > ${WEB_ROOT}/config.php
<?php
/*
*Copyright (C) 2012-2013  Psychokiller
*
*This program is free software; you can redistribute it and/or modify it under the terms of 
*the GNU General Public License as published by the Free Software Foundation; either 
*version 3 of the License, or any later version.
*
*This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
*without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
*See the GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. 
*/
if(!defined("SECURECHECK")) {die($lang['error_file_alone']);} 
/*
REGARD!!
If you use the web interface, they must write the webserver ip in the query_ip_whitelist.txt.
After adding the ip, the server must be restarted!

Add more Server Ip's.
For Example
$server[0]['alias']= "Lokaler Server1";
$server[0]['ip']= "127.0.0.1";
$server[0]['tport']= "10011";

$server[1]['alias']= "Lokaler Server2";
$server[1]['ip']= "127.0.0.2";
$server[1]['tport']= "20022";
*/

$server[0]['alias']= "Server #1";
$server[0]['ip']= "127.0.0.1";
$server[0]['tport']= 10011;
$cfglang        =       "en";                   //Language German = de, English = en, Netherlandish=nl (by pd1evl), French = fr (by supra63200)
$duration = "100";                              //Set the Limit for Clients show per Page on Client List
$fastswitch=true;                               //If true you can switch the Server on the header
$showicons="left";                              //Define the position where the icons on the Viewer will show left or right
$style="bootstrap";                                     //Chose your design  set 'new' for the default design or the name of your own create design
$msgsend_name="Control_panel";  //This Name will be show if you send a message to a Server
$show_motd=true;                                // Set it to false to not show the message of the day window
$show_version=true;                             // Set it to false to not show the Webinterface Version on the footer
?>
EOF

chown -R ${webUser} ${WEB_ROOT}
rm -rf ${WEB_ROOT}/index.html
}

install_soft
install_web
install_php
install_ts
config_ts
systemd_ts
config_web_ts
config_apache
config_firewall

# Включаем обратно сервис самообновления Ubuntu
[ -n "${unattServ}" ] && systemctl start unattended-upgrades.service

# Проверка
q=0
i=20
while [ $q -le $i ]; do
	curl -v --silent http://127.0.0.1/index.php 2>&1 | grep -q "TS3" && final_text && exit 0
	q=$(($q + 1))
	sleep 1
done

exit 1
