#!/bin/bash

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

source /usr/share/yunohost/helpers
source ./_common

app=$YNH_APP_INSTANCE_NAME

domain=$(ynh_app_setting_get "$app" domain)
path=$(ynh_app_setting_get "$app" path)
user=$(ynh_app_setting_get "$app" user)
is_public=$(ynh_app_setting_get $app is_public)

# Remove trailing "/" for next commands
if [[ ! "$path" == "/" ]]; then
    path=${path%/}
fi

# Init final_path, if ever it got deleted somehow
final_path=/var/www/$app
sudo mkdir -p $final_path

# Clean all files and directory except the data directory 
sudo rm -rf $final_path/{cfg,CREDITS.md,i18n,index.php,js,README.md,tmp,CHANGELOG.md,css,favicon.ico,img,INSTALL.md,lib,robots.txt,tpl}

# Copy files to the right place
extract_source $final_path

# 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

# except for data and tmp subdir, where www-data must have write permissions
sudo mkdir -p $final_path/{data,tmp}
sudo chown -R www-data:root $final_path/{data,tmp}
sudo chmod 700 $final_path/{data,tmp}

# Modify Nginx configuration file and copy it to Nginx conf directory
sed -i "s@YNH_WWW_PATH@$path@g" ../conf/nginx.conf
sed -i "s@YNH_WWW_ALIAS@$final_path/@g" ../conf/nginx.conf
nginxconf=/etc/nginx/conf.d/$domain.d/$app.conf
sudo cp ../conf/nginx.conf $nginxconf
sudo chown root: $nginxconf
sudo chmod 600 $nginxconf

# Set ssowat config
ynh_app_setting_set "$app" is_public "$is_public"
if [ "$is_public" = "Yes" ];
then
  ynh_app_setting_set "$app" unprotected_uris "/"
fi

# Reload Nginx
sudo systemctl reload nginx
sudo yunohost app ssowatconf