#!/bin/sh
##### Instalacao do servidor de Streaming #####
dominio_source_instalador="https://installvox.udiwebsistem.com.br/instalador"

# Cores
EfeitoCorTitulo="\033[0;35m"
EfeitoCorOK="\033[0;32m"
EfeitoCorAlerta="\033[1;33m"
EfeitoCorErro="\033[0;31m"
EfeitoFecha="\033[0m"

clear

if [ "$1" == "--help" ]; then

echo
echo -e "$EfeitoCorTitulo Modo de uso: sh instalador-stm-audio-ic-ls-almalinux.sh OPCOES $EfeitoFecha"
echo
echo -e "$EfeitoCorTitulo --skip-ssl            Pula a instalação do SSL(use caso esteja migrando servidor e DNS não esteja configurado ainda) $EfeitoFecha"
echo -e "$EfeitoCorTitulo --skip-inter          Desativa modo interativo para que não seja necessário aperta teclas para continuar $EfeitoFecha"
echo -e "$EfeitoCorTitulo --ssl                 Instala somente SSL $EfeitoFecha"
echo
exit

fi

echo
echo -e "$EfeitoCorTitulo ###################################################### $EfeitoFecha"
echo -e "$EfeitoCorTitulo # Script de Instalação de Servidor Streming de Audio # $EfeitoFecha"
echo -e "$EfeitoCorTitulo # Criado por Cesar - cesarlwh@gmail.com              # $EfeitoFecha"
echo -e "$EfeitoCorTitulo ###################################################### $EfeitoFecha"
echo

if [ x`echo "$1 $2" | egrep -c "\-\-ffmpeg|\-\-ssl|\-\-migrar"` = x0 ]; then

echo -e "$EfeitoCorOK Instalação Servidor de Streaming Audio ShoutCast + IceCast + Liquidsoap para AlmaLinux 9.x $EfeitoFecha"
echo

echo -e "$EfeitoCorAlerta Informe o usuario do mysql usado na instalacao do painel de controle $EfeitoFecha"
read -p 'Usuario: ' usuario_mysql

echo -e "$EfeitoCorAlerta Informe o nome do bano de dados do mysql usado na instalacao do painel de controle $EfeitoFecha"
read -p 'BD: ' banco_mysql

echo -e "$EfeitoCorAlerta Informe a senha do mysql usado na instalacao do painel de controle $EfeitoFecha"
read -p 'Senha: ' senha_mysql

echo -e "$EfeitoCorAlerta Informe o domínio do painel de controle $EfeitoFecha"
read -p 'Domínio Painel: ' dominio_painel

echo -e "$EfeitoCorAlerta Informe o hostname deste servidor para o SSL por ex.: stm1.painel.com $EfeitoFecha"
echo -e "$EfeitoCorAlerta Antes de prosseguir o DNS deve estar apontado para que SSL seja validado ou gerará erros $EfeitoFecha"
read -p 'Dominio Servidor: ' dominio_servidor

echo -e "$EfeitoCorAlerta Informe a porta para SSH(Padrão: 6985) $EfeitoFecha"
read -p 'Porta SSH: ' porta_ssh

echo -e "$EfeitoCorAlerta Informe a senha do usuario de programetes gerado ao instalar o painel de controle(se não possui programetes deixe em banco) $EfeitoFecha"
read -p 'Senha: ' senha_programetes

echo -e "$EfeitoCorAlerta Informe a senha do usuario de programas gerado ao instalar o painel de controle(se não possui programas deixe em banco) $EfeitoFecha"
read -p 'Senha: ' senha_programas

if [ x`echo "$1 $2" | grep -c "\-\-skip\-ssl"` = x1 ]; then

echo -e "$EfeitoCorAlerta O SSL não será instalado agora(--skip-ssl) $EfeitoFecha"

fi

echo
echo -e "$EfeitoCorTitulo Deseja instalar junto a este servidor o Camera Studio(se você já tem instalado em outro servidor não é necessário) $EfeitoFecha"
read -p 'Confirma(y/n): ' confirma_cs

if [ "$confirma_cs" != "${confirma_cs#[Yy]}" ] ;then

echo -e "$EfeitoCorAlerta Informe senha root deste servidor para configurar o admin do wowza/rtmp $EfeitoFecha"
read -p 'Senha root: ' senha_root_servidor

echo -e "$EfeitoCorAlerta Informe o dominio a ser usado no Camera Studio por exemplo cs1.painel.com o DNS DEVEVE ESTAR PROPAGADO antes de continuar neste ponto.... $EfeitoFecha"
read -p 'Dominio: ' dominio_cs

fi

echo
echo -e "$EfeitoCorTitulo Confirme se os dados digitados estão corretos $EfeitoFecha"
read -p 'Confirma(y/n): ' confirma

