#!/bin/bash

SCRIPT_VER="2.0"

APP="rTorrent"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
#><#APP_CHECK_VER_CMD="${PKG_VER} rtorrent"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
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_SESSION_DIRECTORY="/var/www/session"
RTORRENT_PPA="ppa:rapidseedbox/ppa"

while : ; do

    main_rc=1

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

    APT_INSTALL "software-properties-common" || break
    if ! ADD_APT_PPA "${RTORRENT_PPA}" ; then
        WARN "Failed to add '${RTORRENT_PPA}'. Will continue with currently configured APT sources."
    fi

    ${PKG_UPDATE} || break
    ${PKG_INSTALL} "rtorrent" "screen" || 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

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

    INFO "Configuring rtorrent environment for '${USERNAME}'"
    RUN_LOG "usermod -a -G '${APACHE_GROUP}' '${USERNAME}' 2>&1"

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

    RTORRENT_PORT_MIN="$(( (USERUID - FIRST_UID)*100 + 33100 ))"
    RTORRENT_PORT_MAX="$(( RTORRENT_PORT_MIN + 99 ))"
    RTORRENT_DHT_PORT="$(( USERUID + 6881 - FIRST_UID ))"
    RTORRENT_SCGI_PORT="$(( USERUID + 5000 - FIRST_UID ))"

    if [ ! -e "${USERHOME}/.rtorrent.rc" ] ; then
        WGET "${SUPPORT}/rutorrent/rtorrent.rc" \
             "${USERHOME}/.rtorrent.rc" \
          || break

        RUN_LOG "echo 's|###USERHOME###|${USERHOME}|g' | sed -f - -i '${USERHOME}/.rtorrent.rc' 2>&1"
        RUN_LOG "echo 's|###RTORRENT_PORT_MIN###|${RTORRENT_PORT_MIN}|g' | sed -f - -i '${USERHOME}/.rtorrent.rc' 2>&1"
        RUN_LOG "echo 's|###RTORRENT_PORT_MAX###|${RTORRENT_PORT_MAX}|g' | sed -f - -i '${USERHOME}/.rtorrent.rc' 2>&1"
        RUN_LOG "echo 's|###RTORRENT_DHT_PORT###|${RTORRENT_DHT_PORT}|g' | sed -f - -i '${USERHOME}/.rtorrent.rc' 2>&1"
        RUN_LOG "echo 's|###RTORRENT_SCGI_PORT###|${RTORRENT_SCGI_PORT}|g' | sed -f - -i '${USERHOME}/.rtorrent.rc' 2>&1"
        RUN_LOG "echo 's|###RTORRENT_SESSION_PATH###|${APP_SESSION_DIRECTORY}/${USERNAME}|g' | sed -f - -i '${USERHOME}/.rtorrent.rc' 2>&1"
        CHOWN_FILE "${USERNAME}:${USERNAME}" "${USERHOME}/.rtorrent.rc" || break
    fi

    SVC_ENABLE "rtorrent@${USERNAME}" || break
    SVC_START  "rtorrent@${USERNAME}" || break

    if [ -d "/etc/monit/conf.d" ] ; then
        cat <<-EOFMONIT > "/etc/monit/conf.d/rtorrent@${USERNAME}"
	check process rtorrent-${USERNAME} with pidfile ${APP_SESSION_DIRECTORY}/${USERNAME}/rtorrent.pid
	  start program = "/bin/sh /etc/monit/scripts/start/rtorrent@${USERNAME}.start"
	  stop program  = "/usr/sbin/service rtorrent@${USERNAME} stop"
	EOFMONIT
        MKDIR "/etc/monit/scripts/start" || break
        cat <<-EOFMONIT > "/etc/monit/scripts/start/rtorrent@${USERNAME}.start"
	#!/bin/sh

	/bin/rm -f ${APP_SESSION_DIRECTORY}/${USERNAME}/rtorrent.lock
	/bin/rm -f ${APP_SESSION_DIRECTORY}/${USERNAME}/rtorrent.pid
	/usr/sbin/service rtorrent@${USERNAME} restart
	EOFMONIT
        CHMOD_FILE 755 "/etc/monit/scripts/start/rtorrent@${USERNAME}.start" || break
        MONIT_RELOAD || break
    fi

    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."
fi

SCRIPTEXIT
