#!/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 running service instance
    systemctl is-active "nzbhydra2@${USERNAME}" > /dev/null \
        && SVC_STOP "nzbhydra2@${USERNAME}"

    # -- Install NZBHydra 2
    if [ ! -e "${APP_HOME}/version.id" ] ; then
        if [ -d "${APP_HOME}" ] ; then
            RM_DIRS "${APP_HOME}"
        fi
        MKDIR "${APP_HOME}" || break
        INFO "Installing ${APP} into ${APP_HOME}"
        _ver="$( curl -Ls -m 30 -o /dev/null -w '%{url_effective}' \
                          https://github.com/theotherp/nzbhydra2/releases/latest \
                     | awk -F '/' '{print $NF}' | tr -d 'v' )"
        if [ -z "${_ver}" ] ; then
            ERROR "Failed to retrieve ${APP} release tarball URL !"
            break
        else
            APP_URL="https://github.com/theotherp/nzbhydra2/releases/download/v${_ver}/nzbhydra2-${_ver}-amd64-linux.zip"
            INFO "${APP} release tarball URL: ${APP_URL}"
        fi
        if [ -z "${APP_URL}" ] ; then
            ERROR "Failed to parse ${APP} release tarball URL !"
            break
        else
            APP_ARCHIVE=$( echo "${APP_URL}" | awk -F "/" '{print $NF}' )
            INFO "${APP} release tarball: ${APP_ARCHIVE}"
        fi
        WGET "${APP_URL}" || break
        UNZIP "${TMP_DIR}/${APP_ARCHIVE}" "${APP_HOME}/" || break
        echo "${_ver}" > "${APP_HOME}/version.id"
        CHOWN_DIR root:root "${APP_HOME}" || break
        CHMOD_FILE 0755 "${APP_HOME}/nzbhydra2" || break
        CHMOD_FILE 0755 "${APP_HOME}/nzbhydra2wrapper.py" || break
        CHMOD_FILE 0755 "${APP_HOME}/nzbhydra2wrapperPy3.py" || break
        CHMOD_FILE 0755 "${APP_HOME}/core" || break
    fi

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

    # -- Configure NZBHydra 2
    MKDIR "${APP_DIRECTORY}" || break
    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}" || break


    # -- Configure SystemD service
    cat <<-EOF > "/etc/systemd/system/nzbhydra2@.service"
	[Unit]
	Description=NZBHydra2 Daemon for %i
	Documentation=https://github.com/theotherp/nzbhydra2
	After=network.target

	[Service]
	# Create this user by running: adduser --system --group nzbhydra
	User=%i
	Group=%i
	Type=simple
	WorkingDirectory=/opt/nzbhydra2
	ExecStart=/opt/nzbhydra2/nzbhydra2wrapperPy3.py \\
	            --nobrowser \\
 	            --host 127.0.0.1 \\
	            --baseurl /nzbhydra \\
	            --datafolder /home/%i/.config/nzbhydra
	Restart=always

	[Install]
	WantedBy=multi-user.target
	EOF

    # -- Enable / start user's nzbhydra2 service instance
    SYSTEMD_RELOAD
    SVC_ENABLE  "nzbhydra2@${USERNAME}"
    SVC_RESTART "nzbhydra2@${USERNAME}"


    # -- Configure Apache2 reverse proxy
    APP_DAEMON_PORT="$(( USERUID + DAEMON_PORT - FIRST_UID ))"

    APP_BASEURL="nzbhydra"
    [ "${USERUID}" != "${FIRST_UID}" ] \
        && APP_BASEURL="${APP_BASEURL}-${USERNAME}"

    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/nzbhydra2-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^/nzbhydra$ /nzbhydra/ [R=permanent]
	ProxyRequests off
	<Location /nzbhydra/>
	   ProxyPreserveHost On
	   ProxyPass http://127.0.0.1:${APP_DAEMON_PORT}/nzbhydra/
	   ProxyPassReverse http://127.0.0.1:${APP_DAEMON_PORT}/nzbhydra/
	   AuthType Digest
	   AuthName "apache2"
	   AuthDigestProvider file
	   AuthUserFile "/etc/apache2/users.password"
	   Require user ${USERNAME}
	</Location>
	EOF
        # -- Reload `apache2` service
        systemctl is-active "apache2" > /dev/null \
            && SVC_RELOAD "apache2"
    fi


    main_rc=0 
    break

done


SCRIPTEXIT
