#!/bin/bash

# causes the shell to exit if any subcommand or pipeline returns a non-zero status
set -e

# Get app instance name
app=$YNH_APP_INSTANCE_NAME

# Retrieve arguments
domain=$YNH_APP_ARG_DOMAIN
path=$YNH_APP_ARG_PATH
public_site=$YNH_APP_ARG_PUBLIC_SITE

sudo yunohost app setting $app public_site -v $public_site

# Check domain/path availability
sudo yunohost app checkurl $domain$path -a $app
if [[ ! $? -eq 0 ]]; then
    exit 1
fi


# Copy files to the right place
final_path=/var/www/$app
sudo mkdir -p $final_path
sudo cp -a ../sources/* $final_path

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


# Modify Nginx configuration file and copy it to Nginx conf directory
sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf
sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf
# Reload Nginx and regenerate SSOwat conf
sudo service nginx reload
sudo yunohost app setting $app skipped_uris -v "/" 
if [ "$public_site" = "No" ];
then   
	sudo yunohost app setting $app protected_uris -v "/index.html,/scripts" 
fi
sudo yunohost app ssowatconf
