#!/usr/bin/env bash

# Обновление системы
dnf -y update

# Установка nginx
dnf -y install tar unzip mc git gcc gcc-c++ kernel-devel pcre-devel zlib-devel openssl-devel perl perl-devel perl-ExtUtils-Embed libxslt libxslt-devel libxml2 libxml2-devel gd gd-devel policycoreutils-python-utils
cd /tmp
git clone http://github.com/wandenberg/nginx-push-stream-module.git
NGINX_PUSH_STREAM_MODULE_PATH=$PWD/nginx-push-stream-module
curl -O https://nginx.org/download/nginx-1.17.7.tar.gz
tar xzvf nginx-1.17.7.tar.gz
cd nginx-1.17.7
./configure --prefix=/etc/nginx \
      --sbin-path=/usr/sbin/nginx \
      --modules-path=/usr/lib64/nginx/modules \
      --conf-path=/etc/nginx/nginx.conf \
      --error-log-path=/var/log/nginx/error.log \
      --pid-path=/var/run/nginx.pid \
      --lock-path=/var/run/nginx.lock \
      --user=nginx \
      --group=nginx \
      --build=CentOS \
      --with-select_module \
      --with-poll_module \
      --with-threads \
      --with-file-aio \
      --with-http_ssl_module \
      --with-http_v2_module \
      --with-http_realip_module \
      --with-http_addition_module \
      --with-http_xslt_module=dynamic \
      --with-http_image_filter_module=dynamic \
      --with-http_sub_module \
      --with-http_dav_module \
      --with-http_flv_module \
      --with-http_mp4_module \
      --with-http_gunzip_module \
      --with-http_gzip_static_module \
      --with-http_auth_request_module \
      --with-http_random_index_module \
      --with-http_secure_link_module \
      --with-http_degradation_module \
      --with-http_slice_module \
      --with-http_stub_status_module \
      --http-log-path=/var/log/nginx/access.log \
      --http-client-body-temp-path=/var/cache/nginx/client_temp \
      --http-proxy-temp-path=/var/cache/nginx/proxy_temp \
      --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
      --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
      --http-scgi-temp-path=/var/cache/nginx/scgi_temp \
      --with-mail=dynamic \
      --with-mail_ssl_module \
      --with-stream=dynamic \
      --with-stream_ssl_module \
      --with-stream_realip_module \
      --with-stream_ssl_preread_module \
      --with-compat \
      --with-pcre-jit \
      --with-openssl-opt=no-nextprotoneg \
      --with-debug \
      --add-module=../nginx-push-stream-module
make
make install
useradd -M -s /sbin/nologin apache
chown apache:apache /var/log/nginx

echo "
user apache;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    sendfile            off; # bug in VirtualBox
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    client_max_body_size 1024m;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    push_stream_shared_memory_size          64M;

    server {
        listen 80 default_server;
        server_name  _;
        root /var/www/html/web;
        index index.html index.htm index.php;

        location / {
            try_files \$uri \$uri/ @urlrewrite;
        }

        location /messages/pub {
            push_stream_publisher admin;
            push_stream_channels_path \$arg_id;

            allow 127.0.0.1;
        }

        location ~ /messages/sub/(.*) {
            push_stream_subscriber long-polling;
            push_stream_channels_path \$1;
            push_stream_longpolling_connection_ttl 300s;
            push_stream_last_received_message_time \$arg_time;
            push_stream_last_received_message_tag \$arg_tag;
        }

        location ~ \.php\$ {
            try_files \$uri @urlrewrite;
            include /etc/nginx/fastcgi_params;
            fastcgi_pass  unix:/var/run/php-fpm/php-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
            fastcgi_read_timeout 3600;
        }

        location @urlrewrite {
            include /etc/nginx/fastcgi_params;
            fastcgi_pass  unix:/var/run/php-fpm/php-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME \$document_root/index.php;
            fastcgi_read_timeout 3600;
        }
    }
}
" > /etc/nginx/nginx.conf

echo "
[Unit]
Description=nginx with push-stream-module
Documentation=https://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s TERM \$MAINPID

[Install]
WantedBy=multi-user.target
" > /usr/lib/systemd/system/nginx.service

mkdir /var/cache/nginx
chown apache:apache /var/cache/nginx

systemctl start nginx
systemctl enable nginx

# Установка MySQL
dnf -y install mariadb-server mariadb

echo "
[mysqld]
key_buffer_size = 16M
innodb_buffer_pool_size = 2G
innodb_flush_method = O_DIRECT
innodb_flush_log_at_trx_commit = 2
table_open_cache = 16384
thread_cache_size = 16
sort_buffer_size = 24M
tmp_table_size = 16M
max_heap_table_size = 32M
innodb_log_file_size = 256M
max_allowed_packet = 128M
innodb_file_per_table = 1
join_buffer_size = 8M
innodb_buffer_pool_instances = 2
read_rnd_buffer_size = 16M

