#!/bin/bash

SCRIPT_VER="1.1"

APP="uTorrent"
APP_CATEGORY="Torrent Clients and Utilities"
APP_ENABLED="no"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.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}/utorrent"

while : ; do

    main_rc=1

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

    # reconfigure 'logrotate' and 'monit'
    [ -e "/etc/logrotate.d/utserver-${USERNAME}" ] \
        && RM_FILES "/etc/logrotate.d/utserver-${USERNAME}"
    if [ -e "/etc/monit/conf.d/utserver@${USERNAME}" ] ; then
        RM_FILES "/etc/monit/conf.d/utserver@${USERNAME}"
        MONIT_RELOAD
    fi

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

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

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

    # It was last user in uTorrent? - Will delete uTorrent from machine....
    ret="$( find /home -type d -a -iwholename '*/utorrent' )"
    if [ -z "${ret[@]}" ] ; then
        RM_DIRS  "/opt/utorrent"
        RM_FILES "/etc/systemd/system/utserver@.service"
        SYSTEMD_RELOAD
    fi

    main_rc=0
    break

done


SCRIPTEXIT
