#   https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-as-a-web-server-and-reverse-proxy-for-apache-on-one-ubuntu-18-04-server
###============================================================
##      Ubuntu 18.04 Apache NGINX Reverse Proxy Installer
###============================================================
## Zet comments hieronder:
#
#
#
##=============================================================

##----------##
#    Menu    #
##----------##

echo "Domein instellen als NGINX reverse proxy of als NGINX webserver?"
PS3='Keuze:'
options=("Reverse proxy" "Webserver")
select opt in "${options[@]}"
do
    case $opt in
        "Reverse proxy")
            domain_setup=1
            break;;
        "Webserver")
            domain_setup=2
            break;;
        *) echo "Fout commando $REPLY";;
    esac
done

##----------------##
#    Pre-Config    #
##----------------##

# Set server IP variable for apache access
server_ip=$(hostname -I|cut -f1 -d ' ')
# Block direct apache acces
ufw deny 8080/tcp
# Setup domain folder
mkdir -p /var/www/"$domain"/html
chmod -R 755 /var/www

##============##
#    Apache    #
##============##

apt install -y apache2 php-fpm
wget https://mirrors.edge.kernel.org/ubuntu/pool/multiverse/liba/libapache-mod-fastcgi/libapache2-mod-fastcgi_2.4.7~0910052141-1.2_amd64.deb
dpkg -i libapache2-mod-fastcgi_2.4.7~0910052141-1.2_amd64.deb
mv /etc/apache2/ports.conf /etc/apache2/ports.conf.default
echo "Listen 8080" | sudo tee /etc/apache2/ports.conf
a2dissite 000-default

##-----------------##
#    Mod_FastCGI    #
##-----------------##

#a2dismod php7.2
a2enmod actions
mv /etc/apache2/mods-enabled/fastcgi.conf /etc/apache2/mods-enabled/fastcgi.conf.default
cat <<EOF > /etc/apache2/mods-enabled/fastcgi.conf
<IfModule mod_fastcgi.c>
    AddHandler fastcgi-script .fcgi
    FastCgiIpcDir /var/lib/apache2/fastcgi
    AddType application/x-httpd-fastphp .php
    Action application/x-httpd-fastphp /php-fcgi
    Alias /php-fcgi /usr/lib/cgi-bin/php-fcgi
    FastCgiExternalServer /usr/lib/cgi-bin/php-fcgi -socket /run/php/php7.2-fpm.sock -pass-header Authorization
    <Directory /usr/lib/cgi-bin>
        Require all granted
    </Directory>
</IfModule>
EOF

##--------------##
#    Mod_RPAF    #
##--------------##

apt install -y unzip build-essential apache2-dev
wget https://github.com/gnif/mod_rpaf/archive/stable.zip
unzip stable.zip
cd mod_rpaf-stable
make
make install
cat <<EOF > /etc/apache2/mods-available/rpaf.load
LoadModule rpaf_module /usr/lib/apache2/modules/mod_rpaf.so
EOF
cat <<EOF > /etc/apache2/mods-available/rpaf.conf
    <IfModule mod_rpaf.c>
        RPAF_Enable             On
        RPAF_Header             X-Real-Ip
        RPAF_ProxyIPs           $server_ip
        RPAF_SetHostName        On
        RPAF_SetHTTPS           On
        RPAF_SetPort            On
    </IfModule>
EOF
a2enmod rpaf

##-------------------##
#    Reverse Proxy    # 
##-------------------##

if [ $domain_setup = 1 ]; then
cat <<EOF > /etc/apache2/sites-available/"$domain.conf"
<VirtualHost *:8080>
    ServerName $domain
    ServerAlias www.$domain
    DocumentRoot /var/www/$domain/html
    <Directory /var/www/$domain/html>
        AllowOverride All
    </Directory>
</VirtualHost>
EOF
a2ensite $domain
fi

systemctl restart apache2

##===========##
#    NGINX    #
##===========##

apt install -y nginx
rm /etc/nginx/sites-enabled/default

##-------------------##
#    Reverse Proxy    # 
##-------------------##

if [ $domain_setup = 1 ]; then
cat <<EOF > /etc/nginx/sites-available/"$domain"
upstream netdata {
    server 127.0.0.1:19999;
    keepalive 64;
}

