#!/bin/bash

# Retrieve arguments
domain=$(sudo yunohost app setting leed domain)
path=$(sudo yunohost app setting leed path)
is_public=$(sudo yunohost app setting leed is_public)

# Copy files to right place
final_path=/var/www/leed
sudo mkdir -p $final_path
sudo cp -a ../sources/* $final_path
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/leed.conf

# Set right permissions
sudo chown -R www-data: $final_path

# Change variables in Leed configuration
sudo sed -i "s@PATHTOCHANGE@$path@g" /etc/nginx/conf.d/$domain.d/leed.conf
sudo sed -i "s@ALIASTOCHANGE@$final_path/@g" /etc/nginx/conf.d/$domain.d/leed.conf

# Files owned by root, www-data can just read
sudo find $final_path -type f | xargs sudo chmod 644
sudo find $final_path -type d | xargs sudo chmod 755
sudo chown -R root: $final_path
# www-data can write on plugins and cache
sudo chown -R www-data $final_path/cache $final_path/plugins

# Make app private if necessary
sudo yunohost app setting leed is_public -v "$is_public"
if [ "$is_public" = "No" ];
then
	# Retire l'autorisation d'accès de la page d'install.
	sudo yunohost app setting leed unprotected_uris -d
	# Rend la page d'actualisation accessible pour le script cron.
	sudo yunohost app setting leed skipped_uris -v "/action.php"
else	# Si l'app est publique
	sudo yunohost app setting leed unprotected_uris -v "/"
fi

# Reload Nginx and regenerate SSOwat conf
sudo service nginx reload
sudo yunohost app ssowatconf
