#!/bin/bash

clear

echo
echo "Welcome to the 1 command mautic-installation"
echo
echo "Created by Matthias Reich - Info@Online-Business-Duplicator.de"
echo
echo "For infos about this script and detailed step by step videos visit: https://online-business-duplicator.de/mautic"
echo
echo "==========================================================================================================================="
echo
read -p "Subdomain for your mautic-installation (without http:// or https:// " mautic_subdomain
echo
read -p "E-mail sender adress for outgoing mails: " sender_email
echo
read -p "Your firstname: " sender_firstname
echo
read -p "Your lastanme: " sender_lastname
echo 
read -p "E-mail adress to which you want infos and updates about this script: " sender_newsletter
echo
echo "==========================================================================================================================="
echo
read -p "Ready for installation. Press RETURN to continue or STRG + C to stop the installation ..."
echo

mkdir /root/mautic-scripts

mysql_root_password=$(cat /dev/urandom | tr -dc '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#()@' | head -c32)
mysql_mautic_database_password=$(cat /dev/urandom | tr -dc '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#()@' | head -c32)
mautic_secret_key=$(cat /dev/urandom | tr -dc '1234567890abcdefghijklmnopqrstuvwxyz' | head -c64)
mautic_rememberme_key=$(cat /dev/urandom | tr -dc '1234567890abcdefghijklmnopqrstuvwxyz' | head -c40)
mautic_admin_password=$(cat /dev/urandom | tr -dc '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#()@' | head -c32)

file_inhalt="$(cat << EOF
#!/bin/bash
mautic_domain="${mautic_subdomain}"
sender_email="${sender_email}"
sender_firstname="${sender_firstname}"
sender_lastname="${sender_lastname}"
mysql_root_password="${mysql_root_password}"
mysql_mautic_database_password="${mysql_mautic_database_password}"
mautic_secret_key="${mautic_secret_key}"
mautic_rememberme_key="${mautic_rememberme_key}"
backup_directory="/root/mautic-backups/"
mautic_admin_password="${mautic_admin_password}"
EOF
)"
echo "${file_inhalt}" > /root/mautic-scripts/mautic.conf

DEBIAN_FRONTEND=noninteractive apt-get -yq update
DEBIAN_FRONTEND=noninteractive apt-get -yq upgrade

# timedatectl set-timezone Europe/Berlin

apt install -y nginx htop
systemctl enable nginx
systemctl start nginx
chown www-data:www-data /usr/share/nginx/html -R
apt install -y mariadb-server mariadb-client
systemctl enable mariadb

mysql_secure_installation <<EOF
y
$mysql_root_password#1
$mysql_root_password#1
y
y
y
y
y
EOF

apt install -y php7.4 php7.4-fpm php7.4-mysql php-common php7.4-cli php7.4-common php7.4-json php7.4-opcache php7.4-readline php7.4-mbstring php7.4-xml php7.4-gd php7.4-curl
systemctl start php7.4-fpm
systemctl enable php7.4-fpm
rm /etc/nginx/sites-enabled/default

file_inhalt="$(cat << EOF
server {
  listen 80;
  listen [::]:80;
  server_name _;
  root /usr/share/nginx/html/;
  index index.php index.html index.htm index.nginx-debian.html;

  location / {
    try_files \$uri \$uri/ /index.php;
  }

  location ~ \.php$ {
    fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
    include fastcgi_params;
    include snippets/fastcgi-php.conf;
  }

 # A long browser cache lifetime can speed up repeat visits to your page
  location ~* \.(jpg|jpeg|gif|png|webp|svg|woff|woff2|ttf|css|js|ico|xml)$ {
       access_log        off;
       log_not_found     off;
       expires           360d;
  }

  # disable access to hidden files
  location ~ /\.ht {
      access_log off;
      log_not_found off;
      deny all;
  }
}
EOF
)"
echo "${file_inhalt}" > /etc/nginx/conf.d/default.conf


systemctl reload nginx
mkdir -p /etc/systemd/system/nginx.service.d/

file_inhalt="$(cat << EOF
[Service]
Restart=always
RestartSec=5s
EOF
)"
echo "${file_inhalt}" > /etc/systemd/system/nginx.service.d/restart.conf

systemctl daemon-reload

