#!/bin/bash

SCRIPT_VER="2.0"

APP="ruTorrent (Latest)"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
#><#APP_CHECK_VER_CMD="if [ -e /var/www/rutorrent/version.id ] ; then cat /var/www/rutorrent/version.id ; else echo ; fi"
#><#APP_UPGRADE_VER_CMD="curl -Ls -m 30 -o /dev/null -w "%{url_effective}" https://github.com/Novik/ruTorrent/releases/latest | awk -F/ "{print \$NF}" | tr -d "v""
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
DAEMON_PORT=5000
USE_APACHE2="yes"
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="/var/www/rutorrent"
APP_LEGACY_DIRECTORY="/var/www/rutorrent4"
APP_SESSION_DIRECTORY="/var/www/session"
RTORRENT_PPA="ppa:rapidseedbox/ppa"
RUTORRENT_REPO="Novik/ruTorrent"

while : ; do

    main_rc=1

    CHECK_APP ; _rc=$?
    if [ ${_rc} -ne 0 ] \
       && [ ! -d "${APP_DIRECTORY}" ] \
       && [ ! -d "${APP_LEGACY_DIRECTORY}" ]
    then
        main_rc=${_rc}
        break
    fi

    if [ "${USERUID}" != "${FIRST_UID}" ] ; then
        ERROR "Cannot upgrade this application for the user account '${USERNAME}'"
        break
    fi

    APT_INSTALL \
        "software-properties-common" \
        "apache2" \
        "apache2-utils" \
        "php" \
        "libapache2-mod-php" \
        "php-xml" \
        "php-xmlrpc" \
        "php-mbstring" \
        "php-curl" \
        "git-core" \
        "ffmpeg" \
        "mediainfo" \
        "bzip2" \
        "zip" \
        "sox" \
        "p7zip-full" \
        "unrar-free" \
        "curl" \
        "jq" \
        "screen" \
      || break

    if ! ADD_APT_PPA "${RTORRENT_PPA}" ; then
        WARN "Failed to add '${RTORRENT_PPA}'. Will continue with currently configured APT sources."
    fi

    APT_UPDATE || break
    APT_INSTALL "rtorrent" || break

    if [ ! -e "/etc/systemd/system/rtorrent@.service" ] \
       || ! grep -q -e '^ExecStart=.*\s*/usr/bin/rtorrent' "/etc/systemd/system/rtorrent@.service" > /dev/null 2>&1
    then
        cat <<-EOUNIT > "/etc/systemd/system/rtorrent@.service"
	[Unit]
	Description=rTorrent
	After=network.target

	[Service]
	Type=forking
	User=%i
	Group=%i
	KillMode=none
	ExecStartPre=-/bin/rm -f ${APP_SESSION_DIRECTORY}/%i/rtorrent.pid
	ExecStartPre=-/bin/rm -f ${APP_SESSION_DIRECTORY}/%i/rtorrent.lock
	ExecStart=/usr/bin/screen -d -m -fa -S rtorrent-%i /usr/bin/rtorrent
	ExecStartPost=/bin/sh -c "echo \$MAINPID > ${APP_SESSION_DIRECTORY}/%i/rtorrent.pid"
	ExecStop=/usr/bin/screen -S rtorrent-%i -X quit
	Restart=always

	[Install]
	WantedBy=multi-user.target
	EOUNIT

        [ -d "/etc/systemd/system/rtorrent@.service.d" ] \
            || MKDIR "/etc/systemd/system/rtorrent@.service.d" || break

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

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

        cat <<-EOFCONF > "/etc/systemd/system/rtorrent@.service.d/17-LimitNOFILE.conf"
	[Service]
	LimitNOFILE=4000
	EOFCONF

        SYSTEMD_RELOAD || break
    fi

    _users_tmp="${TMP_DIR}/rutorrent-users"
    mkdir -p "${_users_tmp}" >> "${LOGFILE}" 2>&1 || break
    for _src in "${APP_LEGACY_DIRECTORY}" "${APP_DIRECTORY}" ; do
        [ -d "${_src}/conf/users" ] || continue
        while read -r _cfg_dir ; do
            [ -d "${_cfg_dir}" ] || continue
            _cfg_user="$( basename "${_cfg_dir}" )"
            [ -d "${_users_tmp}/${_cfg_user}" ] && continue
            cp -a "${_cfg_dir}" "${_users_tmp}/" >> "${LOGFILE}" 2>&1 || break 2
        done < <( find "${_src}/conf/users" -mindepth 1 -maxdepth 1 -type d | sort )
    done

    GITHUB_RELEASE "${RUTORRENT_REPO}" "latest" || break
    RUTORRENT_TAG="${GITHUB_RELEASE_TAG}"
    RUTORRENT_VERSION="${RUTORRENT_TAG#v}"
    [ -n "${RUTORRENT_VERSION}" ] || break

    WGET "https://github.com/${RUTORRENT_REPO}/archive/refs/tags/${RUTORRENT_TAG}.tar.gz" \
         "${TMP_DIR}/rutorrent.tar.gz" \
      || break
    TAR_ZXF "${TMP_DIR}/rutorrent.tar.gz" "${TMP_DIR}/" || break

    _stage_src="$( find "${TMP_DIR}" -maxdepth 1 -type d -name 'ruTorrent-*' | sort | head -1 )"
    [ -n "${_stage_src}" ] || break
    _stage_dir="${TMP_DIR}/rutorrent-stage"
    mv "${_stage_src}" "${_stage_dir}" >> "${LOGFILE}" 2>&1 || break

    rm -rf "${_stage_dir}/plugins/filemanager" >> "${LOGFILE}" 2>&1
    if GIT_CLONE "https://github.com/nelu/rutorrent-filemanager" "${TMP_DIR}/rutorrent-filemanager" ; then
        cp -a "${TMP_DIR}/rutorrent-filemanager" "${_stage_dir}/plugins/filemanager" >> "${LOGFILE}" 2>&1 || break
        rm -rf "${_stage_dir}/plugins/filemanager/.git" >> "${LOGFILE}" 2>&1
    fi

    [ -e "${_stage_dir}/plugins/filemanager/init.js" ] \
        && RUN_LOG "sed -i -e 's|^\\(.*showhidden:\\).*,.*$|\\1 false,|' '${_stage_dir}/plugins/filemanager/init.js' 2>&1"
    [ -e "${_stage_dir}/plugins/screenshots/ffmpeg.php" ] \
        && RUN_LOG "sed -i -e \"s|'exfrmcount'=>.*,|'exfrmcount'=>10,|\" '${_stage_dir}/plugins/screenshots/ffmpeg.php' 2>&1"
    [ -e "${_stage_dir}/plugins/screenshots/ffmpeg.php" ] \
        && RUN_LOG "sed -i -e \"s|'exfrminterval'=>.*,|'exfrminterval'=>90,|\" '${_stage_dir}/plugins/screenshots/ffmpeg.php' 2>&1"
    [ -d "${_stage_dir}/plugins/_cloudflare" ] \
        && RM_DIRS "${_stage_dir}/plugins/_cloudflare"

    echo "${RUTORRENT_VERSION}" > "${_stage_dir}/version.id"

    _backup_dir="${APP_DIRECTORY}.bak.${SCRIPT_VER}.$$"
    [ -d "${APP_DIRECTORY}" ] && mv "${APP_DIRECTORY}" "${_backup_dir}" >> "${LOGFILE}" 2>&1 || true
    mv "${_stage_dir}" "${APP_DIRECTORY}" >> "${LOGFILE}" 2>&1 || break

    [ -d "${APP_DIRECTORY}/conf/users" ] || MKDIR "${APP_DIRECTORY}/conf/users" || break
    while read -r _cfg_dir ; do
        [ -d "${_cfg_dir}" ] || continue
        _cfg_user="$( basename "${_cfg_dir}" )"
        rm -rf "${APP_DIRECTORY}/conf/users/${_cfg_user}" >> "${LOGFILE}" 2>&1
        cp -a "${_cfg_dir}" "${APP_DIRECTORY}/conf/users/" >> "${LOGFILE}" 2>&1 || break
    done < <( find "${_users_tmp}" -mindepth 1 -maxdepth 1 -type d | sort )

    [ -d "${APP_SESSION_DIRECTORY}" ] || MKDIR "${APP_SESSION_DIRECTORY}" || break
    CHOWN_DIR "${APACHE_USER}:${APACHE_GROUP}" "${APP_SESSION_DIRECTORY}" || break
    CHMOD_FILE 775 "${APP_SESSION_DIRECTORY}" || break
    [ -d "/etc/apache2/userconf-enabled" ] || MKDIR "/etc/apache2/userconf-enabled" || break

    _htpasswd_flags="-c"
    while read -r _cfg_dir ; do
        [ -d "${_cfg_dir}" ] || continue
        _cfg_user="$( basename "${_cfg_dir}" )"
        id "${_cfg_user}" > /dev/null 2>&1 || continue
        _cfg_uid="$( id -u "${_cfg_user}" )"
        _cfg_home="$( getent passwd "${_cfg_user}" | awk -F: '{print $6}' )"
        [ -n "${_cfg_home}" ] || _cfg_home="/home/${_cfg_user}"
        _cfg_scgi_port="$(( _cfg_uid + 5000 - FIRST_UID ))"
        _cfg_password_store="${PASSWORDS_STORE_DIR}/${_cfg_user}"
        _cfg_password="$( awk -F: '$1 == "userdir" {print $2}' "${_cfg_password_store}" 2> /dev/null )"
        [ -n "${_cfg_password}" ] \
            || _cfg_password="$( awk -F: '$1 == "user" {print $2}' "${_cfg_password_store}" 2> /dev/null )"
        [ -n "${_cfg_password}" ] || [ "${_cfg_user}" != "${USERNAME}" ] || _cfg_password="${USERPASSWORD}"

        if [ -n "${_cfg_password}" ] ; then
            RUN_LOG "echo '${_cfg_password}' | htpasswd -i ${_htpasswd_flags} '${APP_DIRECTORY}/.htpasswd' '${_cfg_user}' 2>&1"
            _htpasswd_flags=""
        fi

        [ -d "${APP_SESSION_DIRECTORY}/${_cfg_user}" ] \
            || MKDIR "${APP_SESSION_DIRECTORY}/${_cfg_user}" || break
        CHOWN_DIR "${APACHE_USER}:${APACHE_GROUP}" "${APP_SESSION_DIRECTORY}/${_cfg_user}" || break
        CHMOD_FILE 775 "${APP_SESSION_DIRECTORY}/${_cfg_user}" || break

        cat <<-EOFCFG > "${APP_DIRECTORY}/conf/users/${_cfg_user}/config.php"
	<?php

	  \$topDirectory = '${_cfg_home}/';
	  \$XMLRPCMountPoint = '/RPC2_${_cfg_user}';
	  \$scgi_port = ${_cfg_scgi_port};
	  \$do_diagnostic = false;
	  \$al_diagnostic = false;
	EOFCFG

        cat <<-EOFRPC > "/etc/apache2/userconf-enabled/rtorrentscgi-${_cfg_user}.conf"
	<Location "/RPC2_${_cfg_user}">
	    AuthType Digest
	    AuthName "apache2"
	    AuthUserFile /etc/apache2/users.password
	    Require user ${_cfg_user}
	</Location>
	ProxyPass "/RPC2_${_cfg_user}" "scgi://127.0.0.1:${_cfg_scgi_port}"
	EOFRPC

        RM_FILES "/etc/apache2/sites-available/rtorrentscgi-${_cfg_user}.conf" \
                 "/etc/apache2/sites-enabled/rtorrentscgi-${_cfg_user}.conf" \
                 "/etc/apache2/passwords-available/rtorrentscgi-${_cfg_user}.conf" \
                 "/etc/apache2/passwords-enabled/rtorrentscgi-${_cfg_user}.conf" \
                 "/etc/apache2/userconf-enabled/rutorrent-${_cfg_user}.conf"
    done < <( find "${APP_DIRECTORY}/conf/users" -mindepth 1 -maxdepth 1 -type d | sort )

    cat <<-EOFAPACHE > "/etc/apache2/userconf-enabled/rutorrent-user.conf"
	RewriteEngine on
	RewriteRule ^/rutorrent$ /rutorrent/ [R=permanent]
	RewriteRule ^/rutorrent-user$ /rutorrent/ [R=permanent]
	RewriteRule ^/rutorrent-user/(.*)$ /rutorrent/\$1 [R=permanent]
	RewriteRule ^/rutorrent4$ /rutorrent/ [R=permanent]
	RewriteRule ^/rutorrent4/(.*)$ /rutorrent/\$1 [R=permanent]

	Alias /rutorrent /var/www/rutorrent
	<Directory /var/www/rutorrent>
	    Options +Indexes
	    AllowOverride None
	    AuthType Digest
	    AuthName "apache2"
	    AuthUserFile /etc/apache2/users.password
	    Require valid-user
	</Directory>
	EOFAPACHE

    RM_FILES "/etc/apache2/userconf-enabled/rutorrent4-user.conf" \
             "/etc/apache2/sites-available/rutorrent-8080.conf" \
             "/etc/apache2/sites-enabled/rutorrent-8080.conf" \
             "/etc/apache2/sites-available/rutorrent.conf" \
             "/etc/apache2/sites-enabled/rutorrent.conf"

    RUN_LOG "a2enmod proxy 2>&1"
    RUN_LOG "a2enmod proxy_http 2>&1"
    RUN_LOG "a2enmod proxy_scgi 2>&1"
    RUN_LOG "a2enmod headers 2>&1"
    RUN_LOG "a2enmod rewrite 2>&1"

    CHOWN_DIR "${APACHE_USER}:${APACHE_GROUP}" "${APP_DIRECTORY}" || break
    RUN_LOG "find '${APP_DIRECTORY}' -type d -exec chmod 0755 {} \\; 2>&1"

    SVC_RESTART "${APACHE_SVC}" || break

    while read -r _dir ; do
        [ -z "${_dir}" ] && continue
        _user="$( basename "${_dir}" )"
        systemctl is-active "rtorrent@${_user}" > /dev/null 2>&1 \
            && SVC_RESTART "rtorrent@${_user}"
    done < <( find /home -mindepth 1 -maxdepth 1 -type d | sort )

    [ -d "${_backup_dir}" ] && RM_DIRS "${_backup_dir}"
    [ -d "${APP_LEGACY_DIRECTORY}" ] && RM_DIRS "${APP_LEGACY_DIRECTORY}"

    main_rc=0
    break

done


# Cleanup if error
if [ "${main_rc}" -ne 0 ] && [ "${main_rc}" -ne 111 ] && [ "${main_rc}" -ne 117 ] ; then
    ERROR "'${APP}': Upgrade failed."
fi

SCRIPTEXIT
