#!/bin/bash

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

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

upgrade_type=$(ynh_check_app_version_changed)

#=================================================
# STOP SYSTEMD SERVICE
#=================================================
ynh_script_progression --message="Stopping a systemd service..." --weight=1

ynh_systemd_action --service_name=nginx --action="stop" --log_path="/var/log/$app/$app.log"

#=================================================
# "REBUILD" THE APP (DEPLOY NEW SOURCES, RERUN NPM BUILD...)
#=================================================
# DOWNLOAD, CHECK AND UNPACK SOURCE
#=================================================

if [ "$upgrade_type" == "UPGRADE_APP" ]
then
	ynh_script_progression --message="Upgrading source files..." --weight=1

	# Download, check integrity, uncompress and patch the source from app.src
	ynh_setup_source --dest_dir="$install_dir"
fi

# $install_dir will automatically be initialized with some decent 
# permission by default ... however, you may need to recursively reapply
# ownership to all files such as after the ynh_setup_source step
chown -R $app:www-data "$install_dir"

#=================================================
# SYSTEM CONFIGURATION
#=================================================
ynh_script_progression --message="Adding system configurations related to $app..." --weight=1

# Create a dedicated PHP-FPM config using the conf/php-fpm.conf or conf/extra_php-fpm.conf
ynh_add_fpm_config

# Create a dedicated NGINX config using the conf/nginx.conf template
ynh_add_nginx_config

# # Create a dedicated systemd config
# ynh_add_systemd_config

#=================================================
# RELOAD NGINX
#=================================================
ynh_script_progression --message="Reloading NGINX web server..." --weight=1

ynh_systemd_action --service_name=nginx --action=reload --log_path="/var/log/$app/$app.log"

#=================================================
# END OF SCRIPT
#=================================================

ynh_script_progression --message="Installation of $app completed" --last