#!/bin/sh
##### Instalacao do servidor de Streaming #####
dominio_source_instalador="https://painelvideo.voxtreambrasil.com.br"

# 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-video-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 Video # $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 Instalacao Servidor de Streaming Video 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_painel

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

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

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.: stmv1.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 senha root deste servidor para configurar o admin do wowza $EfeitoFecha"
read -p 'Senha root: ' senha_root_servidor

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

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 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 [ x`echo "$1 $2" | grep -c skip-inter` = x1 ]; 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

sudo dnf remove php* -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
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
echo -e "$EfeitoCorOK Iniciando instalacao Apache + PHP + MySQL $EfeitoFecha"
echo

sudo dnf update -y

unalias cp

unalias mv

mkdir /home/instalador
cd /home/instalador

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

tar -zxvf video-almalinux-sources.tar.gz

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

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

Listen 55

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

dnf install php-gd -y

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.11.29.232714/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

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

dnf install epel-release -y
dnf config-manager --set-enabled crb
dnf install --nogpgcheck https://mirrors.rpmfusion.org/free/el/rpmfusion-free-release-9.noarch.rpm -y
dnf install --nogpgcheck https://mirrors.rpmfusion.org/nonfree/el/rpmfusion-nonfree-release-9.noarch.rpm -y
dnf install ffmpeg ffmpeg-devel -y

ln -s /usr/bin/ffmpeg /usr/local/bin/ffmpeg
ln -s /usr/bin/ffprobe /usr/local/bin/ffprobe

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

echo
echo -e "$EfeitoCorErro Falha na instalacao do FFMPEG! $EfeitoFecha"
echo -e "$EfeitoCorAlerta Tentando novamente.... $EfeitoFecha"
echo

rm -f /usr/local/bin/ffmpeg /usr/local/bin/ffprobe

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

cd /root
wget -q ${dominio_source_instalador}/ffmpeg-4.4.tar.gz
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

fi

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

echo -e "$EfeitoCorOK Instalando Java e Wowza $EfeitoFecha"
echo

yum install java-1.8.0* -y

echo
echo -e "$EfeitoCorOK Efetuando downloads necessarios.... $EfeitoFecha"
echo

mv /home/instalador/instalador-wowza-480.tar.gz /instalador-wowza-480.tar.gz

cd /
tar -zxf instalador-wowza-480.tar.gz
rm -f instalador-wowza-480.tar.gz
ln -s /usr/local/WowzaStreamingEngine-4.8.0 /usr/local/WowzaMediaServer
ln -s /usr/local/WowzaStreamingEngine-4.8.0 /usr/local/WowzaStreamingEngine

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
echo '127.0.0.1 wowzalicense5.wowzamedia.com' >> /etc/hosts
echo '127.0.0.1 wowzamedia.com' >> /etc/hosts
echo '127.0.0.1 wowza.netmasters.nl' >> /etc/hosts
echo '127.0.0.1 www.towza.com' >> /etc/hosts
echo '127.0.0 1 www.towza.tom' >> /etc/hosts

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

cat << 'EOT' > /usr/local/WowzaStreamingEngine/conf/Tune.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Root>
        <Tune>
                <HeapSize>10000M</HeapSize>
                <GarbageCollector>${com.wowza.wms.TuningGarbageCollectorG1Default}</GarbageCollector>
                <VMOptions>
                        <VMOption>-server</VMOption>
                        <VMOption>-Djava.net.preferIPv4Stack=true</VMOption>
                        <VMOption>-Duser.timezone=America/Sao_Paulo</VMOption>
                </VMOptions>
        </Tune>
</Root>
EOT

cp -Rf /usr/local/WowzaStreamingEngine/templates /usr/local/WowzaStreamingEngine/templates-backup
cd /usr/local/WowzaStreamingEngine/templates
mv /home/instalador/templates-target.zip /usr/local/WowzaStreamingEngine/templates
unzip -o templates-target.zip
rm -f templates-target.zip

