#!/bin/bash

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

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

#from 2023.1~ynh1
#End of support for mosquitto. However, we still keep trace of if it was installed in order to be able to back it up and remove it correctly
mosquitto=$(ynh_app_setting_get --app=$app --key=mosquitto)
if [[ -z "${mosquitto+x}" ]]; then
	if [[ "$mqtt_domain"="$domain" ]]; then
		ynh_app_setting_set --app="$app" --key=mosquitto --value=0
	else
		ynh_print_warn --message="If you didn't already do it, you should migrate to mosquitto package outside of the app as it will soon not be maintained anymore"
		ynh_app_setting_set --app="$app" --key=mosquitto --value=1
	fi
fi

#=================================================
# STANDARD REMOVE
#=================================================
# REMOVE SERVICE INTEGRATION IN YUNOHOST
#=================================================

if [ "$mosquitto" = 1 ]; then
	ynh_script_progression --message="Removing system configurations related to Mosquitto..." --weight=1
	yunohost service remove mosquitto
	ynh_secure_remove --file="/etc/mosquitto/conf.d"
	ynh_secure_remove --file="/usr/share/yunohost/hooks/conf_regen/95-nginx_domoticz"
	ynh_secure_remove --file="/etc/nginx/conf.d/"$mqtt_domain".d/mqtt_"$app".conf"
	yunohost tools regen-conf postfix
	ynh_secure_remove --file="/var/log/mosquitto"
fi

ynh_script_progression --message="Removing system configurations related to $app..." --weight=1
if ynh_exec_warn_less yunohost service status "$app" >/dev/null
then
	ynh_script_progression --message="Removing $app service integration..."
	yunohost service remove "$app"
fi

# Remove the dedicated systemd config
ynh_remove_systemd_config

ynh_secure_remove --file="/etc/nginx/conf.d/"$domain".d/api_"$app".conf"
ynh_remove_nginx_config

ynh_remove_logrotate

ynh_remove_fail2ban_config

ynh_secure_remove --file="/var/log/$app"

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

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