#!/bin/bash

SCRIPT_VER="1.1"

APP="NZBHydra 2"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="userdir"
#><#APP_CHECK_VER_CMD="[ -e "/opt/nzbhydra2/version.id" ] && cat "/opt/nzbhydra2/version.id" || echo """
#><#APP_UPGRADE_VER_CMD="curl -Ls -m 30 -o /dev/null -w "%{url_effective}" https://github.com/theotherp/nzbhydra2/releases/latest | awk -F/ "{print \$NF}" | tr -d "v""
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04"
MEMORY_K_MIN="4000000"
USE_APACHE2="yes"
DAEMON_PORT="5076"
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

APP_DIRECTORY="${USERHOME}/.config/nzbhydra"
APP_HOME="/opt/nzbhydra2"

while : ; do

    main_rc=1 

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

    # -- Stop/disable running service instance
    systemctl is-active  "nzbhydra2@${USERNAME}" > /dev/null \
        && SVC_STOP    "nzbhydra2@${USERNAME}"
    systemctl is-enabled "nzbhydra2@${USERNAME}" > /dev/null \
        && SVC_DISABLE "nzbhydra2@${USERNAME}"

    # -- Remove application directory
    if [ -d "${APP_HOME}" ] ; then
        RM_DIRS "${APP_HOME}"
    fi

    # -- Remove instance configuration directory
    [ -d "${APP_DIRECTORY}" ] \
        && RM_DIRS "${APP_DIRECTORY}"

    # -- Configure SystemD service
    if [ -e "/etc/systemd/system/nzbhydra2@.service" ] ; then
        RM_FILES "/etc/systemd/system/nzbhydra2@.service"
        SYSTEMD_RELOAD
    fi


    # -- Configure Apache2 reverse proxy
    if [ -e "/etc/apache2/userconf-enabled/nzbhydra2-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/nzbhydra2-${USERNAME}.conf"
        # -- Reload `apache2` service
        systemctl is-active "apache2" > /dev/null \
            && SVC_RELOAD "apache2"
    fi


    main_rc=0 
    break

done


SCRIPTEXIT
