#!/bin/bash

SCRIPT_VER="1.4"

APP="rTorrent"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
CONFLICTS="ruTorrent (rtorrent 0.9.2)|ruTorrent (rtorrent 0.9.3)|ruTorrent (rtorrent 0.9.4)|ruTorrent (rtorrent 0.9.6)|ruTorrent (rtorrent 0.9.8)|ruTorrent (Latest)|rTorrent 0.9.8"
SUPPORTED_ON="CentOS7,CentOSStream8,Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,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"

while : ; do

    main_rc=1

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


    ${PKG_UPDATE} || break
    ${PKG_INSTALL} "rtorrent" "screen" || break

    if [ "${USERUID}" = "${FIRST_UID}" ] ; then
        # configure systemd service
        cat <<-EOF > /etc/systemd/system/rtorrent@.service 2>> "${LOGFILE}"
		[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
		EOF

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

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

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

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

        SYSTEMD_RELOAD
    fi

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

    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_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 ))"
    [ -e "${USERHOME}/.rtorrent.rc" ] \
       && RM_FILES "${USERHOME}/.rtorrent.rc"
    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"

    # enable service 'rtorrent@user'
    SVC_ENABLE "rtorrent@${USERNAME}"
    # start service 'rtorrent@user'
    SVC_START "rtorrent@${USERNAME}"

    # -- monit configs
    if [ -d "/etc/monit/conf.d" ] ; then
        cat <<-EOF > "/etc/monit/conf.d/rtorrent@${USERNAME}" 2>> "${LOGFILE}"
	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"
	EOF
        MKDIR "/etc/monit/scripts/start"
        cat <<-EOF > "/etc/monit/scripts/start/rtorrent@${USERNAME}.start" 2>> "${LOGFILE}"
	#!/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
	EOF
        MONIT_RELOAD
    fi


    main_rc=0
    break

done


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

SCRIPTEXIT