mv /home/instalador/Server-targets.xml /usr/local/WowzaStreamingEngine/conf/Server.xml
mv /home/instalador/wse-plugin-httplivestreamrecord.jar /usr/local/WowzaStreamingEngine/lib/wse-plugin-httplivestreamrecord.jar
mv /home/instalador/wms-plugin-httpserverstatsxml-LIVREEE.jar /usr/local/WowzaStreamingEngine/lib/wms-plugin-httpserverstatsxml.jar

mv /home/instalador/src-video-centos-6-7-8.tar.gz /src-video-centos-6-7-8.tar.gz

cd /

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

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


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_painel
MYSQLPassword   $senha_painel
MYSQLDatabase   $banco_painel

MYSQLCrypt      cleartext

MYSQLGetPW      SELECT senha FROM streamings WHERE (login="\L" AND status="1") AND aplicacao IN ('tvstation', 'vod')
MYSQLGetDir     SELECT ftp_dir FROM streamings WHERE (login="\L" AND status="1") AND aplicacao IN ('tvstation', 'vod')
MySQLGetQTASZ   SELECT espaco FROM streamings WHERE (login="\L" AND status="1") AND aplicacao IN ('tvstation', 'vod')

EOT

cat << 'EOT' >> /home/streaming/web/watermark.php
<?php
if(isset($_GET["login"])){
    
    if (file_exists("/home/streaming/".$_GET["login"]."/logo-watermark.png")){
        header('content-type: image/png');
        echo file_get_contents("/home/streaming/".$_GET["login"]."/logo-watermark.png");
    } else {
    
    $width = 200;
    $height = 30;
    $text = "Sem logo / No image";
    $fontsize = 5;

    $img = imagecreate($width, $height);

    // Transparent background
    $black = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $black);

    // Red text
    $red = imagecolorallocate($img, 255, 0, 0);
    imagestring($img, $fontsize, 0, 0, $text, $red);

    header('Content-type: image/png');
    imagepng($img);
    imagedestroy($img);
    
    }
}
?>
EOT

wget -q ${dominio_source_instalador}/Application-webrtc.xml -O /usr/local/WowzaStreamingEngine/templates/Application-webrtc.xml
wget -q ${dominio_source_instalador}/VHost-webrtc.xml -O /usr/local/WowzaStreamingEngine/conf/VHost.xml

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 -y install certbot-apache

ln -s /usr/bin/certbot-3 /usr/bin/certbot

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

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

systemctl stop httpd

> /etc/httpd/conf.d/ssl.conf
vversao=`cat /home/instalador/versao.txt`

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

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

rm -Rf /usr/local/WowzaMediaServer/ssl

mkdir /usr/local/WowzaMediaServer/ssl

openssl pkcs12 -export -in /etc/letsencrypt/live/$dominio_servidor/fullchain.pem -inkey /etc/letsencrypt/live/$dominio_servidor/privkey.pem -name $dominio_servidor -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_servidor/chain1.pem -keystore /usr/local/WowzaMediaServer/ssl/certificado.jks

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-video-almalinux.sh --ssl $EfeitoFecha"
echo

fi

fi

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


> /usr/local/WowzaStreamingEngine/renovar-ssl.sh

cat << 'EOF' > /usr/local/WowzaStreamingEngine/renovar-ssl.sh
#!/bin/sh

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

if [ -f /usr/bin/systemctl ]; then
    systemctl stop WowzaStreamingEngine
else 
    /etc/init.d/WowzaStreamingEngine stop
fi

fi

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