max_connections = 500
interactive_timeout = 300
wait_timeout = 300
innodb_log_buffer_size = 8M
skip_name_resolve = 1
query_cache_type = 0
query_cache_size = 0
slow_query_log          = /var/log/mysql-slow.log
long_query_time         = 1
" > /etc/my.cnf.d/tune.cnf

systemctl start mariadb
systemctl enable mariadb

# Установка PHP-FPM
dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
dnf -y install https://rpms.remirepo.net/enterprise/remi-release-8.rpm
dnf -y module install php:remi-7.4
dnf -y install php php-fpm php-common php-gd php-mbstring php-xml php-mysql php-opcache php-cli php-intl php-ldap php-sodium php-pecl-imagick php-soap php-zip php-memcached

rm -rf /etc/localtime
ln -s /usr/share/zoneinfo/Europe/Moscow /etc/localtime
sed -i "s/;date.timezone.*/date.timezone = Europe\\/Moscow/g" /etc/php.ini
sed -i "s/; max_input_vars.*/max_input_vars = 100000/g" /etc/php.ini
sed -i "s/short_open_tag*/short_open_tag = On/g" /etc/php.ini
sed -i "s/error_reporting.*/error_reporting \= E_ALL \& ~E_DEPRECATED \& ~E_STRICT \& ~E_NOTICE \& ~E_WARNING/g" /etc/php.ini
sed -i "s/;realpath_cache_size = .*/realpath_cache_size = 4096k/g" /etc/php.ini
sed -i "s/upload_max_filesize = .*/upload_max_filesize = 512M/g" /etc/php.ini
sed -i "s/memory_limit = .*/memory_limit = 1024M/g" /etc/php.ini
sed -i "s/post_max_size = .*/post_max_size = 512M/g" /etc/php.ini
sed -i "s/session.gc_maxlifetime = .*/session.gc_maxlifetime = 2678400/g" /etc/php.ini
sed -i "s/session.cookie_lifetime = .*/session.cookie_lifetime = 2678400/g" /etc/php.ini
sed -i "s/;date.timezone.*/date.timezone = Europe\\/Moscow/g" /etc/php.ini
sed -i "s/;\s*max_input_vars.*/max_input_vars = 100000/g" /etc/php.ini
sed -i "s/short_open_tag = .*/short_open_tag = On/g" /etc/php.ini
sed -i "s/display_errors = .*/display_errors = On/g" /etc/php.ini
sed -i "s/;realpath_cache_size = .*/realpath_cache_size = 4096k/g" /etc/php.ini
sed -i "s/opcache.max_accelerated_files=.*/opcache.max_accelerated_files=100000/g" /etc/php.d/10-opcache.ini
sed -i "s/opcache.max_accelerated_files=.*/opcache.max_accelerated_files=100000/g" /etc/php.d/10-opcache.ini
sed -i "s/listen = \\/run\\/php-fpm\\/www.sock/listen = \\/var\\/run\\/php-fpm\\/php-fpm.sock/g" /etc/php-fpm.d/www.conf
sed -i "s/;listen.owner = nobody/listen.owner = apache/g" /etc/php-fpm.d/www.conf
sed -i "s/;listen.group = nobody/listen.group = apache/g" /etc/php-fpm.d/www.conf

systemctl start php-fpm
systemctl enable php-fpm

# Установка Composer
cd /tmp
curl -sS https://getcomposer.org/installer | php
mv /tmp/composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer
mkdir -p /root/.config/composer
sh -c 'echo \"{"github-oauth": {"github.com": "5a07804b8b4b3a25750cd446f42451d6701e8fc8"}}\" > /root/.config/composer/auth.json'
/usr/local/bin/composer global require "fxp/composer-asset-plugin:^1.2.0"

# Memcached
sudo dnf -y install memcached
sudo systemctl enable memcached
sudo systemctl start memcached

# Libreoffice
sudo dnf -y install libreoffice ghostscript

# Настройка SELinux
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html(/.*)?"
restorecon -R /var/www/html
chown -R apache:apache /var/lib/php/session

semanage permissive -a httpd_t
setsebool -P httpd_can_network_connect on

firewall-cmd --permanent --add-service=http
firewall-cmd --reload

# crontab
echo "* * * * * sudo -u nginx php /var/www/html/yii agent" > /tmp/crontab.av
crontab /tmp/crontab.av
unlink /tmp/crontab.av

mkdir /var/www/html/web
curl https://avtor-vuz.ru/private/scripts/install-v2.php > /var/www/html/web/install-v2.php
echo "<?php
header('Location: /install-v2.php');
" > /var/www/html/web/index.php
chown -R apache:apache /var/www/html
chmod -R 0775 /var/www/html