#!/bin/bash
#
# 10 septembre 2019

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Nginx est un serveur HTTP et reverse proxy utilisé par de nombreux sites. 
# OpenResty est une surcouche construite avec de nombreux modules par défaut, ils permettent par exemple 
# la personnalisation via des scripts Lua ou des accès simplifiés à des bases de données.
# http://openresty.org/en/
# https://getawesomeness.herokuapp.com/get/openresty
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# Vérifier si utilisateur "root"
if [ $(id -u) != "0" ]; then
    echo "Erreur : Vous devez être root pour exécuter ce script"
    exit 1
fi

#logiciels pour compilation 
apt update
apt install dpkg-dev build-essential zlib1g-dev libpcre3 libpcre3-dev libcurl4-openssl-dev libossp-uuid-dev libssl-dev libxslt-dev libgd-dev libgeoip-dev libperl-dev libpam0g-dev libbz2-dev tar unzip curl git -y
# 
# openresty voir https://openresty.org/en/download.html pour la dernière version
wget https://openresty.org/download/openresty-1.15.8.1.tar.gz
tar -xvf openresty-1.15.8.1.tar.gz
cd openresty-1.15.8.1

# les modules 
mkdir -p modules
cd modules
#### Clonage des modules externes avant compilation ####

# headers-more-nginx-module
git clone https://github.com/openresty/headers-more-nginx-module
# ngx_http_auth_pam_module
git clone https://github.com/stogh/ngx_http_auth_pam_module nginx-auth-pam
#ngx_cache_purge
git clone https://github.com/FRiCKLE/ngx_cache_purge.git nginx-cache-purge
#
git clone https://github.com/aviafelix/nginx-dav-ext-module
#echo-nginx-module
git clone https://github.com/openresty/echo-nginx-module nginx-echo
#ngx-fancyindex
git clone https://github.com/aperezdc/ngx-fancyindex
# modification fancyindex pour avoir la ligne complète
#nchan ex nginx-push-stream-module
git clone https://github.com/slact/nchan
#nginx-upload-progress-module
git clone https://github.com/masterzen/nginx-upload-progress-module nginx-upload-progress
#ngx_http_substitutions_filter_module
git clone https://github.com/yaoweibin/ngx_http_substitutions_filter_module
#Nginx Upstream Fair Proxy Load Balancer
git clone https://github.com/itoffshore/nginx-upstream-fair

# configurer
cd ..
./configure \
 --with-debug \
 --with-pcre-jit \
 --with-http_ssl_module \
 --with-http_stub_status_module \
 --with-http_realip_module \
 --with-http_auth_request_module \
 --with-http_v2_module \
 --with-http_dav_module \
 --with-http_slice_module \
 --with-threads \
 --with-http_addition_module \
 --with-http_flv_module \
 --with-http_geoip_module=dynamic \
 --with-http_gunzip_module \
 --with-http_gzip_static_module \
 --with-http_image_filter_module=dynamic \
 --with-http_mp4_module \
 --with-http_perl_module=dynamic \
 --with-http_random_index_module \
 --with-http_secure_link_module \
 --with-http_sub_module \
 --with-http_xslt_module=dynamic \
 --with-mail=dynamic \
 --with-mail_ssl_module \
 --with-stream=dynamic \
 --with-stream_ssl_module \
 --add-dynamic-module=modules/nginx-auth-pam \
 --add-dynamic-module=modules/nginx-cache-purge \
 --add-dynamic-module=modules/nginx-dav-ext-module \
 --add-dynamic-module=modules/ngx-fancyindex \
 --add-dynamic-module=modules/nchan \
 --add-dynamic-module=modules/nginx-upload-progress \
 --add-dynamic-module=modules/nginx-upstream-fair \
 --add-dynamic-module=modules/ngx_http_substitutions_filter_module 

## Modules ci-dessous sont intégrés à openresty ##
# --add-dynamic-module=modules/headers-more-nginx-module \
# --add-dynamic-module=modules/nginx-echo \

# compilation installation
make && make install

# Configuration nginx pour le chargement des modules
mkdir -p /usr/local/openresty/nginx/modules-enabled
for file in $(find "/usr/local/openresty/nginx/modules/" -type f -name "*.so")
  do 
   tempfile="${file##*/}"
   prefix="50-mod"
	if [ $tempfile = "ndk_http_module.so" ]
	 then
	  prefix="10-mod"
	fi
   echo 'load_module "/usr/local/openresty/nginx/modules/'$tempfile'";' | tee  /usr/local/openresty/nginx/modules-enabled/$prefix-$tempfile-upload.conf

  done

# Création des liens pour le dossier /usr/local/openresty/bin/
for file in /usr/local/openresty/bin/*
  do 
   tempfile="${file##*/}"
   rest=${tempfile%.*}
        #convert $tempfile $rest".png"
	ln -s $file /usr/local/bin/$tempfile
   done