server {
    listen 80;

    root /var/www/$domain/html;
    index index.php index.html index.htm;

    server_name $domain www.$domain;

    #netdata here

    location / {
        proxy_pass http://$server_ip:8080;
        proxy_set_header X-Real-IP  \$remote_addr;
        proxy_set_header X-Forwarded-For \$remote_addr;
        proxy_set_header Host \$host;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
        
    location ~ \.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)(\\n|\?ver=[0-9.])\$ {
        return 200;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF
fi

##---------------##
#    Webserver    #
##---------------##

if [ $domain_setup = 2 ]; then
cat <<EOF > /etc/nginx/sites-available/"$domain"
upstream netdata {
    server 127.0.0.1:19999;
    keepalive 64;
}

server {
    listen 80;

    root /var/www/$domain/html;
    index index.php index.html index.htm;

    server_name $domain www.$domain;
    
    #netdata here
    
    location / {
        try_files \$uri \$uri/ /index.php;
    }

    location ~ \.php\$ {
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        include snippets/fastcgi-php.conf;
    }
}
EOF
fi

ln -s /etc/nginx/sites-available/"$domain" /etc/nginx/sites-enabled/"$domain"

##===========##
#    Other    #
##===========##

##-----------##
#    MYSQL    #
##-----------##

apt install -y mysql-server-5.7
# mysql_secure_installation automated
mysqladmin -u root password "$password"
mysql -u root -p"$password" -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1')"
mysql -u root -p"$password" -e "DELETE FROM mysql.user WHERE User=''"
mysql -u root -p"$password" -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%'"
mysql -u root -p"$password" -e "SELECT user,authentication_string,plugin,host FROM mysql.user;"
mysql -u root -p"$password" -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '"$password"';"
mysql -u root -p"$password" -e "FLUSH PRIVILEGES;"
mysql -u root -p"$password" -e "SELECT user,authentication_string,plugin,host FROM mysql.user;"

##-------------##
#    Certbot    #
##-------------##

apt install -y python-certbot-nginx
certbot --nginx -n -d "$domain" -d "www.$domain" -m "$email" --hsts --redirect --no-eff-email --agree-tos
sed -i 's/ssl ipv6only/ssl http2 ipv6only/g' /etc/nginx/sites-available/"$domain"
sed -i 's/listen 443 ssl/listen 443 ssl http2/g' /etc/nginx/sites-available/"$domain"
sed -i 's#include /etc/letsencrypt/options-ssl-nginx.conf;#ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;#g' /etc/nginx/sites-available/"$domain"

##---------##
#    PHP    #
##---------##

apt install -y php-mysql php-cgi php-common php-pear php-mbstring php-curl php-gd php-intl php-soap php-xml php-xmlrpc php-zip

sed -i 's/;opcache.memory_consumption=128/opcache.memory_consumption=256/g' /etc/php/7.2/fpm/php.ini
sed -i 's/;opcache.enable=1/opcache.enable=0/g' /etc/php/7.2/fpm/php.ini
sed -i 's/;opcache.interned_strings_buffer=8/opcache.interned_strings_buffer=8/g' /etc/php/7.2/fpm/php.ini
sed -i 's/;opcache.max_accelerated_files=10000/opcache.max_accelerated_files=50000/g' /etc/php/7.2/fpm/php.ini
sed -i 's/;opcache.max_wasted_percentage=5/opcache.max_wasted_percentage=5/g' /etc/php/7.2/fpm/php.ini
sed -i 's/;opcache.revalidate_freq=2/opcache.revalidate_freq=0/g' /etc/php/7.2/fpm/php.ini
sed -i 's/; max_input_vars = 1000/max_input_vars = 10000/g' /etc/php/7.2/fpm/php.ini
sed -i 's/upload_max_filesize = 2/upload_max_filesize = 128/g' /etc/php/7.2/fpm/php.ini
sed -i 's/post_max_size = 8/post_max_size = 64/g' /etc/php/7.2/fpm/php.ini

##----------------##
#    PHPMyAdmin    #
##----------------##

debconf-set-selections <<< "phpmyadmin phpmyadmin/dbconfig-install boolean true"
debconf-set-selections <<< "phpmyadmin phpmyadmin/app-password-confirm password $password"
debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/admin-pass password $password"
debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/app-pass password $passsword"
debconf-set-selections <<< "phpmyadmin phpmyadmin/reconfigure-webserver multiselect"
apt install -y phpmyadmin
# Redirect phpmyadmin -> database
ln -s /usr/share/phpmyadmin /var/www/"$domain"/html/database

##-------------##
#    Postfix    #
##-------------##

debconf-set-selections <<< "postfix postfix/mailname string $domain"
debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
apt install -y mailutils
sed -i 's/#inet_interfaces = all/inet_interfaces = loopback-only/g' /etc/postfix/main.cf
sed -i 's/mydestination/#mydestination/g' /etc/postfix/main.cf
sed -i 's/relayhost =/mydestination = '$domain', localhost.'$domain', '$domain'/g' /etc/postfix/main.cf
cat <<EOF > /etc/aliases
# See man 5 aliases for format
postmaster:    root
root:          $email
EOF
newaliases

##-------------##
#    Netdata    #
##-------------##

if [ $netdata = 1 ]; then
    apt install -y netdata
    sed -i 's/SEND_EMAIL="YES"/SEND_EMAIL="NO"/g' /etc/netdata/health_alarm_notify.conf
    ufw allow 19999/tcp
    sed -i 's+#netdata here+location = /netdata {\n        return 301 /netdata/;\n    }\n\n    location ~ /netdata/(?<ndpath>.*) {\n        proxy_redirect off;\n        proxy_set_header Host \$host;\n        proxy_set_header X-Forwarded-Host \$host;\n        proxy_set_header X-Forwarded-Server \$host;\n        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;\n        proxy_http_version 1.1;\n        proxy_pass_request_headers on;\n        proxy_set_header Connection "keep-alive";\n        proxy_store off;\n        proxy_pass http://netdata/\$ndpath\$is_args\$args;\n    }+g' /etc/nginx/sites-available/"$domain"
    # systemctl stop netdata
    # systemctl disable netdata
fi


##---------------##
#    Memcached    #
##---------------##

if [ $memcached = 1 ]; then
    apt install -y memcached
    # systemctl stop memcached
    # systemctl disable memcached
fi

##-----------##
#    Redis    #
##-----------##

if [ $redis = 1 ]; then
    apt install -y redis-server
    sed -i 's/supervised no/supervised systemd/g' /etc/redis/redis.conf
    sed -i 's/# bind 127.0.0.1 ::1/bind 127.0.0.1 ::1/g' /etc/redis/redis.conf
    sed -i 's/# requirepass foobared/requirepass '$password'/g' /etc/redis/redis.conf
    # systemctl stop redis
    # systemctl disable redis
fi

##---------------##
#    Wordpress    #
##---------------##

if [ $wordpress = 1 ]; then
    db_suffix=`expr $(ls -l /var/www | grep -c ^d) - 1`
    db_name="wp_$db_suffix"
    db_user="wp_$db_suffix"
    db_pass=$(date +%s|sha256sum|base64|head -c 32)
    mysql -u root -p"$password" -e "CREATE DATABASE "$db_name" DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;"
    mysql -u root -p"$password" -e "GRANT ALL ON "$db_name".* TO '"$db_user"'@'localhost' IDENTIFIED BY '"$db_pass"';"
    mysql -u root -p"$password" -e "FLUSH PRIVILEGES;"
    wget https://wordpress.org/latest.tar.gz -O /tmp/wp.tar.gz
    tar xzvf /tmp/wp.tar.gz -C /tmp
    mv /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php
    cp -a /tmp/wordpress/. /var/www/"$domain"/html
    WPSalts=$(wget https://api.wordpress.org/secret-key/1.1/salt/ -q -O -)
cat <<EOF > /var/www/"$domain"/html/wp-config.php
<?php
define('DB_NAME', '$db_name');
define('DB_USER', '$db_user');
define('DB_PASSWORD', '$db_pass');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '');
#define( 'WP_SITEURL', '' );
#define( 'WP_HOME', '' );
#define( 'ALTERNATE_WP_CRON', true );
#define('DISABLE_WP_CRON', 'true');
#define('WP_CRON_LOCK_TIMEOUT', 900);
#define('AUTOSAVE_INTERVAL', 300);
define( 'WP_MEMORY_LIMIT', '256M' );
define( 'DISALLOW_FILE_EDIT', true );
#define( 'EMPTY_TRASH_DAYS', 7 );
define( 'NOBLOGREDIRECT', 'https://$domain' );
#define( 'FS_CHMOD_DIR', ( 0755 & ~ umask() ) );
#define( 'FS_CHMOD_FILE', ( 0644 & ~ umask() ) );
#define( 'WP_ALLOW_REPAIR', true );
#define( 'FORCE_SSL_ADMIN', true );
#define( 'AUTOMATIC_UPDATER_DISABLED', true );
#define( 'WP_AUTO_UPDATE_CORE', false );
$WPSalts
\$table_prefix = '$db_name';

define('WP_DEBUG', false);
if ( !defined('ABSPATH') )
	define('ABSPATH', dirname(__FILE__) . '/');

#\$memcached_servers = array(
#    'default' => array(
#        '127.0.0.1:11211'
#    )
#);
#define('WP_REDIS_HOST', '127.0.0.1');
#define('WP_REDIS_PASSWORD', '$password');
#define('WP_REDIS_PORT', '6379');
require_once(ABSPATH . 'wp-settings.php');
EOF
fi

##-----------------##
#    Opcache GUI    #
##-----------------##

wget https://raw.githubusercontent.com/amnuts/opcache-gui/master/index.php -O /var/www/"$domain"/html/opcache.php

##--------------##
#    Info.php    #
##--------------##

cat > /var/www/"$domain"/html/info.php <<- "EOF"
<?php phpinfo();
EOF

##-----------------------##
#    Html Folder Perms    #
##-----------------------##

chown -R www-data:www-data /var/www/"$domain"/html