#!/bin/bash

SCRIPT_VER="1.8"

APP="ruTorrent (Latest)"
APP_CATEGORY="Torrent Clients and Utilities"
APP_ENABLED="yes"
APP_SCOPE="user"
CONFLICTS="ruTorrent (rtorrent 0.9.2)|ruTorrent (rtorrent 0.9.3)|ruTorrent (rtorrent 0.9.4)|ruTorrent (rtorrent 0.9.6)|ruTorrent (rtorrent 0.9.8)"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.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="/var/www/rutorrent"
APP_SESSION_DIRECTORY="/var/www/session"

while : ; do

    main_rc=1

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

    # ----------------------------------
    # -- Unistall ruTorret UI         --
    # ----------------------------------
    WGET "${RSB_URL}/uninstall_rutorrent_ui.inc.sh" || break
    . "${TMP_DIR}/uninstall_rutorrent_ui.inc.sh"

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

    # stop service
    SVC_STOP "rtorrent@${USERNAME}"
    # disable service
    SVC_DISABLE "rtorrent@${USERNAME}"

    RM_FILES "${USERHOME}/.rtorrent.rc"

    # It was last user in ruTorrent? - Will delete rtorrent service from machine....
    if [ ! -d "${APP_DIRECTORY}" ] ; then
        RM_FILES "/etc/systemd/system/rtorrent@.service" && SYSTEMD_RELOAD
        [ -d "/etc/systemd/system/rtorrent@.service.d" ] \
            && RM_DIRS "/etc/systemd/system/rtorrent@.service.d"
        ${PKG_CHECK} "rtorrent" \
            && ${PKG_REMOVE} "rtorrent"
    fi


    main_rc=0
    break

done


SCRIPTEXIT