if [ "$confirma" != "${confirma#[Nn]}" ] ;then

clear

echo
echo -e "$EfeitoCorAlerta Reinicie o instalador com os dados corretos... $EfeitoFecha"
echo

exit 1

fi

porta_ssl="1443"

if [ -z "$porta_ssh" ]; then
porta_ssh="6985"
fi

echo -e "$EfeitoCorOK Iniciando instalacao dos modulos... $EfeitoFecha"
echo

if [ "$1" == "--skip-inter" ] || [ "$2" == "--skip-inter" ]; then

echo
echo -e "$EfeitoCorAlerta Modo interativo desativado! $EfeitoFecha"
echo

silenciar="sim"

fi

echo "nameserver 8.8.8.8" > /etc/resolv.conf
echo "nameserver 8.8.4.4" >> /etc/resolv.conf

sudo dnf install epel-release -y

sudo dnf install epel-next-release -y

sudo dnf update -y

sudo dnf install iptables usermode wget nano sendmail screen nmap perl rsync gcc nano openssh-server openssh-clients kernel-devel postgresql-libs gcc glibc.i686 glibc-devel.i686 zlib-devel.i686 ncurses-devel.i686 libX11-devel.i686 libXrender.i686 libXrandr.i686 postgresql-libs openssl-devel glibc-devel unzip git net-tools sqlite-devel -y

sudo dnf install ca-certificates -y

sudo dnf install tar -y

if ! [ -x "/usr/bin/perl" ]; then

echo
echo -e "$EfeitoCorErro Falha na instalacao de modulos essenciais, instalação abotada, verificar logs na tela. $EfeitoFecha"
echo

exit 1
fi

cd
wget https://www.rarlab.com/rar/rarlinux-x64-5.5.0.tar.gz
tar -zxf rarlinux-x64-5.5.0.tar.gz
cd rar
cp -v rar unrar /usr/local/bin/

sudo dnf install vnstat -y

ln -s /usr/bin/nano /usr/bin/pico

iptables -F

echo 'SELINUX=disabled' > /etc/selinux/config
echo 'SELINUXTYPE=targeted' >> /etc/selinux/config

setenforce 0

systemctl disable firewalld
systemctl stop firewalld

semanage port -a -t ssh_port_t -p tcp $porta_ssh

perl -i -p -e "s/#Port 22/Port $porta_ssh/" /etc/ssh/sshd_config

iptables -F

adduser streaming

echo "streaming:`echo $dominio_painel | /usr/bin/md5sum | /usr/bin/head -c 10`" | chpasswd

usermod -u 500 streaming
groupmod -g 500 streaming

chmod 0777 /home/streaming

echo >> /etc/bashrc
echo 'ulimit -n 4096 -u 14335 -m unlimited -d unlimited -s 8192 -c 1000000 -v unlimited 2>/dev/null' >> /etc/bashrc
echo "LS_OPTIONS='--color=tty -F -a -b -T 0 -l -h';" >> /etc/bashrc
echo 'export LS_OPTIONS;' >> /etc/bashrc
echo "alias ls='/bin/ls \$LS_OPTIONS';" >> /etc/bashrc
echo 'eval `dircolors -b`' >> /etc/bashrc
echo 'PS1="\u@\h [\w]# "' >> /etc/bashrc
echo 'export VISUAL=nano' >> /etc/bashrc

source /etc/bashrc

if [ ! "$silenciar" ]; then
echo
read -n 1 -s -r -p "Pressione qualquer tecla para continuar..."
echo
fi

echo -e "$EfeitoCorOK Iniciando instalacao dos arquivos do painel e servidor de streaming, esta parte pode demorar... $EfeitoFecha"
echo

mkdir /home/instalador
cd /home/instalador

wget -q ${dominio_source_instalador}/audio-almalinux-sources.tar.gz

tar -zxvf audio-almalinux-sources.tar.gz

mv src-audio-centos-6-7-8.tar.gz /src-audio-centos-6-7-8.tar.gz

cd /

tar -zxvf src-audio-centos-6-7-8.tar.gz

rm -f src-audio-centos-6-7-8.tar.gz

mv /home/instalador/web.tar.gz /home/streaming/

cd /home/streaming/

tar -zxvf web.tar.gz
rm -f web.tar.gz

mkdir --mode=0777 /home/streaming/logs
mkdir --mode=0777 /home/streaming/playlists
mkdir --mode=0777 /home/streaming/configs
mkdir --mode=0777 /home/streaming/programas
mkdir --mode=0777 /home/streaming/programetes

cd /home/instalador

sudo dnf update -y

unalias cp

unalias mv

cd /home/streaming/

sudo dnf install pure-ftpd httpd mod_ssl -y

