#!/bin/bash

SCRIPT_VER="1.8"

APP="RuTorrent"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="userdir"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
USE_APACHE2="yes"
DAEMON_PORT=5000
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/rutorrent4"
APP_SESSION_DIRECTORY="/var/www/session"
#RUTORRENT4_VERSION="4.0-beta3"
#RUTORRENT4_VERSION="4.0-stable"
#RUTORRENT4_VERSION="4.0.1-hotfix"

while : ; do

    main_rc=1

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

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

    ADD_PKGS=""
    INSTALL_PLOWSHARE_FROM_SOURCE=no

    case "${LSB_VENDOR}" in
      "Ubuntu")
          case "${LSB_CODENAME}" in
            "focal")
                # Plowshare, archivers
                ADD_PKGS="${ADD_PKGS} plowshare rar unrar"
                # PHP
                ADD_PKGS="${ADD_PKGS} php libapache2-mod-php php-xml php-xmlrpc php-mbstring php-geoip"
                ;;
            "jammy")
                # Plowshare, archivers
                ADD_PKGS="${ADD_PKGS} plowshare rar unrar"
                # PHP
                ADD_PKGS="${ADD_PKGS} php libapache2-mod-php php-xml php-xmlrpc php-mbstring"
                ;;
            "noble")
                # Archivers
                ADD_PKGS="${ADD_PKGS} rar unrar make"
                # PHP
                ADD_PKGS="${ADD_PKGS} php libapache2-mod-php php-xml php-xmlrpc php-mbstring"
                INSTALL_PLOWSHARE_FROM_SOURCE=yes
                ;;
            *)
                ERROR "Unsupported ${LSB_VENDOR} release: ${LSB_RELEASE}"
                break
                ;;
          esac

          ${PKG_UPDATE} || break

          ${PKG_INSTALL} \
              "git-core" \
              "ffmpeg" \
              "mediainfo" \
              "bzip2" \
              "zip" \
              "sox" \
              "p7zip-full" \
              "unrar-free" \
              ${ADD_PKGS} \
            || break

          if [ "${INSTALL_PLOWSHARE_FROM_SOURCE}" = yes ] ; then
              GIT_CLONE "https://github.com/mcrapet/plowshare" \
                        "${TMP_DIR}/plowshare" || break
              pushd "${TMP_DIR}/plowshare" > /dev/null 2>&1 || break
              RUN_LOG "make install" || break
              popd > /dev/null 2>&1 || break
          fi
          ;;
    esac

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

    _rt4_ver="$( curl -Ls -m 30 -o /dev/null -w "%{url_effective}" \
                          https://github.com/Novik/ruTorrent/releases/latest \
                     | awk -F/ "{print \$NF}" \
                     | sed -e "s/^.*-v//" -e "s/^v//" )"

    pushd "${APP_DIRECTORY}" > /dev/null 2>&1
    if [ ! -d "${APP_DIRECTORY}/.git" ] ; then
        RUN_LOG "git init 2>&1"
        RUN_LOG "git config --global user.email 'user@example.com' 2>&1"
        RUN_LOG "git config --global user.name 'Seedbox Admin' 2>&1"
        RUN_LOG "git config --global --add safe.directory '${APP_DIRECTORY}' 2>&1"
        RUN_LOG "git add . 2>&1"
        RUN_LOG "git commit -m 'RSB: initial commit' 2>&1"
        RUN_LOG "git clean -f 2>&1"
        RUN_LOG "git remote add origin 'https://github.com/Novik/ruTorrent' 2>&1"
    fi
    RUN_LOG "git fetch --all 2>&1"
    RUN_LOG "git reset --hard origin/master" || break
    RUN_LOG "git checkout tags/v${_rt4_ver} 2>&1"
    RUN_LOG "git fetch 2>&1"
    popd > /dev/null 2>&1

    RUN_LOG "sed -i -re 's/(\s*)version:\s*\".*\"(.*)$/\1version: \"${_rt4_ver}\"\2/' '${APP_DIRECTORY}/js/webui.js' 2>&1"
    echo "${_rt4_ver}" > "${APP_DIRECTORY}/version.id"


    # Install `rutorrent-filemanager*` plugin(s)
    for _p in "filemanager" ; do
        GIT_CLONE "https://github.com/nelu/rutorrent-${_p}" \
                  "${TMP_DIR}/rutorrent-${_p}"
        if [ $? -eq 0 ] ; then
            CP_DIR "${TMP_DIR}/rutorrent-${_p}" \
                   "${APP_DIRECTORY}/plugins/${_p}" || break
        fi
    done

    # -- Remove some plugins
    RM_DIRS "${APP_DIRECTORY}/plugins/_cloudflare"

    # -- Set rutorrent directory owner & permissions
    CHOWN_DIR "${APACHE_USER}":"${APACHE_GROUP}" "${APP_DIRECTORY}"
    RUN_LOG "find '${APP_DIRECTORY}' -type d -exec chmod 0755 {} \; 2>&1"

    # -- Configure session directory
    [ ! -e "${APP_SESSION_DIRECTORY}" ] \
        && MKDIR "${APP_SESSION_DIRECTORY}"
    CHOWN_DIR "${APACHE_USER}":"${APACHE_GROUP}" "${APP_SESSION_DIRECTORY}"
    CHMOD_FILE 775 "${APP_SESSION_DIRECTORY}"

    # -- Configure Apache (subdir URL)
    for _d in \
           "/etc/apache2/sites-available" \
           "/etc/apache2/sites-enabled" \
           "/etc/apache2/passwords-available" \
           "/etc/apache2/passwords-enabled" \
           "/etc/apache2/userconf-enabled"
    do
        [ -d "${_d}" ] || MKDIR "${_d}"
    done
    if [ ! -e "/etc/apache2/userconf-enabled/rutorrent4-user.conf" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/rutorrent4-user.conf"
	RewriteEngine on
	RewriteRule ^/rutorrent4$ /rutorrent4/ [R=permanent]

	# -- ruTorrent 4 URL
	Alias /rutorrent4 /var/www/rutorrent4
	<Directory /var/www/rutorrent4>
	    Options +Indexes
	    Order allow,deny
	    Allow from all
	    AuthType Digest
	    AuthName "apache2"
	    AuthUserFile /etc/apache2/users.password
	    Require user user
	</Directory>
	EOF
    fi

    RUN_LOG "usermod -a -G '${APACHE_GROUP}' '${USERNAME}' 2>&1"

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

    #
    # Modify settings
    #
    RTORRENT_SCGI_PORT="$(( USERUID + 5000 - FIRST_UID ))"
    RPC_MOUNT_POINT="/RPC2_${USERNAME}"
    #
    if [ ! -d "${APP_DIRECTORY}/conf/users/${USERNAME}" ] ; then
        MKDIR "${APP_DIRECTORY}/conf/users/${USERNAME}"
    fi
#    if [ $? -eq 0 ] ; then
        cat <<-EOF > "${APP_DIRECTORY}/conf/users/${USERNAME}/config.php"
	<?php   

	  \$topDirectory = '${USERHOME}/';           // Upper available directory. Absolute path with trail slash
	  \$XMLRPCMountPoint = "/RPC2_${USERNAME}";  // DO NOT DELETE THIS LINE!!! DO NOT COMMENT THIS LINE!!!
	  \$scgi_port = ${RTORRENT_SCGI_PORT};
	  \$do_diagnostic = false;
	  \$al_diagnostic = false;
	EOF
#    fi

    # restart service 'apache2'
    RUN_LOG "systemctl is-active '${APACHE_SVC}' 2>&1" \
        && SVC_RESTART "${APACHE_SVC}"


    main_rc=0
    break

done


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

SCRIPTEXIT
