#!/bin/bash

SCRIPT_VER="1.1"

APP="qBittorrent WebUI (Latest)"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
#><#APP_CHECK_VER_CMD="[ -e "/usr/local/qbittorrent-nox-static/version.id" ] && cat "/usr/local/qbittorrent-nox-static/version.id" || echo """
STORED_PASSWORD_SERVICE="user"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=18180
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/qBittorrent_static"
APP_HOME="/usr/local/qbittorrent-nox-static"

while : ; do

    main_rc=1

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

    systemctl is-enabled "qbittorrent-static@${USERNAME}" > /dev/null 2>&1 \
        && SVC_DISABLE "qbittorrent-static@${USERNAME}"
    systemctl is-active "qbittorrent-static@${USERNAME}" > /dev/null 2>&1 \
        && SVC_STOP  "qbittorrent-static@${USERNAME}"

    if [ -d "${APP_DIRECTORY}" ] ; then
        RM_DIRS "${APP_DIRECTORY}"
    fi

    if [ -e "/etc/apache2/userconf-enabled/qbittorrent-static-${USERNAME}.conf" ] ; then
        if [ "${USERUID}" = "${FIRST_UID}" ] ; then
            [ -e "/etc/apache2/userconf-enabled/qbittorrent-static.conf" ] \
                && RM_FILES "/etc/apache2/userconf-enabled/qbittorrent-static.conf"
        fi
        RM_FILES "/etc/apache2/userconf-enabled/qbittorrent-static-${USERNAME}.conf"
        SVC_RELOAD "apache2"
    fi

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


    main_rc=0
    break

done


SCRIPTEXIT