dnf install https://rpms.remirepo.net/enterprise/remi-release-9.rpm -y 
dnf module install php:remi-7.4 -y

dnf install php php-mysqlnd php-pdo php-mbstring php-mcrypt php-xml php-gd php-curl php-bcmath php-common php-process php-tidy php-pear php-devel -y

cat <<EOT > /etc/httpd/conf/httpd.conf
ServerRoot "/etc/httpd"

Listen 555

Include conf.modules.d/*.conf

User streaming
Group streaming

ServerAdmin root@localhost

<Directory />
    AllowOverride none
    Require all denied
</Directory>

DocumentRoot "/home/streaming/web"

<Directory "/var/www">
    AllowOverride None
    Require all granted
</Directory>

<Directory "/home/streaming/web">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

<Files ".ht*">
    Require all denied
</Files>

ErrorLog "logs/error_log"

LogLevel warn

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
</IfModule>

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    TypesConfig /etc/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

AddDefaultCharset ISO-8859-1

<IfModule mime_magic_module>
    MIMEMagicFile conf/magic
</IfModule>

EnableSendfile on

IncludeOptional conf.d/*.conf
EOT

echo 'LoadModule mpm_event_module modules/mod_mpm_event.so' > /etc/httpd/conf.modules.d/00-mpm.conf

sed -i 's/apache/streaming/g' /etc/php-fpm.d/www.conf

sed -i '/max_execution_time/d' /etc/php.ini
sed -i '/max_input_time/d' /etc/php.ini
sed -i '/max_input_vars/d' /etc/php.ini
sed -i '/post_max_size/d' /etc/php.ini
sed -i '/upload_max_filesize/d' /etc/php.ini
sed -i '/memory_limit/d' /etc/php.ini
sed -i '/max_file_uploads/d' /etc/php.ini

echo '' >> /etc/php.ini
echo ';Tunning Cesar - cesarlwh@gmail.com' >> /etc/php.ini
echo 'max_execution_time = 1800' >> /etc/php.ini
echo 'max_input_time = 1800' >> /etc/php.ini
echo 'max_input_vars = 5000' >> /etc/php.ini
echo 'post_max_size = 200M' >> /etc/php.ini
echo 'upload_max_filesize = 200M' >> /etc/php.ini
echo 'memory_limit = 1024M' >> /etc/php.ini
echo 'max_file_uploads = 200' >> /etc/php.ini

chown -Rfv streaming.streaming /home/streaming/

rm -Rf /etc/localtime
ln -s /usr/share/zoneinfo/America/Sao_Paulo /etc/localtime

rpm -qa postfix | xargs rpm -e
rpm -qa ntp | xargs rpm -e

wget -O /usr/local/bin/youtube-dl https://github.com/yt-dlp/yt-dlp-nightly-builds/releases/download/2023.04.16.172652/yt-dlp

chmod 777 /usr/local/bin/youtube-dl
/usr/local/bin/youtube-dl -U

cd /root
wget https://downloads.sourceforge.net/lame/lame-3.99.5.tar.gz
tar -zxf lame-3.99.5.tar.gz
cd /root/lame-3.99.5
./configure --enable-shared --enable-nasm
make
make install
make distclean

echo '/usr/local/lib' >> /etc/ld.so.conf
echo '/usr/lib' >> /etc/ld.so.conf

cd /root
git clone http://git.videolan.org/git/x264.git
cd x264
./configure --enable-shared --enable-pic --disable-asm && make && make install

ldconfig

if [ ! "$silenciar" ]; then
echo
read -n 1 -s -r -p "Pressione qualquer tecla para continuar..."
echo
fi

echo -e "$EfeitoCorOK Configurando FTP para conexao com banco de dados do painel $EfeitoFecha"
echo

echo > /etc/pure-ftpd/pureftpd-mysql.conf

cat <<EOT >> /etc/pure-ftpd/pureftpd-mysql.conf
MYSQLServer     $dominio_painel
MYSQLPort       3306
MYSQLUser       $usuario_mysql
MYSQLPassword   $senha_mysql
MYSQLDatabase   $banco_mysql

MYSQLCrypt      cleartext

MYSQLGetPW      SELECT senha FROM streamings WHERE (porta="\L" AND status="1") AND (autodj="sim" AND espaco > 0)
MYSQLGetDir     SELECT ftp_dir FROM streamings WHERE (porta="\L" AND status="1") AND (autodj="sim" AND espaco > 0)
MySQLGetQTASZ   SELECT espaco FROM streamings WHERE (porta="\L" AND status="1") AND (autodj="sim" AND espaco > 0)

EOT

sed -i '/UseFtpUsers/d' /etc/pure-ftpd/pure-ftpd.conf
sed -i '/MinUID/d' /etc/pure-ftpd/pure-ftpd.conf

sed -i '/MYSQLDefaultUID/d' /etc/pure-ftpd/pureftpd-mysql.conf
sed -i '/MYSQLDefaultGID/d' /etc/pure-ftpd/pureftpd-mysql.conf
user_stm_id=`id -u streaming`

sed -i '/^$/d' /etc/pure-ftpd/pure-ftpd.conf
sed -i '/^[[:blank:]]*#/d;s/#.*//' /etc/pure-ftpd/pure-ftpd.conf
sed -i '/Authentication/d' /etc/pure-ftpd/pure-ftpd.conf
echo 'MySQLConfigFile             /etc/pure-ftpd/pureftpd-mysql.conf' >> /etc/pure-ftpd/pure-ftpd.conf
echo 'CreateHomeDir               yes' >> /etc/pure-ftpd/pure-ftpd.conf