sed -i 's/memory_limit = 128M/memory_limit = 2048M/' /etc/php/7.4/fpm/php.ini
sed -i 's/post_max_size = 8M/post_max_size = 512M/' /etc/php/7.4/fpm/php.ini
sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 512M/' /etc/php/7.4/fpm/php.ini
sed -i 's/memory_limit = 128M/memory_limit = 2048M/' /etc/php/7.4/fpm/php.ini
sed -i 's/max_execution_time = 30/max_execution_time = 360/' /etc/php/7.4/fpm/php.ini
# sed -i 's+;date.timezone =+date.timezone = Europe/Berlin+' /etc/php/7.4/fpm/php.ini
sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/' /etc/php/7.4/fpm/php.ini
sed -i 's/session.gc_maxlifetime = 1440/session.gc_maxlifetime = 14400/' /etc/php/7.4/fpm/php.ini

systemctl restart php7.4-fpm.service

apt install -y unzip zip
wget https://online-business-duplicator.de/mautic-install/mautic-files-template-en.zip
mkdir -p /var/www/mautic/
unzip mautic-files-template-en.zip -d /var/www/
chown -R www-data:www-data /var/www/mautic/
rm mautic-files-template-en.zip

apt install -y php-imagick php7.4-fpm php7.4-mysql php7.4-common php7.4-gd php7.4-imap php7.4-imap php7.4-json php7.4-curl php7.4-zip php7.4-xml php7.4-mbstring php7.4-bz2 php7.4-intl php7.4-gmp

echo "CREATE DATABASE mautic DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;GRANT ALL ON mautic.* TO 'mauticuser'@'localhost' IDENTIFIED BY '${mysql_mautic_database_password}';FLUSH PRIVILEGES;" | mysql -u root

file_inhalt="$(cat << EOF
server {
   listen 80;
   listen [::]:80;
   server_name ${mautic_subdomain};

   root /var/www/mautic;
   error_log /var/log/nginx/mautic.error;
   access_log /var/log/nginx/mautic.access;
   client_max_body_size 512M;

   index index.php index.html index.htm index.nginx-debian.html;

   location / {
     # try to serve file directly, fallback to app.php
     try_files \$uri /index.php\$is_args\$args;
   }

   location ~ /(mtc.js|1.js|mtracking.gif|.*\.gif|mtc) {
       # default_type "application/javascript";
       try_files \$uri /index.php\$is_args\$args;
   }

   # redirect some entire folders
     rewrite ^/(vendor|translations|build)/.* /index.php break;

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

   location ~* ^/index.php {
     # try_files \$uri =404;
     fastcgi_split_path_info ^(.+\.php)(/.+)$;
     # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

     fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
     fastcgi_index index.php;
     fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
     include fastcgi_params;

     fastcgi_buffer_size 128k;
     fastcgi_buffers 256 16k;
     fastcgi_busy_buffers_size 256k;
     fastcgi_temp_file_write_size 256k;
   }

    # Deny everything else in /app folder except Assets folder in bundles
    location ~ /app/assets/* {
        allow all;
        access_log off;
    }

    location ~ /app/bundles/.*/Assets/ {
        allow all;
        access_log off;
    }
    location ~ /app/ { deny all; }

    # Deny everything else in /addons or /plugins folder except Assets folder in bundles
    location ~ /(addons|plugins)/.*/Assets/ {
        allow all;
        access_log off;
    }
    # location ~ /(addons|plugins)/ { deny all; }

    # Deny all php files in themes folder
      location ~* ^/themes/(.*)\.php {
        deny all;
    }

    # Don't log favicon
    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    # Don't log robots
    location = /robots.txt  {
        access_log off;
        log_not_found off;
    }

    # Deny yml, twig, markdown, init file access
    location ~* /(.*)\.(?:markdown|md|twig|yaml|yml|ht|htaccess|ini)$ {
        deny all;
        access_log off;
        log_not_found off;
    }

  # Allow access to certbot directory in order to obtain TLS certificate
     location ~ /.well-known/acme-challenge {
      allow all;
   }

  # Deny all attempts to access hidden files/folders such as .htaccess, .htpasswd, .DS_Store (Mac), etc...
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Deny all grunt, composer files
    location ~* (Gruntfile|package|composer)\.(js|json)$ {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Deny access to any files with a .php extension in the uploads directory
        location ~* /(?:uploads|files)/.*\.php$ {
                deny all;
    }

     # A long browser cache lifetime can speed up repeat visits to your page
  location ~* \.(jpg|jpeg|gif|png|webp|svg|woff|woff2|ttf|css|js|ico|xml)$ {
       access_log        off;
       log_not_found     off;
       expires           360d;
  }
}
EOF
)"
echo "${file_inhalt}" > /etc/nginx/conf.d/mautic.conf

