#!/bin/bash

# Source YunoHost helpers
source /usr/share/yunohost/helpers

# Stop script if errors
set -u

# Import common cmd
source ./psql.sh
source ./experimental_helper.sh
source ./_common.sh

# Retrieve app settings
domain=$(ynh_app_setting_get $app special_domain)
final_path=$(ynh_app_setting_get $app final_path)
synapse_tls_port=$(ynh_app_setting_get $app synapse_tls_port)
turnserver_tls_port=$(ynh_app_setting_get $app turnserver_tls_port)
turnserver_alt_tls_port=$(ynh_app_setting_get $app turnserver_alt_tls_port)

systemctl stop matrix-$YNH_APP_INSTANCE_NAME.service || true
systemctl stop coturn-$app.service || true

# Close firewall ports
closeport() {
    if yunohost firewall list | grep -q "\- $port$"
    then
            echo "Close port $port"
            yunohost firewall disallow Both $port > /dev/null
    fi
}

port=$synapse_tls_port
closeport
port=$turnserver_tls_port
closeport
port=$turnserver_alt_tls_port
closeport

# Remove the skipped url
python $final_path/remove_sso_conf.py

# Remove depandance
ynh_remove_app_dependencies || true

# Clean all directory
ynh_secure_remove $final_path
ynh_secure_remove /var/lib/matrix-$YNH_APP_INSTANCE_NAME
ynh_secure_remove /var/log/matrix-$YNH_APP_INSTANCE_NAME
ynh_secure_remove /etc/matrix-$YNH_APP_INSTANCE_NAME
ynh_secure_remove /etc/default/matrix-$YNH_APP_INSTANCE_NAME
ynh_secure_remove /etc/default/coturn-$YNH_APP_INSTANCE_NAME

# Remove nginx config
ynh_remove_nginx_config

# Remove systemd service
ynh_remove_systemd_config matrix-$YNH_APP_INSTANCE_NAME
ynh_remove_systemd_config coturn-$YNH_APP_INSTANCE_NAME

# Remove database and user
ynh_psql_remove_db $synapse_db_name $synapse_db_user

# Remove user
ynh_system_user_delete matrix-$YNH_APP_INSTANCE_NAME

# Remove logrotate
ynh_remove_logrotate

# Remove Monitoring
yunohost service remove matrix-$YNH_APP_INSTANCE_NAME