# Création systemd openresty.service
cat > /etc/systemd/system/openresty.service << EOF
# Stop dance for OpenResty
# A modification of the Nginx systemd script
# =======================
#
# ExecStop sends SIGSTOP (graceful stop) to the Nginx process.
# If, after 5s (--retry QUIT/5) OpenResty is still running, systemd takes control
# and sends SIGTERM (fast shutdown) to the main process.
# After another 5s (TimeoutStopSec=5), and if OpenResty is alive, systemd sends
# SIGKILL to all the remaining processes in the process group (KillMode=mixed).
#
# Nginx signals reference doc:
# http://nginx.org/en/docs/control.html
#
[Unit]
Description=A dynamic web platform based on Nginx and LuaJIT.
After=network.target

[Service]
Type=forking
PIDFile=/run/openresty.pid
ExecStartPre=/usr/local/openresty/bin/openresty -t -q -g 'daemon on; master_process on;'
ExecStart=/usr/local/openresty/bin/openresty -g 'daemon on; master_process on;'
ExecReload=/usr/local/openresty/bin/openresty -g 'daemon on; master_process on;' -s reload
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/openresty.pid
TimeoutStopSec=5
KillMode=mixed

[Install]
WantedBy=multi-user.target
EOF

# le fichier de configuration /usr/local/openresty/nginx/conf/nginx.conf
rm /usr/local/openresty/nginx/conf/nginx.conf
cat > /usr/local/openresty/nginx/conf/nginx.conf << EOF
user www-data;
worker_processes  auto;
pid /run/openresty.pid;

include ../modules-enabled/*.conf;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    variables_hash_max_size 2048;
    
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;

    keepalive_timeout  65;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    access_log /var/log/openresty/access.log;
    error_log /var/log/openresty/error.log;

    gzip  on;
    gzip_disable "msie6";

    include ../sites/*.conf;
}
EOF

mkdir -p /var/log/openresty
systemctl daemon-reload
systemctl start openresty
systemctl enable openresty

# Ensuite, créez le nouveau répertoire de sites que nous avons spécifié dans la ligne d’ include , il contient les fichiers de configuration conf des sites virtuels VHOST
mkdir -p /usr/local/openresty/nginx/sites
# Création du dossier  contenant les fichiers html, php, etc...
mkdir -p /usr/local/openresty/nginx/www/

# PHP7.3
apt-get -y install apt-transport-https lsb-release ca-certificates
wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
apt update
# Le paquet php7.3-mcrypt est inexistant (si besoin ,installer php7.1-mcrypt)
apt install php7.3 php7.3-fpm php7.3-mysql php7.3-curl php7.3-json php7.3-gd php7.3-tidy php7.3-intl php7.3-imagick php7.3-xml php7.3-mbstring php7.3-zip -y

# Contenu fichier /usr/local/openresty/nginx/sites/default.conf
# back slash pour prise en compte request_filename
cat > /usr/local/openresty/nginx/sites/default.conf << EOF
server {
    listen 80;
    listen [::]:80;
    root /usr/local/openresty/nginx/www/ ;
        location ~ \.php$ {
           fastcgi_split_path_info ^(.+\.php)(/.+)$;
           fastcgi_pass unix:/run/php/php7.3-fpm.sock;   # PHP7.3
           fastcgi_index index.php;
           include fastcgi_params;
           fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
}
EOF

# DÉPLACEMENT fichier index.html
mv /usr/local/openresty/nginx/html/index.html /usr/local/openresty/nginx/www/

# test php
echo "<?php phpinfo(); ?>" > /usr/local/openresty/nginx/www/info.php

# Réinitialiser
systemctl daemon-reload
# Relancer les services
systemctl restart openresty php7.3-fpm 

# Installer MariaDb
apt install mariadb-server -y
# Générer un mot de passe pour mysql
echo $(head -c 12 /dev/urandom | openssl enc -base64) > /etc/mysql/mdp
# fichier sql
cat > /tmp/mysql_secure.sql << EOF
GRANT ALL ON *.* TO 'admin'@'localhost' IDENTIFIED BY '$(cat /etc/mysql/mdp)' WITH GRANT OPTION;
FLUSH PRIVILEGES; /* Applique les changements effectués précédemment concernant la gestion des droits */
EOF

# Exécuter la requête sql
mysql -uroot < /tmp/mysql_secure.sql

clear
echo "**************************************"
echo "Versions Nginx OpenSSL MariaDB et PHP"
echo "**************************************"
openresty -v
openssl version
mysql --version
echo "Mot de passe MySql/MariaDB : /etc/mysql/mdp"
php -v

echo "********** FIN EXECUTION SCRIPT ************"