rm -rf /usr/local/WowzaMediaServer/ssl/*

dominio_servidor=`grep archive_dir /etc/letsencrypt/renewal/*.conf | head -1 | cut -d / -f 5`

openssl pkcs12 -export -in /etc/letsencrypt/live/$dominio_servidor/fullchain.pem -inkey /etc/letsencrypt/live/$dominio_servidor/privkey.pem -name $dominio_servidor -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/live/$dominio_servidor/chain.pem -keystore /usr/local/WowzaMediaServer/ssl/certificado.jks

if [ -f /usr/bin/systemctl ]; then
    systemctl start WowzaStreamingEngine
    systemctl restart httpd
else 
    /etc/init.d/WowzaStreamingEngine start
    /etc/init.d/httpd restart
fi

fi
EOF

chmod 777 /usr/local/WowzaStreamingEngine/renovar-ssl.sh


cat <<EOT > /var/spool/cron/root
0 */1 * * * /usr/local/WowzaMediaServer/limpar_mem_cache
*/5 * * * * /home/streaming/calcular-uso-ftp
0 3 * * * /usr/local/bin/youtube-dl -U
0 */12 * * * /usr/bin/rdate -s rdate.cpanel.net
30 4 * * * /home/streaming/remover-videos-inexistentes
*/30 * * * * /bin/chown streaming.streaming /home/streaming/*
*/30 * * * * /bin/echo -n > /var/spool/mail/root
*/30 * * * * /bin/echo -n > /var/spool/mail/streaming
0 */2 * * * /bin/echo -n > /usr/local/WowzaStreamingEngine/logs/wowzastreamingengine_error.log
0 */2 * * * /bin/echo -n > /usr/local/WowzaStreamingEngine/logs/wowzastreamingengine_access.log
0 */12 * * * rm -f /usr/local/WowzaStreamingEngine/logs/wowzastreamingengine_*.log.*
30 4 * * * certbot -n renew --standalone --pre-hook='/usr/local/WowzaStreamingEngine/renovar-ssl.sh desligar' --post-hook='/usr/local/WowzaStreamingEngine/renovar-ssl.sh converter'
EOT

mv /home/instalador/migrar-videos-ftp.txt /home/streaming/web/migrar-videos-ftp.php
mv /home/instalador/youtube.php.txt /home/streaming/web/youtube.php

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 -Rf

update-crypto-policies --set DEFAULT:SHA1

sudo dnf install lynx -y

systemctl enable WowzaStreamingEngine
systemctl disable WowzaStreamingEngineManager
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 start WowzaStreamingEngine
systemctl restart php-fpm

status_apache=`lynx -head -dump https://$dominio_servidor:$porta_ssl | 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-video-almalinux.sh --ssl $EfeitoFecha"
echo

fi

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

echo
echo -e "$EfeitoCorErro Falha na instalacao do FFMPEG, verificar logs. $EfeitoFecha"
echo -e "$EfeitoCorAlerta Para tentar novamente execute o instalador com a opção --ffmpeg ex.: sh instalador-stm-video-almalinux.sh --ffmpeg $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.: stmv1.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

systemctl stop httpd

> /etc/httpd/conf.d/ssl.conf
vversao=`wget -q -O - http://${dominio_source_instalador}/instalador/versao.txt`

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

Listen 1443

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 *:1443

<VirtualHost *:1443>
    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

echo -e "$EfeitoCorOK Instalando SSL Wowza $EfeitoFecha"
echo
echo -e "$EfeitoCorAlerta Use a senha quando for solicitado: $EfeitoFecha $EfeitoCorErro pGePkkuZ7HeMM922aU97 $EfeitoFecha"
echo

mkdir /usr/local/WowzaMediaServer/ssl

openssl pkcs12 -export -in /etc/letsencrypt/live/$dominio_servidor/fullchain.pem -inkey /etc/letsencrypt/live/$dominio_servidor/privkey.pem -name $dominio_servidor -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_servidor/chain1.pem -keystore /usr/local/WowzaMediaServer/ssl/certificado.jks

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 -e "$EfeitoCorAlerta Para tentar novamente execute o instalador com a opção --ssl ex.: sh instalador-stm-video-almalinux.sh --ssl $EfeitoFecha"
echo

fi

fi