echo "MinUID             $user_stm_id" >> /etc/pure-ftpd/pure-ftpd.conf
echo "MYSQLDefaultUID $user_stm_id" >> /etc/pure-ftpd/pureftpd-mysql.conf
echo "MYSQLDefaultGID $user_stm_id" >> /etc/pure-ftpd/pureftpd-mysql.conf

if [ ! "$silenciar" ]; then
echo
read -n 1 -s -r -p "Pressione qualquer tecla para continuar..."
echo
fi

sudo dnf install lynx -y

sudo dnf -y install certbot-apache

if ! [ -x "/usr/bin/certbot" ]; then
ln -s /usr/bin/certbot-3 /usr/bin/certbot
fi

if [ x`echo "$1 $2" | grep -c "\-\-skip\-ssl"` = x0 ]; then

echo -e "$EfeitoCorOK Instalando SSL Apache $EfeitoFecha"
echo

read -n 1 -s -r -p "Pressione qualquer tecla para continuar com a instalacao do SSL(DNS deve estar configurado e propagado)..."

systemctl stop httpd

> /etc/httpd/conf.d/ssl.conf

cat <<EOT >> /etc/httpd/conf.d/ssl.conf
# Configurado
LoadModule ssl_module modules/mod_ssl.so

Listen $porta_ssl

SSLPassPhraseDialog  builtin

SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)
SSLSessionCacheTimeout  300

SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin

SSLCryptoDevice builtin

EOT

certbot -n --agree-tos --register-unsafely-without-email certonly --standalone -d $dominio_servidor

if [ -f "/etc/letsencrypt/live/$dominio_servidor/cert.pem" ]; then

cat <<EOT >> /etc/httpd/conf.d/ssl.conf

NameVirtualHost *:$porta_ssl

<VirtualHost *:$porta_ssl>
    DocumentRoot /home/streaming/web
    ServerName $dominio_servidor

    ErrorLog logs/ssl_error_log
    TransferLog logs/ssl_access_log
    LogLevel warn

    SSLEngine on
    SSLProtocol all -SSLv2
    SSLCipherSuite DEFAULT:!EXP:!SSLv2:!DES:!IDEA:!SEED:+3DES
    SSLCertificateFile /etc/letsencrypt/live/$dominio_servidor/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/$dominio_servidor/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/$dominio_servidor/chain.pem

    SetEnvIf User-Agent ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

</VirtualHost>

EOT

else

echo
echo -e "$EfeitoCorErro Falha na instalacao do SSL, verificar logs. $EfeitoFecha"
echo -e "$EfeitoCorAlerta Para tentar novamente execute o instalador com a opção --ssl ex.: sh instalador-stm-audio-almalinux.sh --ssl $EfeitoFecha"
echo

fi

fi

echo -e "$EfeitoCorAlerta Instalando ShoutCast 2.6.x $EfeitoFecha"
echo

wget -O /home/streaming/cacert.pem http://curl.haxx.se/ca/cacert.pem
rm -f /home/streaming/sc_serv

mv /home/instalador/shoutcast-server-v2.6.1.777 /home/streaming/sc_serv

chmod 777 /home/streaming/sc_serv

echo -e "$EfeitoCorAlerta Instalando IceCast + Liquidsoap $EfeitoFecha"
echo

sudo dnf install php php-mysqlnd netcat yum-utils telnet telnet-server git gcc gcc-c++ automake patch libcurl libsndfile -y

sudo dnf install openssl-devel -y

sudo dnf -y groupinstall "Development Tools"

sudo dnf install --nogpgcheck https://mirrors.rpmfusion.org/free/el/rpmfusion-free-release-9.noarch.rpm -y
sudo dnf install https://mirrors.rpmfusion.org/nonfree/el/rpmfusion-nonfree-release-9.noarch.rpm -y

