#!/bin/bash

# Controleer of het script als root wordt uitgevoerd
if [[ $EUID -ne 0 ]]; then
   echo "Dit script moet als root worden uitgevoerd."
   exit 1
fi

# Vraag de gebruiker om de domeinnaam en het e-mailadres
read -p "Voer de domeinnaam in voor Certbot: " DOMAIN
read -p "Voer het e-mailadres in voor Certbot: " EMAIL

# Genereer een willekeurig wachtwoord voor de databasegebruiker
DB_PASSWORD=$(openssl rand -base64 16)

# Escape speciale tekens in het wachtwoord voor gebruik met sed
ESCAPED_DB_PASSWORD=$(echo "$DB_PASSWORD" | sed 's/[\/&]/\\&/g')

# Werk de pakketlijst bij en installeer vereiste pakketten
apt update
apt install -y apache2 mariadb-server libapache2-mod-php
apt install -y php-mysql php-curl php-json php-cgi php-xsl php-mbstring php-zip php-xmlrpc php-soap php-intl php-imagick php-readline php-xml php-gd php-cli php-bz2

# Installeer Certbot en het Apache-plugin
apt install -y certbot python3-certbot-apache

# Verwijder de standaard index.html-pagina van Debian
rm /var/www/html/index.html

# Download en installeer WordPress
cd /tmp
wget https://wordpress.org/latest.tar.gz
tar xzvf latest.tar.gz
touch /tmp/wordpress/.htaccess
cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php
mkdir /tmp/wordpress/wp-content/upgrade
cp -a /tmp/wordpress/. /var/www/html

# Stel de juiste machtigingen in
chown -R www-data:www-data /var/www/html
find /var/www/html -type d -exec chmod 750 {} \;
find /var/www/html -type f -exec chmod 640 {} \;

# Schakel de standaard Apache-welkomstpagina uit
a2dissite 000-default.conf

# Configureer de Apache-virtual host
cat > /etc/apache2/sites-available/wordpress.conf <<EOL
<VirtualHost *:80>
    DocumentRoot /var/www/html
    ServerName $DOMAIN

    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/wordpress_error.log
    CustomLog \${APACHE_LOG_DIR}/wordpress_access.log combined
</VirtualHost>
EOL

# Activeer de nieuwe site en Certbot
a2ensite wordpress.conf
a2enmod rewrite
systemctl reload apache2

# Voer Certbot uit om een SSL-certificaat te verkrijgen
certbot --apache -d $DOMAIN --non-interactive --agree-tos --email $EMAIL

# Configureer de MariaDB-database
mysql -u root -e "CREATE DATABASE wordpress;"
mysql -u root -e "CREATE USER 'wordpressuser'@'localhost' IDENTIFIED BY '$DB_PASSWORD';"
mysql -u root -e "GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpressuser'@'localhost';"
mysql -u root -e "FLUSH PRIVILEGES;"

# Configureer wp-config.php
sed -i "s/database_name_here/wordpress/" /var/www/html/wp-config.php
sed -i "s/username_here/wordpressuser/" /var/www/html/wp-config.php
sed -i "s/password_here/$ESCAPED_DB_PASSWORD/" /var/www/html/wp-config.php
sed -i "s/localhost/127.0.0.1/" /var/www/html/wp-config.php

echo "WordPress is geïnstalleerd en geconfigureerd op $DOMAIN."

