#!/bin/bash

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

# retrieve arguments
app=$YNH_APP_INSTANCE_NAME
old_domain=$YNH_APP_OLD_DOMAIN
new_domain=$YNH_APP_NEW_DOMAIN

# load settings
ynh_script_progression --message="Loading installation settings..." --time --weight=1
old_nginx_conf="/etc/nginx/conf.d/$old_domain.d/$app.conf"
new_nginx_conf="/etc/nginx/conf.d/$new_domain.d/$app.conf"

# manage script failure
ynh_script_progression --message="Backing up the app before changing its url (may take a while)..." --time --weight=1
ynh_backup_before_upgrade
ynh_clean_setup () {
	ynh_secure_remove --file="/etc/nginx/conf.d/$new_domain.d/$app.conf"
	ynh_restore_upgradebackup
}
ynh_abort_if_errors

# check which parts should be changed
change_domain=0
if [ "$old_domain" != "$new_domain" ]; then
	change_domain=1
fi

# Change the domain for nginx
if [ $change_domain -eq 1 ]; then
    ynh_script_progression --message="Updating nginx web server configuration..." --time --weight=1
	# Delete file checksum for the old conf file location
	ynh_delete_file_checksum --file="$old_nginx_conf"
	mv "$old_nginx_conf" "$new_nginx_conf"
	# Store file checksum for the new config file location
	ynh_store_file_checksum --file="$new_nginx_conf"
fi

# reload nginx
ynh_script_progression --message="Reloading nginx web server..." --time --weight=1
ynh_systemd_action --service_name=nginx --action=reload

ynh_script_progression --message="Change of URL completed for $app" --time --last