mkdir /root/liquidsoap-sources
mv /home/instalador/liquidsoap-sources.zip /root/liquidsoap-sources/liquidsoap-sources.zip
cd /root/liquidsoap-sources
unzip liquidsoap-sources.zip
rm -f liquidsoap-sources.zip

sudo dnf install faad2-libs libcurl libcurl-devel taglib libtheora frei0r-plugins pcre-devel libpsl libsamplerate libssh2 libssh2-devel curl faad2 faad2-devel libxslt-devel -y --nogpgcheck

sudo dnf config-manager --set-enabled crb

sudo dnf install epel-next-release -y

sudo dnf install libvorbis-devel taglib-devel -y

sudo dnf install flac flac-libs flac-devel -y

sudo dnf install libmad libmad-devel -y

sudo dnf install libcurl-devel -y

sudo dnf install opus opus-devel -y

sudo dnf install speex-devel -y

sudo dnf install libsamplerate-devel -y

sudo dnf install frei0r-plugins frei0r-devel -y

sudo dnf install libtheora-devel libtheora -y

sudo dnf --enablerepo=rpmfusion-nonfree-updates install fdk-aac-devel fdk-aac -y

sudo dnf install fdk-aac-free-devel fdk-aac-free -y

sudo dnf install libxslt-devel -y

cd /home/instalador
tar -zxvf icecast-2.4.4.tar.gz
cd icecast-2.4.4
./configure && make && make install

mkdir /home/tmp
chmod 777 /home/tmp
export TMPDIR=/home/tmp

cd /root/liquidsoap-sources
sed -i 's/read BINDIR/BINDIR="$DEFAULT_BINDIR"/g' install.sh
sh install.sh
opam init --disable-sandboxing -a --bare
opam switch create 4.14.0

eval $(opam env)


cd /root/liquidsoap-sources
tar -zxvf ffmpeg-4.4.tar.gz
cd ffmpeg-4.4/
./configure --enable-nonfree --enable-openssl --disable-yasm --enable-libmp3lame --enable-libx264 --enable-pic --enable-pic --enable-gpl --enable-shared --enable-decoder=aac --enable-filter=aformat --enable-filter=volume --enable-filter=aresample && make && make install
ldconfig

cd /root/liquidsoap-sources
tar -xvf liquidsoap-2.0.4.tar.bz2
cd liquidsoap-2.0.4/
opam pin add liquidsoap . --no-action -y

export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig"

opam install liquidsoap camomile.1.0.2 ssl.0.5.9 ocurl taglib fdkaac.0.3.2 mad lame vorbis cry faad.0.5.0 flac.0.3.0 opus vorbis theora speex ogg.0.7.2 xmlplaylist duppy ladspa dtools samplerate ffmpeg.1.1.4 ffmpeg-avutil.1.1.4 ffmpeg-avcodec.1.1.4 ffmpeg-avdevice.1.1.4 ffmpeg-av.1.1.4 ffmpeg-avfilter.1.1.4 ffmpeg-swresample.1.1.4 ffmpeg-swscale.1.1.4 frei0r -y --assume-depexts

eval $(opam env)

valida_ls=`liquidsoap --version | grep -c 2.0.4`

if [ "$valida_ls" = "0" ]; then

echo
echo -e "$EfeitoCorErro Falha na instalação do Liquidsoap, tentando novamente... $EfeitoFecha"
echo

opam install liquidsoap camomile.1.0.2 ssl.0.5.9 ocurl.0.9.2 taglib.0.3.9 fdkaac.0.3.2 mad.0.5.2 lame.0.3.6 vorbis.0.8.0 cry.0.6.7 faad.0.5.0 flac.0.3.0 opus.0.2.2 theora.0.4.0 speex.0.4.1 ogg.0.7.2 xmlplaylist.0.1.5 duppy.0.9.2 ladspa.0.2.2 dtools.0.4.4 samplerate.0.1.6 ffmpeg.1.1.4 ffmpeg-avutil.1.1.4 ffmpeg-avcodec.1.1.4 ffmpeg-avdevice.1.1.4 ffmpeg-av.1.1.4 ffmpeg-avfilter.1.1.4 ffmpeg-swresample.1.1.4 ffmpeg-swscale.1.1.4 frei0r.0.1.2 -y --assume-depexts

eval $(opam env)

fi

valida_ls2=`liquidsoap --version | grep -c 2.0.4`

if [ "$valida_ls2" = "1" ]; then

mkdir /home/streaming/liquidsoap
mv -f /usr/local/share/icecast /home/streaming/
cp -v `whereis liquidsoap | awk '{ print $2;}'` /home/streaming/liquidsoap/
cp -v `whereis icecast | awk '{ print $2;}'` /home/streaming/icecast/

rm -rf /root/liquidsoap-sources

