#!/bin/bash

#=================================================
# GENERIC START
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

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

#=================================================
# MANAGE SCRIPT FAILURE
#=================================================

ynh_abort_if_errors

#=================================================
# RETRIEVE ARGUMENTS FROM THE MANIFEST
#=================================================

domain=$YNH_APP_ARG_DOMAIN
path_url=$YNH_APP_ARG_PATH_URL
app=$YNH_APP_INSTANCE_NAME
app_user=$app

#==================================================
# CHECK IF THE APP CAN BE INSTALLED WITH THESE ARGS
#==================================================

www_path=/var/www/$app
if [[ -e $www_path ]]
then
  ynh_die "The path $www_path already contains a folder"
fi

# Normalize the url path syntax
path_url=$(ynh_normalize_url_path $path_url)
# Trim trailing slashes
path_url=$(sed 's@*/$@@' <<< $path_url)

# Check web path availability
if ! ynh_webpath_available $domain $path_url
then
  ynh_die "$domain$path_url is not available"
fi

# Register (book) web path
ynh_webpath_register $app $domain $path_url

#=================================================
# STORE SETTINGS
#=================================================

ynh_app_setting_set $app domain $domain
ynh_app_setting_set $app path_url $path_url
ynh_app_setting_set $app app_user $app_user
ynh_app_setting_set $app www_path $www_path

#=================================================
# STANDARD MODIFICATIONS
#=================================================
# CREATE DEDICATED USER
#=================================================

ynh_print_info "Creating app's user…"

mkdir -p $www_path
ynh_system_user_create $app_user $www_path

#=================================================
# INSTALL STATIC FILE
#=================================================

ynh_print_info "Installing static site…"

cp -a ../sources/. $www_path
chown -R $app_user: $www_path

sed -i "s@PATHTOCHANGE@$path_url@g" ../conf/nginx.conf
sed -i "s@ALIASTOCHANGE@$www_path@g" ../conf/nginx.conf

cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf

nginx -tq
service nginx reload