#!/bin/bash

SCRIPT_VER="1.4"

APP="Deluge"
APP_CATEGORY="Torrent Clients and Utilities"
APP_ENABLED="yes"
#SYS_PKG_NAME="deluged"
#><#APP_CHECK_VER_CMD="${PKG_VER} deluged"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
LIBRARY="functions4.sh"

if [ "${SUPPORT-}" = '' ]; then
    SUPPORT="https://installers.rapidseedbox.com/scripts/whmcs_client_installers/support"
fi

LOGFILE="/var/log/whmcs_client_installers/${0}.log"
[ ! -d "/var/log/whmcs_client_installers" ] && mkdir -p "/var/log/whmcs_client_installers"

wget -4 -nc -q --no-check-certificate --timeout=20 --tries=5 ${SUPPORT}/${LIBRARY} >> "${LOGFILE}" 2>&1
if [ ! -f "./${LIBRARY}" ] ; then
    echo "55"
    echo "Error downloading \"${SUPPORT}/${LIBRARY}\"" >> "${LOGFILE}"
    exit 55
fi

# shellcheck source=support/functions4.sh
. "./${LIBRARY}"
SCRIPTENTRY

VALIDATE_USER


APP_DIRECTORY="${USERHOME}/.config/deluge"

while : ; do

    main_rc=1

    CHECK_APP ; _rc=$?
    if [ ${_rc} -ne 0 ] ; then
        main_rc=${_rc}
        break
    fi


    for svc in "deluged" "deluge-web" ; do

        # reconfigure 'monit'
        if [ -f "/etc/monit/conf.d/${svc}@${USERNAME}" ] ; then
            RM_FILES "/etc/monit/conf.d/${svc}@${USERNAME}"
            MONIT_RELOAD
        fi

        # stop service
        SVC_STOP "${svc}@${USERNAME}"

        # disable service
        SVC_DISABLE "${svc}@${USERNAME}"

    done

    RM_DIRS "${APP_DIRECTORY}"
    RM_DIRS "/var/log/deluge/${USERNAME}"

    for f in \
        "/etc/apache2/userconf-enabled/${USERNAME}.conf" \
        "/etc/apache2/userconf-enabled/deluge-${USERNAME}.conf" \
        "/etc/logrotate.d/deluge-${USERNAME}"
    do
        [ -e "${f}" ] && RM_FILES "${f}"
    done


    # It was last user in Deluge? - Will delete Deluge from machine....
    ret="$( find /home -type d -a -iwholename '*/.config/deluge' )"
    if [ -z "${ret[@]}" ] ; then
        case "${LSB_VENDOR}" in
          "Ubuntu")
              deluged_pkg="deluged"
              ;;
        esac
        for pkg in "${deluged_pkg}" "deluge-web" "deluge-console" ; do
            ${PKG_REMOVE} "${pkg}"
        done
        case "${LSB_VENDOR}" in
          "Ubuntu")
              DEL_APT_REPO "ppa:deluge-team/stable"
              DEL_APT_REPO "ppa:deluge-team/develop"
              DEL_APT_REPO "ppa:deluge-team/ppa" || break
              ;;
        esac
        ${PKG_AUTOREMOVE}
        ${PKG_UPDATE}
        RM_DIRS "/var/log/deluge"
        RM_FILES "/etc/systemd/system/deluged@.service"
        [ -d "/etc/systemd/system/deluged@.service.d" ] \
             && RM_DIRS "/etc/systemd/system/deluged@.service.d"
        RM_FILES "/etc/systemd/system/deluge-web@.service"
        SYSTEMD_RELOAD
    fi


    # restart service 'apache2'
    SVC_RESTART "apache2"


    main_rc=0
    break

done


SCRIPTEXIT