cd /home/streaming
rm -f liquidsoap-conf.tar.gz
mv /home/instalador/liquidsoap-conf.tar.gz /home/streaming/liquidsoap-conf.tar.gz
tar -zxf liquidsoap-conf.tar.gz
rm -f liquidsoap-conf.tar.gz
chmod 777 /home/streaming/liquidsoap -Rf

else 

echo
echo -e "$EfeitoCorErro Falha na instalação do Liquidsoap, verificar logs acima e contactar suporte. $EfeitoFecha"
echo
echo
read -n 1 -s -r -p "Pressione qualquer tecla para continuar..."
echo

fi

echo -e "$EfeitoCorAlerta Finalizando ajustes $EfeitoFecha"
echo

cd /etc/letsencrypt/archive
for dominio in `find . -maxdepth 1 -type d | awk -F"./" '{print $2}'`;
do
if [ -d "/etc/letsencrypt/archive/${dominio}" ]; then
cat /etc/letsencrypt/live/${dominio}/fullchain.pem /etc/letsencrypt/live/${dominio}/privkey.pem > /home/streaming/icecast/${dominio}.pem
fi
done

mv /home/instalador/modulo-update-listar-musicas.tar.gz /home/streaming/modulo-update-listar-musicas.tar.gz 
cd /home/streaming
tar -zxvf modulo-update-listar-musicas.tar.gz
rm -f modulo-update-listar-musicas.tar.gz

sed -i '/local_port_range/d' /etc/sysctl.conf
echo 'net.ipv4.ip_local_port_range = 55000 64500' >> /etc/sysctl.conf
sysctl -w net.ipv4.ip_local_port_range="55000 64500"

cat <<EOT > /var/spool/cron/root
*/5 * * * * chmod 777 /home/streaming -Rf
0 */6 * * * /usr/bin/rdate -s rdate.cpanel.net
0 3 * * 0 find /home/streaming/logs -type f -mtime +15 -print -exec rm -rf {} \;
0 3 * * * /usr/local/bin/youtube-dl -U
*/3 * * * * /home/streaming/calcular-uso-ftp
* * * * * /home/streaming/liquidsoap/gerar-hora-certa
*/1 * * * * /home/streaming/cache/gerar-cache-pastas.sh
* * * * * /usr/bin/php /home/streaming/lives/gerar-fundo-lives.php
25 20 * * * /usr/bin/php /home/streaming/atualizar-avozdobrasil.php
30 4 * * * /home/streaming/atualizar-programas.sh $dominio_painel programas $senha_programas;/usr/bin/php /home/streaming/atualizar-avozdobrasil.php
30 4 * * * /home/streaming/atualizar-programetes.sh $dominio_painel programetes $senha_programetes
30 4 * * * certbot -n renew --pre-hook='/home/streaming/icecast/certbot-hook.sh listar' --post-hook='/home/streaming/icecast/certbot-hook.sh reiniciar'
EOT

mv /home/instalador/gerar-cache-pastas.sh /home/streaming/cache/gerar-cache-pastas.sh
mv /home/instalador/certbot-hook.sh /home/streaming/icecast/certbot-hook.sh

sed -i '/acl_groups/d' /etc/php-fpm.d/www.conf
echo 'listen.acl_groups = apache,streaming' >> /etc/php-fpm.d/www.conf

chmod 777 /home/streaming/cache/gerar-cache-pastas.sh
chmod 777 /home/streaming/icecast/certbot-hook.sh

update-crypto-policies --set DEFAULT:SHA1

sed -i '/localhost6/d' /etc/hosts

echo 'net.ipv6.conf.all.disable_ipv6=1' >> /etc/sysctl.conf
echo 'net.ipv6.conf.default.disable_ipv6=1' >> /etc/sysctl.conf
sysctl -p

systemctl enable vnstat
systemctl enable pure-ftpd
systemctl enable httpd
systemctl enable crond
systemctl enable php-fpm

systemctl restart sshd
systemctl restart vnstat
systemctl restart httpd
systemctl restart crond
systemctl restart pure-ftpd
systemctl restart php-fpm


if [ "$confirma_cs" != "${confirma_cs#[Yy]}" ] ;then

echo
echo -n "Instalação Camera Studio"
echo

echo -e "$EfeitoCorOK Iniciando instalacao dos modulos... $EfeitoFecha"
echo

dnf install java-1.8.0* -y

cd /home/instalador

wget -q ${dominio_source_instalador}/WowzaMediaServer-2.2.3.noarch.rpm

rpm -Uvh WowzaMediaServer-2.2.3.noarch.rpm

echo "TTKYD-WY749-Y9PC8-369J9-K8ARB" > /usr/local/WowzaMediaServer/conf/Server.license

