#!/bin/bash

SCRIPT_VER="1.1"

APP="rTorrent 0.9.8"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
CONFLICTS="rTorrent|rTorrent 0.9.2|rTorrent 0.9.3|rTorrent 0.9.4|rTorrent 0.9.6"
STORED_PASSWORD_SERVICE="rutorrent"
SUPPORTED_ON="CentOS7,Ubuntu16.04,Ubuntu18.04"
DAEMON_PORT=5000
USE_APACHE2="yes"
LIBRARY="functions4.sh"

RT_VER="0.9.8"
RT_S_VER="098"
LT_VER="0.13.8"

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


    case "${LSB_VENDOR}" in

      "CentOS")
          ${PKG_UPDATE} || break
          # Install CentOS build tools
          ${PKG_INSTALL} "gcc" "gcc-c++" "make" "kernel-headers" "pkgconfig" \
                      "file" "autoconf" "libtool" "m4" \
              || break
          # Install CentOS rtorrent build tools
          ${PKG_INSTALL} "libsigc++20-devel" "ncurses-devel" "openssl-devel" "cppunit-devel" \
                      "libcurl-devel" "curl-devel" "gettext-devel" "xmlrpc-c" "xmlrpc-c-devel" \
              || break
          ;;

      "Debian"|"Ubuntu")
          ${PKG_UPDATE} || break

          # Install build tools
          ${PKG_INSTALL} \
              "build-essential" \
              "autoconf" \
              "libtool" \
              "libcppunit-dev" \
              "libssl-dev" \
              "pkg-config" \
              "libncurses5-dev" \
              "libsigc++-2.0-dev" \
              "libcurl4-openssl-dev" \
              "libxml2-dev" \
              "libxmlrpc-core-c3" \
              "libxmlrpc-core-c3-dev" \
            || break

          # Run-time requirements
          ${PKG_INSTALL} \
              "screen" \
            || break
          ;;
    esac


    # Fetch & unpack sources
    WGET "${SUPPORT}/libtorrent/libtorrent-${LT_VER}.tar.gz" || break
    WGET "${SUPPORT}/rtorrent/rtorrent-${RT_VER}.tar.gz" || break
    TAR_ZXF "${TMP_DIR}/libtorrent-${LT_VER}.tar.gz" "${TMP_DIR}/" || break
    TAR_ZXF "${TMP_DIR}/rtorrent-${RT_VER}.tar.gz" "${TMP_DIR}/" || break
    #
    MKDIR "/usr/local/rt${RT_S_VER}/bin"     || break
    MKDIR "/usr/local/rt${RT_S_VER}/include" || break
    MKDIR "/usr/local/rt${RT_S_VER}/lib"     || break
    #
    oWD=$( pwd )
    #
    JOB_START "Build & Install libtorrent-${LT_VER}"
    cd "${TMP_DIR}/libtorrent-${LT_VER}"
    RUN_LOG "./autogen.sh" || break
    RUN_LOG "./configure --prefix=/usr/local/rt${RT_S_VER} --disable-silent-rules" || break
    RUN_LOG "make" || break
    RUN_LOG "make install" || break
    cat <<-EOF > "/etc/ld.so.conf.d/rt${RT_S_VER}.conf"
	# libtorrent ${LT_VER}
	/usr/local/rt${RT_S_VER}/lib
	EOF
    RUN_LOG "ldconfig -v" || break
    JOB_END "Build & Install libtorrent-${LT_VER}"
    #
    JOB_START "Build & Install rtorrent-${RT_VER}"
    cd "${TMP_DIR}/rtorrent-${RT_VER}"
    RUN_LOG "./autogen.sh" || break
    RUN_LOG "PKG_CONFIG_PATH=/usr/local/rt${RT_S_VER}/lib/pkgconfig \
                ./configure \
                   --prefix=/usr/local/rt${RT_S_VER} \
                   --disable-silent-rules \
                   --with-xmlrpc-c" \
        || break
    RUN_LOG "PKG_CONFIG_PATH=/usr/local/rt${RT_S_VER}/lib/pkgconfig make" || break
    RUN_LOG "PKG_CONFIG_PATH=/usr/local/rt${RT_S_VER}/lib/pkgconfig make install" || break
    JOB_END "Build & Install rtorrent-${RT_VER}"
    #
    cd "${oWD}"


    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/local/rt${RT_S_VER}/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
    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"
        RUN_LOG "echo 's|^scgi_port =.*\$|network.scgi.open_port = \"127.0.0.1:${RTORRENT_SCGI_PORT}\"|' | \
            sed -f - -i '${USERHOME}/.rtorrent.rc' 2>&1"
    fi
    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 [ -e "/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
fi

SCRIPTEXIT
