#!/usr/bin/env bash

# Custom configuration
H2DIR="disroot.lan"
WEBROOT="/var/www/$H2DIR"
WWWUSER="www-data"

# Provisioning actions

# Add sury repository to sources.list for PHP7.1
sudo apt install ca-certificates apt-transport-https 
echo "deb https://packages.sury.org/php/ stretch main" | sudo tee -a /etc/apt/sources.list.d/php.list
# Sury Key for PHP7.1
wget -q https://packages.sury.org/php/apt.gpg -O- | sudo apt-key add -
sudo apt-get -y update

echo "Installing Apache.."
sudo apt-get install -y apache2 composer
echo "Installing php7.."
sudo apt-get install -y php7.1-zip php7.1-cli php7.1-curl php7.1-gd php7.1-mysql php7.1-mbstring php7.1-xml libapache2-mod-php7.1 php7.1-mcrypt php7.1-fpm

# Enable all the Apache mods
sudo a2enmod proxy proxy_fcgi rewrite
sudo phpenmod mcrypt zip

# Create the Apache config files and restart webserver
sudo rsync -cr /vagrant/provision/etc/apache2/sites-available/ /etc/apache2/sites-available/
sudo sed -i "s/ServerName V_DOMAIN_NAME/ServerName $H2DIR/g" /etc/apache2/sites-available/*.conf
sudo sed -i "s/V_DOMAIN_NAME/$H2DIR/g" /etc/apache2/sites-available/*.conf
sudo a2ensite "$H2DIR".conf
sudo a2enconf php-fpm
sudo rm /etc/apache2/sites-enabled/000-default.conf
sudo service apache2 restart

# Install GRAV in webroot
composer create-project getgrav/grav $WEBROOT
cd $WEBROOT
sudo chown -R www-data:www-data  $WEBROOT
sudo chmod 775 -R bin/
sudo -u www-data bin/grav install
#sudo -u www-data bin/gpm install disroot
sudo -u www-data bin/gpm install language-selector
sudo -u www-data bin/gpm install form
sudo -u www-data sed -i 's/quark/disroot/g' $WEBROOT/user/config/system.yaml
sudo -u www-data ex -s -c '13i|redirect_default_route: true' -c x $WEBROOT/user/config/system.yaml
sudo -u www-data echo "
languages:
  supported:
    - en
    - es
    - fr
    - it" >> $WEBROOT/user/config/system.yaml
sudo -u www-data sed -i '4d' $WEBROOT/user/config/system.yaml
sudo -u www-data ex -s -c "4i|  alias: '/home'" -c x $WEBROOT/user/config/system.yaml
sudo -u www-data sed -i 's/false/true/g' $WEBROOT/user/plugins/language-selector/language-selector.yaml
#sudo -u www-data cp $WEBROOT/user/plugins/language-selector/templates/partials/language-selector.html.twig $WEBROOT/user/themes/disroot/templates/partials/
#sudo -u www-data ex -s -c "9i|	{% include 'partials/language-selector.hreflang.html.twig' %}" -c x $WEBROOT/user/themes/disroot/templates/partials/base.html.twig
#sudo -u www-data sed -i '2d' $WEBROOT/user/themes/disroot/css/layout.css

# Add website domain to local /etc/hosts file
sudo sed -i "s/127.0.0.1\tlocalhost/127.0.0.1\tlocalhost $H2DIR/" /etc/hosts

#Add website pages in GRAV
#rm -rf /var/www/disroot.lan/user/pages
sudo mount -o bind /var/www/pages /var/www/disroot.lan/user/pages
chown www-data:www-data -R /var/www/disroot.lan/user/pages
sudo -u www-data ln -s /var/www/grav-theme-disroot /var/www/disroot.lan/user/themes/disroot
exit 0