echo "admin $senha_root_servidor" > /usr/local/WowzaMediaServer/conf/admin.password

yum install nginx -y

rm -rfv /etc/nginx/conf.d/ssl.conf

if [ x`echo "$1 $2" | grep -c "\-\-skip\-ssl"` = x0 ]; then

systemctl stop httpd

certbot -n --agree-tos --register-unsafely-without-email certonly --standalone -d $dominio_cs

mkdir /usr/local/WowzaMediaServer/ssl

openssl pkcs12 -export -in /etc/letsencrypt/live/$dominio_cs/fullchain.pem -inkey /etc/letsencrypt/live/$dominio_cs/privkey.pem -name $dominio_cs -out /usr/local/WowzaMediaServer/ssl/certificado.p12 -password pass:pGePkkuZ7HeMM922aU97
keytool -importkeystore -noprompt -keypass pGePkkuZ7HeMM922aU97 -srcstorepass pGePkkuZ7HeMM922aU97 -deststorepass pGePkkuZ7HeMM922aU97 -destkeystore /usr/local/WowzaMediaServer/ssl/certificado.jks -srckeystore /usr/local/WowzaMediaServer/ssl/certificado.p12 -srcstoretype PKCS12
keytool -import -noprompt -keypass pGePkkuZ7HeMM922aU97 -storepass pGePkkuZ7HeMM922aU97 -alias bundle -trustcacerts -file /etc/letsencrypt/archive/$dominio_cs/chain1.pem -keystore /usr/local/WowzaMediaServer/ssl/certificado.jks


cat <<EOT >> /etc/nginx/conf.d/ssl.conf

server {
   listen 443 ssl;
   server_name $dominio_cs;
   ssl_certificate /etc/letsencrypt/live/$dominio_cs/fullchain.pem;
   ssl_certificate_key /etc/letsencrypt/live/$dominio_cs/privkey.pem;
   ssl_trusted_certificate /etc/letsencrypt/live/$dominio_cs/chain.pem;
   ssl_session_cache shared:SSL:10m;
   ssl_session_timeout 5m;
   ssl_protocols TLSv1.1 TLSv1.2;
   ssl_prefer_server_ciphers on;
   ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256;
   add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
   location / {

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
        add_header 'Content-Type' 'application/vnd.apple.mpegurl';

        proxy_set_header        X-Real-IP       \$remote_addr;
        proxy_set_header        REMOTE_ADDR     \$remote_addr;
        proxy_set_header        Host            \$host;
        proxy_redirect          off;
        proxy_set_header        X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_connect_timeout 90;
        proxy_send_timeout 90;
        proxy_read_timeout 90;
        client_max_body_size 10m;
        client_body_buffer_size 128k;
        proxy_buffer_size 4k;
        proxy_buffers 4 32k;
        proxy_busy_buffers_size 64k;

        proxy_pass http://127.0.0.1:8080;

   }
}

EOT

fi

mv /home/instalador/src-camera-studio.tar.gz /src-camera-studio.tar.gz

cd /

tar -zxvf src-camera-studio.tar.gz

rm -f src-camera-studio.tar.gz

echo '# Wowza' >> /etc/hosts
echo '127.0.0.1 wowzalicense1.wowzamedia.com' >> /etc/hosts
echo '127.0.0.1 wowzalicense2.wowzamedia.com' >> /etc/hosts
echo '127.0.0.1 wowzalicense3.wowzamedia.com' >> /etc/hosts
echo '127.0.0.1 wowzalicense4.wowzamedia.com' >> /etc/hosts

sed -i 's/555/55/g' /usr/local/WowzaMediaServer/conf/VHost.xml

echo '/etc/init.d/WowzaMediaServer restart' >> /etc/rc.local
systemctl enable nginx

/etc/init.d/WowzaMediaServer restart
systemctl restart nginx
systemctl restart httpd

fi

status_apache=`lynx -head -dump http://localhost:555 | head -n 1 | awk {'print $2'}`

if [ $status_apache -ne 200 ]; then

echo
echo -e "$EfeitoCorErro Falha ao iniciar Apache possivelmente erro com SSL, verificar logs. $EfeitoFecha"
echo -e "$EfeitoCorAlerta Para tentar novamente execute o instalador com a opção --ssl ex.: sh instalador-stm-audio-almalinux.sh --ssl $EfeitoFecha"
echo

fi

echo
echo -e "$EfeitoCorAlerta $vversao $EfeitoFecha"
echo
echo -e "$EfeitoCorAlerta Porta SSH alterada para $porta_ssh $EfeitoFecha"
echo
echo -e "$EfeitoCorOK Instalacao do servidor concluida. $EfeitoFecha"
echo
echo

fi

if [ x`echo "$1 $2" | grep -c "\-\-ssl"` = x1 ]; then

