#!/bin/bash

#=================================================
# GENERIC START
#=================================================

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

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

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

ynh_script_progression --message="Loading installation settings..."

# Retrieve arguments
domain=$(ynh_app_setting_get --app $app --key domain)

#=================================================
# STANDARD REMOVE
#=================================================

ynh_script_progression --message="Stoping services..."

# Stop all services
ynh_systemd_action --service_name seafile --action stop
ynh_systemd_action --service_name seahub --action stop

# Force to kill all process in case of a process is not stoped cleanly
pkill -f seafile-controller || true
pkill -f seaf-server || true
pkill -f ccnet-server || true
pkill -f seahub || true

ynh_script_progression --message="Removing logs..."
ynh_secure_remove --file=/var/log/seafile
ynh_script_progression --message="Removing code..."
ynh_secure_remove --file=/var/www/$app
ynh_secure_remove --file=/opt/yunohost/$app
ynh_secure_remove --file=/tmp/seahub_cache

# Remove databases
ynh_script_progression --message="Removing databases..."
ynh_mysql_remove_db --db_name ccnetdb --db_user seafile
ynh_mysql_remove_db --db_name seafiledb --db_user seafile
ynh_mysql_remove_db --db_name seahubdb --db_user seafile

# Remove systemd service
ynh_script_progression --message="Removing systemd units..."
ynh_remove_systemd_config --service seafile
ynh_remove_systemd_config --service seahub

# Remove user
ynh_script_progression --message="Removing the dedicated system user..."
ynh_system_user_delete --username seafile

# Remove depandance
ynh_script_progression --message="Removing dependencies" --weight=10
ynh_remove_app_dependencies

# Remove nginx config
ynh_script_progression --message="Removing nginx configuration..."
ynh_remove_nginx_config

# Remove logrotate
ynh_remove_logrotate

# Remove the dedicated fail2ban config
ynh_script_progression --message="Removing fail2ban configuration..."
ynh_remove_fail2ban_config

ynh_script_progression --message="Removing seafile service..."
yunohost service remove seafile
yunohost service remove seahub

ynh_print_info --message="Due of the backup core only feature the data directory in '/home/yunohost.app/seafile-data' was not removed. It need to be removed manually to purge app user data."

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