systemctl reload nginx
apt install -y certbot
mkdir -p /var/www/mautic/.well-known/acme-challenge
chown www-data:www-data /var/www/mautic/.well-known/acme-challenge
apt install -y python3-certbot-nginx
certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --no-eff-email --email $sender_email -d $mautic_subdomain

sed -i 's/listen 443 ssl;/listen 443 ssl http2;/' /etc/nginx/conf.d/mautic.conf
systemctl reload nginx

file_inhalt="$(cat << EOF
# /etc/crontab: system-wide crontab

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

*/5 * * * * root /root/mautic-scripts/mautic-cronjobs-001.sh &> /dev/null
3 * * * * root /root/mautic-scripts/mautic-cronjobs-002.sh &> /dev/null
0 * * * * root /root/mautic-scripts/backup-mautic-datenbank.sh &> /dev/null
0 4 * * * root /root/mautic-scripts/backup-mautic-dateien.sh &> /dev/null
EOF
)"
echo "${file_inhalt}" > /etc/crontab

cd /root/mautic-scripts
source mautic.conf

mkdir $backup_directory

cd /root/

wget https://online-business-duplicator.de/mautic-install/mautic-scripts.zip
unzip mautic-scripts.zip -d /root/ 
rm mautic-scripts.zip

wget https://online-business-duplicator.de/mautic-install/mautic-database-template-en.sql.zip
unzip mautic-database-template-en.sql.zip
rm mautic-database-template-en.sql.zip

sed -i "s|Info@Online-Business-Duplicator.de|$sender_email|g" mautic-database-template-en.sql
sed -i "s|mautic-demo.online-business-duplicator.de|$mautic_domain|g" mautic-database-template-en.sql
sed -i "s|Matthias|$sender_firstname|g" mautic-database-template-en.sql
sed -i "s|Reich|$sender_lastname|g" mautic-database-template-en.sql

mysql -u root -p$mysql_root_password mautic < mautic-database-template-en.sql
rm mautic-database-template-en.sql

mautic_admin_password_md5=$(echo "$mautic_admin_password" | openssl passwd -1 -stdin)
echo "use mautic; UPDATE users SET password='${mautic_admin_password_md5}' WHERE username='mautic-admin';" | mysql -u root

wget https://online-business-duplicator.de/mautic-install/local-en.php.zip
unzip local-en.php.zip -d /root/
mv local-en.php local.php
rm local-en.php.zip

sed -i "s|###mysql_mautic_database_password###|$mysql_mautic_database_password|g" local.php
sed -i "s|###sender_firstname###|$sender_firstname|g" local.php
sed -i "s|###sender_lastname###|$sender_lastname|g" local.php
sed -i "s|###sender_email###|$sender_email|g" local.php
sed -i "s|###mautic_secret_key###|$mautic_secret_key|g" local.php
sed -i "s|###mautic_domain###|$mautic_domain|g" local.php
sed -i "s|###mautic_rememberme_key###|$mautic_rememberme_key|g" local.php

cp local.php /var/www/mautic/app/config/
rm local.php

chown -R www-data:www-data /var/www/mautic/

ufw allow ssh 
ufw allow 80
ufw allow 443
ufw --force enable

apt-get -y install fail2ban 
cp /etc/fail2ban/jail.{conf,local}

sed -i "s|bantime  = 10m|bantime  = 1d|g" /etc/fail2ban/jail.local

systemctl restart fail2ban

echo
echo
echo
echo
echo "===========================================================================================================================" 
echo
echo "Installation finished!"
echo
echo "Login under: https://"$mautic_domain
echo "User: mautic-admin"
echo "Password: "$mautic_admin_password
echo
echo "===========================================================================================================================" 
echo "Created by Matthias Reich - Info@Online-Business-Duplicator.de"
echo
echo "For infos about this script and detailed step by step videos visit: https://online-business-duplicator.de/mautic"
echo "===========================================================================================================================" 