echo -e "$EfeitoCorAlerta Informe o hostname deste servidor para o SSL por ex.: stm1.painel.com $EfeitoFecha"
echo -e "$EfeitoCorAlerta Antes de prosseguir o DNS deve estar apontado para que SSL seja validado ou gerará erros $EfeitoFecha"
read -p 'Dominio Servidor: ' dominio_servidor

porta_ssl="1443"

systemctl stop httpd

> /etc/httpd/conf.d/ssl.conf

cat <<EOT > /etc/httpd/conf.d/ssl.conf
# Configurado
LoadModule ssl_module modules/mod_ssl.so

Listen $porta_ssl

SSLPassPhraseDialog  builtin

SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)
SSLSessionCacheTimeout  300

SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin

SSLCryptoDevice builtin

EOT

sudo dnf -y install certbot-apache

certbot -n --agree-tos --register-unsafely-without-email certonly --standalone -d $dominio_servidor

if [ -f "/etc/letsencrypt/live/$dominio_servidor/cert.pem" ]; then

cat <<EOT >> /etc/httpd/conf.d/ssl.conf

NameVirtualHost *:$porta_ssl

<VirtualHost *:$porta_ssl>
    DocumentRoot /home/streaming/web
    ServerName $dominio_servidor

    ErrorLog logs/ssl_error_log
    TransferLog logs/ssl_access_log
    LogLevel warn

    SSLEngine on
    SSLProtocol all -SSLv2
    SSLCipherSuite DEFAULT:!EXP:!SSLv2:!DES:!IDEA:!SEED:+3DES
    SSLCertificateFile /etc/letsencrypt/live/$dominio_servidor/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/$dominio_servidor/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/$dominio_servidor/chain.pem

    SetEnvIf User-Agent ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

</VirtualHost>

EOT

certbot -n --agree-tos --register-unsafely-without-email certonly --standalone -d $dominio_cs

mkdir /usr/local/WowzaMediaServer/ssl

openssl pkcs12 -export -in /etc/letsencrypt/live/$dominio_cs/fullchain.pem -inkey /etc/letsencrypt/live/$dominio_cs/privkey.pem -name $dominio_cs -out /usr/local/WowzaMediaServer/ssl/certificado.p12 -password pass:pGePkkuZ7HeMM922aU97
keytool -importkeystore -noprompt -keypass pGePkkuZ7HeMM922aU97 -srcstorepass pGePkkuZ7HeMM922aU97 -deststorepass pGePkkuZ7HeMM922aU97 -destkeystore /usr/local/WowzaMediaServer/ssl/certificado.jks -srckeystore /usr/local/WowzaMediaServer/ssl/certificado.p12 -srcstoretype PKCS12
keytool -import -noprompt -keypass pGePkkuZ7HeMM922aU97 -storepass pGePkkuZ7HeMM922aU97 -alias bundle -trustcacerts -file /etc/letsencrypt/archive/$dominio_cs/chain1.pem -keystore /usr/local/WowzaMediaServer/ssl/certificado.jks

cat <<EOT >> /etc/nginx/conf.d/ssl.conf

server {
   listen 443 ssl;
   server_name $dominio_cs;
   ssl_certificate /etc/letsencrypt/live/$dominio_cs/fullchain.pem;
   ssl_certificate_key /etc/letsencrypt/live/$dominio_cs/privkey.pem;
   ssl_trusted_certificate /etc/letsencrypt/live/$dominio_cs/chain.pem;
   ssl_session_cache shared:SSL:10m;
   ssl_session_timeout 5m;
   ssl_protocols TLSv1.1 TLSv1.2;
   ssl_prefer_server_ciphers on;
   ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256;
   add_header Strict-Transport-Security "max-age=31536000; includeSubdomains";
   location / {

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
        add_header 'Content-Type' 'application/vnd.apple.mpegurl';

        proxy_set_header        X-Real-IP       \$remote_addr;
        proxy_set_header        REMOTE_ADDR     \$remote_addr;
        proxy_set_header        Host            \$host;
        proxy_redirect          off;
        proxy_set_header        X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_connect_timeout 90;
        proxy_send_timeout 90;
        proxy_read_timeout 90;
        client_max_body_size 10m;
        client_body_buffer_size 128k;
        proxy_buffer_size 4k;
        proxy_buffers 4 32k;
        proxy_busy_buffers_size 64k;

        proxy_pass http://127.0.0.1:8080;

   }
}

EOT

systemctl start httpd

echo
echo -e "$EfeitoCorOK SSL instalado com sucesso para domínio $dominio_servidor $EfeitoFecha"
echo

else

echo
echo -e "$EfeitoCorErro Falha na instalacao do SSL, verificar logs. $EfeitoFecha"
echo

fi

fi
