#!/bin/bash

#=================================================
# GENERIC STARTING
#=================================================
# IMPORT GENERIC HELPERS
#=================================================

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

#=================================================
# MODIFY URL IN NGINX CONF
#=================================================
ynh_script_progression --message="Updating NGINX web server configuration..." --weight=2

ynh_change_url_nginx_config

#=================================================
# SPECIFIC MODIFICATIONS
#=================================================
ynh_script_progression --message="Applying $app specific modifications..." --weight=2

# Define a function to execute commands with `occ`
exec_occ() {
  (cd "$install_dir" && ynh_exec_as "$app" \
      php${phpversion} --define apc.enable_cli=1 occ --no-interaction --no-ansi "$@")
}

if [ $change_domain -eq 1 ]
then
	# Change the trusted domain
	exec_occ config:system:set trusted_domains 1 --value=$new_domain

	# Change hostname for activity notifications
    exec_occ config:system:set overwrite.cli.url --value="https://${new_domain}"
fi

if [ $change_domain -eq 1 ]
then
	# Check if .well-known is available for this domain
	if is_url_handled --domain="$new_domain" --path="/.well-known/caldav" || is_url_handled --domain="$new_domain" --path="/.well-known/carddav"
	then
		ynh_print_warn --message="Another app already uses the domain $new_domain to serve a CalDAV/CardDAV feature. You may encounter issues when dealing with your calendar or address book."

		# Remove lines about .well-known/carddav and caldav with sed.
		sed --in-place --regexp-extended '/location = \/\.well\-known\/(caldav|carddav)/d' "/etc/nginx/conf.d/$new_domain.d/$app.conf"
		ynh_store_file_checksum --file="/etc/nginx/conf.d/$new_domain.d/$app.conf"
	fi
fi

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

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