#!/bin/bash

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

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

# Stop script if errors
set -u

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

# Init get Final path
get_configuration

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

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

systemctl stop seafile-server.service

# 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

# remove sso config to unprotect domain.tld/seafhttp in /etc/ssowat/conf.json.persistent
test -e /var/www/$app/remove_sso_conf.py && python3 /var/www/$app/remove_sso_conf.py
test -e /opt/yunohost/$app/remove_sso_conf.py && python3 /opt/yunohost/$app/remove_sso_conf.py
ynh_secure_remove /var/log/seafile
ynh_secure_remove /var/www/$app
ynh_secure_remove /opt/yunohost/$app
ynh_secure_remove /etc/init.d/seafile-server
ynh_secure_remove /home/yunohost.app/seafile-data
ynh_secure_remove /tmp/seahub_cache

# Remove databases
ynh_mysql_drop_db ccnetdb
ynh_mysql_drop_db seafiledb
ynh_mysql_drop_db seahubdb

# Remove user
ynh_system_user_delete seafile

# Remove depandance
ynh_remove_app_dependencies

# Remove domain config
ynh_secure_remove /etc/nginx/conf.d/$domain.d/seafile.conf

# Remove logrotate
ynh_remove_logrotate

yunohost service remove seafile-server

# Reload nginx
systemctl reload nginx.service