#!/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 """
#><#APP_UPGRADE_VER_CMD="curl -Ls --connect-timeout 10 --retry 3 -m 30 -o /dev/null -w "%{url_effective}" https://github.com/userdocs/qbittorrent-nox-static/releases/latest | awk -F/ "{print \$NF}" | awk -F- "{print \$NF}""
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

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

    INFO "Installing '${APP}' binary into ${APP_HOME}/"
    if [ ! -d "${APP_HOME}" ] ; then
        MKDIR "${APP_HOME}" || break
    fi
    _ver="$( curl -Ls -m 30 -o /dev/null -w '%{url_effective}' \
                  https://github.com/userdocs/qbittorrent-nox-static/releases/latest \
                | awk -F '/' '{print $NF}' \
                | awk -F- '{print $NF}' )"
    if [ -z "${_ver}" ] ; then
        ERROR "Failed to retrieve ${APP} binary release info !"
        break
    else
        QB_URL="https://github.com/userdocs/qbittorrent-nox-static/releases/download/release-${_ver}/x86_64-qbittorrent-nox"
        INFO "${APP} binary release URL: ${QB_URL}"
    fi
    if [ -z "${QB_URL}" ] ; then
        ERROR "Failed to parse ${APP} binary release URL !"
        break
    fi
    WGET "${QB_URL}" "${APP_HOME}/qbittorrent-nox" || break
    CHMOD_FILE 0755 "${APP_HOME}/qbittorrent-nox" || break
    echo "${_ver}" > "${APP_HOME}/version.id"

    # Restart services
    systemctl is-enabled "qbittorrent-static@${USERNAME}" > /dev/null 2>&1 \
        && SVC_RESTART "qbittorrent-static@${USERNAME}"


    main_rc=0
    break

done


SCRIPTEXIT
