#!/bin/bash

# Exit on command errors and treat unset variables as an error
set -eu

source .fonctions	# Loads the generic functions usually used in the script
source /usr/share/yunohost/helpers # Source app helpers

CLEAN_SETUP () {
	# Clean installation residues that are not supported by the remove script.
	# Clean hosts
	sudo sed -i '/#GRAV/d' /etc/hosts
}
TRAP_ON	# Active trap to stop the script if an error is detected.

domain=$YNH_APP_ARG_DOMAIN
path=$YNH_APP_ARG_PATH
admin_grav=$YNH_APP_ARG_ADMIN
language=$YNH_APP_ARG_LANGUAGE
is_public=$YNH_APP_ARG_IS_PUBLIC

app=$YNH_APP_INSTANCE_NAME

CHECK_VAR "$app" "app name not set"

CHECK_USER "$admin_grav"

CHECK_PATH

CHECK_DOMAINPATH

CHECK_FINALPATH

ynh_app_setting_set $app domain $domain
ynh_app_setting_set $app path $path
ynh_app_setting_set $app admin $admin_grav
ynh_app_setting_set $app is_public $is_public
ynh_app_setting_set $app language $language

# Creates the destination directory and stores its location.
sudo mkdir "$final_path"
ynh_app_setting_set $app final_path $final_path

# Get source
SETUP_SOURCE

# Grav install
sudo $final_path/bin/grav

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

echo -e "127.0.0.1 $domain #GRAV" | sudo tee -a /etc/hosts

# Copy nginx config
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf

# Modif the variables in the nginx configuration file
sudo sed -i "s@__PATHTOCHANGE__@$path@g" /etc/nginx/conf.d/$domain.d/$app.conf
sudo sed -i "s@__FINALPATH__@$final_path@g" /etc/nginx/conf.d/$domain.d/$app.conf
sudo sed -i "s@__NAMETOCHANGE__@$app@g" /etc/nginx/conf.d/$domain.d/$app.conf

if [ "$is_public" = "Yes" ];
then
	sudo sed -i "s@#--PRIVATE--@@g" /etc/nginx/conf.d/$domain.d/$app.conf
fi

# Create the php-fpm pool config
POOL_FPM

# Setup SSOwat
ynh_app_setting_set "$app" is_public "$is_public"
if [ "$is_public" = "Yes" ];
then
  ynh_app_setting_set "$app" unprotected_uris "/"
fi

# Reload SSOwat configuration
sudo yunohost app ssowatconf

# Reload Nginx and regenerate SSOwat conf
sudo systemctl reload php5-fpm
sudo systemctl reload nginx

# Nettoyer hosts
sudo sed -i '/#GRAV/d' /etc/hosts