#!/bin/bash

SCRIPT_VER="1.2"

APP="qBittorrent WebUI (Latest)"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="no"
#><#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

    [ -e "${APP_HOME}/qbittorrent-static" ] \
        && RM_FILES "${APP_HOME}/qbittorrent-static"
        
    if [ ! -x "${APP_HOME}/qbittorrent-nox" ] ; then
        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"
    fi

    INFO "Configuring '${APP}' environment"

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

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

    cat <<-EOF > "${APP_DIRECTORY}/config/qBittorrent.conf"
	[BitTorrent]
	Session\DefaultSavePath=${USERHOME}/Downloads

	[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}
	EOF

    cat <<-'EOF' > "/etc/systemd/system/qbittorrent-static@.service"
	[Unit]
	Description=qBittorrent service (Static)
	After=network.target

	[Service]
	Type=simple
	User=%I
	Group=%I
	UMask=0002
	Restart=on-failure
	PermissionsStartOnly=true
	ExecStart=/usr/local/qbittorrent-nox-static/qbittorrent-nox \
	               --profile=/home/%I/.config \
	               --configuration=static
	ExecStartPost=/bin/sh -c "echo $MAINPID > /home/%I/.config/qBittorrent_static/qbittorrent.pid"

	[Install]
	WantedBy=multi-user.target
	EOF

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

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

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

    SYSTEMD_RELOAD

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

    # Configure `apache2` service
    if [ -d "/etc/apache2/userconf-enabled/" ] ; then
        if [ "${USERUID}" = "${FIRST_UID}" ] ; then
            cat <<-EOF > "/etc/apache2/userconf-enabled/qbittorrent-static.conf"
		RewriteEngine on
		RewriteRule ^/qbittorrent-static$ /qbittorrent-static/ [R=permanent]
		ProxyRequests off
		<Location /qbittorrent-static/>
		   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 "apache2"
		   AuthDigestProvider file
		   AuthUserFile "/etc/apache2/users.password"
		   Require user ${USERNAME}
		</Location>
		EOF
        fi
        cat <<-EOF > "/etc/apache2/userconf-enabled/qbittorrent-static-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^/qbittorrent-static-${USERNAME}$ /qbittorrent-static-${USERNAME}/ [R=permanent]
	ProxyRequests off
	<Location /qbittorrent-static-${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 "apache2"
	   AuthDigestProvider file
	   AuthUserFile "/etc/apache2/users.password"
	   Require user ${USERNAME}
	</Location>
	EOF
        SVC_RELOAD "apache2"
    fi


    main_rc=0
    break

done


SCRIPTEXIT
