#!/bin/bash

SCRIPT_VER="1.10"

APP="ruTorrent (Legacy)"
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)"
STORED_PASSWORD_SERVICE="rutorrent"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.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_SESSION_DIRECTORY="/var/www/session"

while : ; do

    main_rc=1

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

    ADD_PKGS=""

    case "${LSB_VENDOR}" in

      "Debian"|"Ubuntu")
          case "${LSB_CODENAME}" in
            "stretch"|"buster")
                # Plowshare
                ADD_PKGS="${ADD_PKGS} plowshare"
                # PHP
                ADD_PKGS="${ADD_PKGS} php libapache2-mod-php php-xmlrpc php-geoip rar unrar"
                ;;
            "xenial")
                # Plowshare
                ADD_PKGS="${ADD_PKGS} plowshare"
                # PHP
                ADD_PKGS="${ADD_PKGS} php7.0 libapache2-mod-php7.0 php7.0-xml php7.0-xmlrpc php-mbstring php-geoip rar unrar"
                ;;
            "bionic")
                # 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"
                ;;
            *)
                ERROR "Unsupported ${LSB_VENDOR} release: ${LSB_RELEASE}"
                break
                ;;
          esac

          APT_UPDATE || break

          APT_INSTALL \
              "apache2" \
              "rtorrent" \
              "libapache2-mod-scgi" \
              "git-core" \
              "screen" \
              "ffmpeg" \
              "mediainfo" \
              "bzip2" \
              "zip" \
              "sox" \
              ${ADD_PKGS} \
            || break
          ;;
    esac

    if [ ! -d "${APP_DIRECTORY}" ] ; 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.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/killall -w -s 2 /usr/bin/rtorrent
	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
    fi

    # -----------------------------------
    # -- Modify '.rtorret.rc' 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 ))
    RPC_MOUNT_POINT="/RPC2_${USERNAME}"
    [ -e "${USERHOME}/.rtorrent.rc" ] \
        && RM_FILES "${USERHOME}/.rtorrent.rc"
    WGET \
        "${SUPPORT}/rutorrent/rtorrent.rc" \
        "${USERHOME}/.rtorrent.rc"
    if [ $? -eq 0 ] ; then
        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"
    fi
    CHOWN_FILE "${USERNAME}":"${USERNAME}" "${USERHOME}/.rtorrent.rc"

    # ----------------------------------
    # -- Install ruTorret UI          --
    # ----------------------------------
    WGET "${RSB_URL}/install_rutorrent_ui.inc.sh" || break
    . "${TMP_DIR}/install_rutorrent_ui.inc.sh"

    # ----------------------------------
    # enable service 'rtorrent@user'  --
    # ----------------------------------
    SVC_ENABLE "rtorrent@${USERNAME}"
    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 /var/www/session/${USERNAME}/rtorrent.lock
	/bin/rm -f /var/www/session/${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
#    RM_DIRS "${APP_DIRECTORY}"
fi

SCRIPTEXIT
