#!/bin/bash

clear
echo "--- Contentify DigitalOcean Installation Script ---"

# Set variables
RELEASEFILE="contentify_3_0"
CMSURL="contentify.org/share/releases/"
SCRIPTDIR=$(pwd)

# Update packet sources
sudo apt-get update

# Activate the mod_rewrite module
sudo a2enmod rewrite

# Change the document root
/bin/cat <<EOM >/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/public

    <Directory "/var/www/html/public/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog /var/www/error.log
    CustomLog /var/www/access.log combined
</VirtualHost>
EOM

# Note: DigitalOcean install Ubuntu 18 with PHP 7.2.
# Install the PHP mbstring extension
sudo apt-get install php7.2-mbstring

# Install the PHP curl extension
sudo apt-get install php7.2-curl

# Install XML extension
sudo apt-get install php7.2-xml

# Create database
clear
echo ""
echo "--- Creating Database ---"
# Show the file where the pw is stored
cat /root/.digitalocean_password
echo "Please enter the password shown above: "
read SQLPW
mysql --user=root --password=$SQLPW -e "CREATE DATABASE contentify2 CHARACTER SET=utf8 COLLATE=utf8_unicode_ci"

# Secure the database
mysql --user=root --password=$SQLPW -e "DROP USER ''@'localhost'"
mysql --user=root --password=$SQLPW -e "DROP USER ''@'$(hostname)'"
mysql --user=root --password=$SQLPW -e "DROP DATABASE test"
mysql --user=root --password=$SQLPW -e "FLUSH PRIVILEGES"

# Restart Apache
sudo service apache2 restart

# Install unzip
sudo apt-get install unzip

# Go to www dir
cd /var/www/

# Remove the existing html dir (it will be recreated)
rm -rf html

# Download the CMS
wget ${CMSURL}${RELEASEFILE}.zip

# Unzip
unzip -q ${RELEASEFILE}.zip >/dev/null

# Delete zip file
rm ${RELEASEFILE}.zip

# Rename dir
mv $RELEASEFILE html

# Change access permissions
cd html
chmod -R 777 storage
chmod -R 777 bootstrap/cache
chmod -R 777 public

# Save the MySQL password
sed -i '7s/.*/password = '$SQLPW'/' storage/app/database.ini

clear
echo ""
echo "--- Done. You are now ready to install Contentify! ---"

echo "With your browser, navigate to your website:"
printf "%s" "http://"
wget http://ipinfo.io/ip -qO -

# Remove script file
rm $SCRIPTDIR/install.sh