#!/bin/bash

SCRIPT_VER="1.12"

APP="qBittorrent WebUI"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
SYS_PKG_NAME="qbittorrent-nox"
#><#APP_CHECK_VER_CMD="${PKG_VER} qbittorrent-nox"
STORED_PASSWORD_SERVICE="qbittorrent"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
USE_APACHE2="yes"
DAEMON_PORT=18080
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"

while : ; do

    main_rc=1

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

    ADD_APT_PPA "ppa:rapidseedbox/ppa" || break
    ADD_APT_PPA "ppa:qbittorrent-team/qbittorrent-stable" || break
    APT_UPDATE || break

    APT_INSTALL "qbittorrent-nox" || break

    INFO "Configuring '${APP}' environment"

    if [ ! -d "${APP_DIRECTORY}" ] ; then
        MKDIR "${APP_DIRECTORY}" || break
    fi

    QB_DAEMON_PORT="$(( USERUID + 18080 - FIRST_UID ))"

    cat <<-EOD > "${APP_DIRECTORY}/qBittorrent.conf"
	[Preferences]
	WebUI\Address=127.0.0.1
	WebUI\AuthSubnetWhitelist=127.0.0.1/32
	WebUI\AuthSubnetWhitelistEnabled=true
	WebUI\HTTPS\Enabled=false
	WebUI\Password_ha1=@ByteArray($( echo -n "${USERPASSWORD}" | md5sum | awk '{print $1}' ))
	WebUI\Port=${QB_DAEMON_PORT}
	WebUI\Username=${USERNAME}
	EOD

    cat <<-'EOD' > "/etc/systemd/system/qbittorrent@.service"
	[Unit]
	Description=qBittorrent service
	After=network.target

	[Service]
	Type=forking
	User=%I
	Group=%I
	UMask=0002
	Restart=on-failure
	PermissionsStartOnly=true
	ExecStart=/usr/bin/qbittorrent-nox -d
	ExecStartPost=/bin/sh -c "echo $MAINPID > /home/%I/.config/qBittorrent/qbittorrent.pid"

	[Install]
	WantedBy=multi-user.target
	EOD

    [ ! -d "/etc/systemd/system/qbittorrent@.service.d" ] \
        && MKDIR "/etc/systemd/system/qbittorrent@.service.d"

    cat <<-EOD > "/etc/systemd/system/qbittorrent@.service.d/10-Nice.conf"
	[Service]
	Nice=19
	EOD

    cat <<-EOD > "/etc/systemd/system/qbittorrent@.service.d/15-IOScheduling.conf"
	[Service]
	IOSchedulingClass=2
	IOSchedulingPriority=7
	EOD

    SYSTEMD_RELOAD

    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}" || break
    
    # Enable/Start services
    SVC_ENABLE "qbittorrent@${USERNAME}"
    SVC_START  "qbittorrent@${USERNAME}"

    # Configure `apache2` service
    if [ -d "/etc/apache2/userconf-enabled/" ] ; then
        if [ "${USERUID}" = "${FIRST_UID}" ] ; then
            cat <<-EOD > "/etc/apache2/userconf-enabled/qbittorrent.conf"
		RewriteEngine on
		RewriteRule ^/qbittorrent$ /qbittorrent/ [R=permanent]
		ProxyRequests off
		<Location /qbittorrent/>
		   ProxyPreserveHost Off
		   RequestHeader unset Accept-Encoding
		   RequestHeader unset Referer
		   RequestHeader unset Origin
		   RequestHeader set Referer ""
		   RequestHeader set Origin ""
		   ProxyPass http://127.0.0.1:${QB_DAEMON_PORT}/
		   ProxyPassReverse http://127.0.0.1:${QB_DAEMON_PORT}/
		   Order Allow,Deny
		   Allow from All
		   AuthType Digest
		   AuthName "qBittorrent"
		   AuthDigestProvider file
		   AuthUserFile "/etc/apache2/qbittorrent.users.password"
		   Require user ${USERNAME}
		</Location>
		EOD
        fi
        cat <<-EOD > "/etc/apache2/userconf-enabled/qbittorrent-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^/qbittorrent-${USERNAME}$ /qbittorrent-${USERNAME}/ [R=permanent]
	ProxyRequests off
	<Location /qbittorrent-${USERNAME}/>
	   ProxyPreserveHost Off
	   RequestHeader unset Accept-Encoding
	   RequestHeader unset Referer
	   RequestHeader unset Origin
	   RequestHeader set Referer ""
	   RequestHeader set Origin ""
	   ProxyPass http://127.0.0.1:${QB_DAEMON_PORT}/
	   ProxyPassReverse http://127.0.0.1:${QB_DAEMON_PORT}/
	   Order Allow,Deny
	   Allow from All
	   AuthType Digest
	   AuthName "qBittorrent"
	   AuthDigestProvider file
	   AuthUserFile "/etc/apache2/qbittorrent.users.password"
	   Require user ${USERNAME}
	</Location>
	EOD
        SVC_RESTART "apache2"
    fi

    passwd_file="/etc/apache2/qbittorrent.users.password"
    pline=$( \
        ( echo -n "${USERNAME}:qBittorrent:" && echo -n "${USERNAME}:qBittorrent:${USERPASSWORD}" \
           | md5sum | awk '{print $1}' \
        ) \
      )
    if [ -e "${passwd_file}" ] ; then
        if grep -q -e "^${USERNAME}:qBittorrent:" "${passwd_file}" ; then
            RUN_LOG "echo 's#^${USERNAME}:qBittorrent:.*#${pline}#' | \
                        sed -f - -i '${passwd_file}'"
        else
            echo "${pline}" >> "${passwd_file}"
        fi
    else
        echo "${pline}" > "${passwd_file}"
    fi

    #
    # -- monit configs
    if [ -d "/etc/monit/conf.d" ] ; then
         cat <<-EOD > "/etc/monit/conf.d/qbittorrent@${USERNAME}" 2>> "${LOGFILE}"
		check process qbittorrent-${USERNAME} with pidfile /home/${USERNAME}/.config/qBittorrent/qbittorrent.pid
		  start program = "/usr/sbin/service qbittorrent@${USERNAME} restart"
		  stop program  = "/usr/sbin/service qbittorrent@${USERNAME} stop"
		  if failed host localhost port ${QB_DAEMON_PORT} type tcp then restart
		  if 5 restarts within 5 cycles then timeout
		EOD
        MONIT_RELOAD
    fi



    main_rc=0
    break

done


SCRIPTEXIT
