#!/bin/bash

SCRIPT_VER="1.2"

APP="uTorrent"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="no"
STORED_PASSWORD_SERVICE="utorrent"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.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_DIRECTORY="${USERHOME}/utorrent"

while : ; do

    main_rc=1

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

    APT_INSTALL "git-core" "unzip" "libssl-dev" || break
    # install 'python27'
    case "${LSB_VENDOR}" in
      "Debian" | "Ubuntu")
          APT_INSTALL "python2" || break
          ;;
    esac

    if [ ! -d "/opt/utorrent" ] ; then
        MKDIR "/opt/utorrent" || break

        # Install OpenSSL 1.0.0 library
        case "${LSB_VER}" in
          "Debian9")
              APT_INSTALL "build-essential" || break
              WGET "${SUPPORT}/openssl/OpenSSL_1_0_0r.tar.gz" \
                 && TAR_ZXF "${TMP_DIR}/OpenSSL_1_0_0r.tar.gz" "${TMP_DIR}/"
              if [ $? -eq 0 ] ; then
                  oWD=$( pwd )
                  cd "${TMP_DIR}/openssl-OpenSSL_1_0_0r"
                  RUN_LOG "./config shared 2>&1" || break
                  RUN_LOG "make 2>&1" || break
                  cd "${oWD}"
                  CP_FILE "${TMP_DIR}/openssl-OpenSSL_1_0_0r/libssl.so.1.0.0" "/opt/utorrent/" || break
                  CP_FILE "${TMP_DIR}/openssl-OpenSSL_1_0_0r/libcrypto.so.1.0.0" "/opt/utorrent/" || break
                  LD_PRE="LD_LIBRARY_PATH=/home/%i/utorrent "
              else
                  ERROR "Fatal error fetching and unpacking: OpenSSL_1_0_0r.tar.gz"
                  break
              fi
              ;;
          *)
              APT_INSTALL "libssl1.0.0" || break
              LD_PRE=""
              ;;
        esac

        lsb_vendor="${LSB_VENDOR,,}"
        UT_URL="${SUPPORT}/utserver/${lsb_vendor}/utserver.tar.gz"
        WGET "${UT_URL}" || break

        TAR_ZXF "${TMP_DIR}/utserver.tar.gz" "/opt/" || break

        CP_DIR "/opt/utorrent-server-alpha-v3_3/." "/opt/utorrent/" || break

        UNZIP "/opt/utorrent/webui.zip" "/opt/utorrent" || break

        RM_DIRS "/opt/utorrent-server-alpha-v3_3"

        CHMOD_FILE 777 "/opt/utorrent"

        MKDIR "/var/log/utorrent"

        GIT_CLONE "https://github.com/iocube/utwhisper" "/opt/utorrent/utwhisper"
        RM_DIRS "/opt/utorrent/utwhisper/.git"

        cat <<-EOF > "/opt/utorrent/utserver.conf" 2>> "${LOGFILE}"
	ut_webui_port: ###UTSERVER_WEBUI_PORT###
	dir_active: ###USERHOME###/Downloads
	dir_torrent_files: ###USERHOME###/Torrents
	ut_webui_dir: ###USERHOME###/utorrent

	# RSB custom settings
	localhost_authentication: false
	#prealloc_space: true
	#check_update: false
	#check_update_beta: false
	#anoninfo: false
	# /RSB custom settings
	logmask: 17
	EOF
        cat <<-EOF > "/opt/utorrent/utwhisper/settings.py" 2>> "${LOGFILE}"
	WEBUI = 'http://127.0.0.1:###UTSERVER_WEBUI_PORT###/gui/'
	USER = ''
	PASSWD = ''
	# location of token & cookie storage place for future reuse.
	AUTH_SAVE_PATH = "authreuse"
	EOF
        cat <<-EOF > "/etc/systemd/system/utserver@.service" 2>> "${LOGFILE}"
	[Unit]
	Description=uTorrent
	After=apache2.target

	[Service]
	ExecStart=/bin/sh -c '${LD_PRE}/home/%i/utorrent/utserver -settingspath /home/%i/utorrent/ -configfile /home/%i/utorrent/utserver.conf -logfile /var/log/utorrent/%i/utserver.log -pidfile /home/%i/utorrent/utserver.pid'
	ExecStop=/usr/bin/killall -w -s 2 utserver
	Type=simple
	User=%i
	Group=%i
	TimeoutSec=200
	KillMode=process
	Restart=always
	# -- Optimization -- #
	Nice=19
	IOSchedulingClass=2
	IOSchedulingPriority=7

	[Install]
	WantedBy=multi-user.target
	EOF
    fi

    INFO "Configuring utserver environment"

    UTSERVER_WEBUI_PORT="$(( USERUID + 8090 - FIRST_UID ))"
    UTSERVER_BIND_PORT="$(( USERUID + 6981 - FIRST_UID ))"

    CP_DIR "/opt/utorrent" "${USERHOME}"/

    RUN_LOG "echo \"s|###UTSERVER_WEBUI_PORT###|${UTSERVER_WEBUI_PORT}|g\" | \
        sed -f - -i '${APP_DIRECTORY}/utserver.conf' 2>&1"

    RUN_LOG "echo \"s|###UTSERVER_WEBUI_PORT###|${UTSERVER_WEBUI_PORT}|g\" | \
        sed -f - -i '${APP_DIRECTORY}/utwhisper/settings.py' 2>&1"

    RUN_LOG "echo \"s|###USERHOME###|${USERHOME}|g\" | \
        sed -f - -i '${APP_DIRECTORY}/utserver.conf' 2>&1"

    # --- Disable localhost authentication
    RUN_LOG "sed -e 's|^localhost_authentication:.*$|localhost_authentication: false|g' \
        -i '${APP_DIRECTORY}/utserver.conf' 2>&1"

    # ---
    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}"

    MKDIR "/var/log/utorrent/${USERNAME}"
    CHOWN_DIR "${USERNAME}":"${USERNAME}" "/var/log/utorrent/${USERNAME}"

    SVC_ENABLE "utserver@${USERNAME}" \
        && SVC_START "utserver@${USERNAME}"

    INFO "Post-processing: utserver"
    RUN_LOG "sleep 5"
    RUN_LOG "systemctl is-active 'utserver@${USERNAME}' 2>&1"
    if [ $? -eq 0 ] ; then

        utwhisper="python ${APP_DIRECTORY}/utwhisper/utwhisper.py"

        # Configure uTorrent server

        # 1. General settings
        RUN_LOG "${utwhisper} --setsettings prealloc_space=1 2>&1"
        RUN_LOG "${utwhisper} --setsettings check_update=0 2>&1"
        RUN_LOG "${utwhisper} --setsettings check_update_beta=0 2>&1"
        RUN_LOG "${utwhisper} --setsettings anoninfo=0 2>&1"

        # 2. Connection
        RUN_LOG "${utwhisper} --setsettings bind_port=${UTSERVER_BIND_PORT} 2>&1"

        # 3. Bandwidth
        RUN_LOG "${utwhisper} --setsettings conns_globally=2500 2>&1"
        RUN_LOG "${utwhisper} --setsettings conns_per_torrent=500 2>&1"
        RUN_LOG "${utwhisper} --setsettings ul_slots_per_torrent=100 2>&1"

        # 4. Bittorrent
        RUN_LOG "${utwhisper} --setsettings dht=0 2>&1"
        RUN_LOG "${utwhisper} --setsettings dht_per_torrent=0 2>&1"
        RUN_LOG "${utwhisper} --setsettings encryption_mode=1 2>&1"

        # 5. Queueing
        RUN_LOG "${utwhisper} --setsettings max_active_torrent=1000 2>&1"
        RUN_LOG "${utwhisper} --setsettings max_active_downloads=100 2>&1"

        # 6. Auth
        RUN_LOG "${utwhisper} --setsettings webui.username=${USERNAME} 2>&1"
        RUN_LOG "${utwhisper} --setsettings webui.password=${USERPASSWORD} 2>&1"

        # --- Save all current 'utserver' settings
        RUN_LOG "${utwhisper} --getsettings 2>&1"

        # --- Enable localhost authentication
        RUN_LOG "sed -e 's|^localhost_authentication:.*$|localhost_authentication: true|g' \
                     -i '${APP_DIRECTORY}/utserver.conf' 2>&1"

        # --- Cleanup
        RM_FILES "authreuse"

        # Restart service
        SVC_RESTART "utserver@${USERNAME}"

    fi

    # -- logrotate configs
    if [ -d "/etc/logrotate.d" ] ; then
        cat <<-EOF > "/etc/logrotate.d/utserver-${USERNAME}" 2>> "${LOGFILE}"
	/var/log/utorrent/${USERNAME}/utserver.log {
	    weekly
	    rotate 8
	    compress
	    delaycompress
	    dateext
	    missingok
	    size 10M
	    create 660 ${USERNAME} ${USERNAME}
	    postrotate
	        systemctl restart utserver@${USERNAME} 1>/dev/null
	    endscript
	    maxage 100
	}
	EOF
    fi

    # -- monit configs
    if [ -d "/etc/monit/conf.d" ] ; then
        cat <<-EOF > "/etc/monit/conf.d/utserver@${USERNAME}" 2>> "${LOGFILE}"
	check process utserver-${USERNAME} with pidfile ${APP_DIRECTORY}/utserver.pid
	  start program = "/usr/sbin/service utserver@${USERNAME} restart"
	  stop program = "/usr/sbin/service utserver@${USERNAME} stop"
	  if failed host localhost port ${UTSERVER_WEBUI_PORT} type tcp then 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}" "/opt/utorrent" "/var/log/utorrent/${USERNAME}"
fi

SCRIPTEXIT
