#!/bin/bash

SCRIPT_VER="1.22"

APP="Deluge 2"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
SYS_PKG_NAME="deluged"
STORED_PASSWORD_SERVICE="deluge"
#><#APP_CHECK_VER_CMD="${PKG_VER} deluged"
CONFLICTS="Deluge 1.3.5|Deluge 1.3.6|Deluge 1.3.7|Deluge 1.3.8|Deluge 1.3.9|Deluge 1.3.10|Deluge 1.3.11|Deluge 1.3.12|Deluge 1.3.13|Deluge 1.3.14|Deluge (Latest)"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
USE_APACHE2="yes"
DAEMON_PORT=58846
LIBRARY="functions4.sh"

if [ "${SUPPORT-}" = '' ]; then
    SUPPORT="http://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

. "./${LIBRARY}"
SCRIPTENTRY

VALIDATE_USER

APP_DIRECTORY="${USERHOME}/.config/deluge"
DELUGE_HOME="/var/lib/deluge"
DELUGE_LOGDIR="/var/log/deluge"

while : ; do

    main_rc=1

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

    [ -d "${USERHOME}" ] || break

    case "${LSB_VENDOR}" in
      "CentOS")
          _app_bin_path="/usr/local/bin"
          PIP3_INSTALL "deluge" || break
          ;;
      "Ubuntu")
          _app_bin_path="/usr/bin"
          DEL_APT_REPO "ppa:deluge-team/develop"
          case "${LSB_VER}" in
            "Ubuntu16.04"|"Ubuntu18.04")
                for pkg in "deluged" "deluge-web" "deluge-console" "deluge-common" "python3-libtorrent"
                do
                    APT_REMOVE "${pkg}"
                done
                APT_AUTOREMOVE
                ADD_APT_PPA "ppa:deluge-team/stable" || break
                ADD_APT_PPA "ppa:libtorrent.org/2.0-daily" || break
                APT_UPDATE || break
                APT_INSTALL \
                  "python3" \
                  "python3-pip" \
                  "python3-geoip" \
                  "python3-libtorrent" \
                  "deluged" \
                  "deluge-console" \
                  "deluge-web" \
                || break
                # --
                # https://forum.deluge-torrent.org/viewtopic.php?p=235002#p235002
                oPWD="$( pwd )"
                cd "/usr/lib/python3/dist-packages"
                RUN_LOG "ln -svf libtorrent.cpython-36dm-x86_64-linux-gnu.so libtorrent.so 2>&1"
                cd "${oPWD}"
                # --
                ;;
            "Ubuntu20.04"|"Ubuntu22.04")
                # Upgrade 'libtorrent' package
                ADD_APT_PPA "ppa:libtorrent.org/2.0-daily" || break
                ADD_APT_PPA "ppa:deluge-team/stable" || break
                APT_UPDATE || break
                APT_INSTALL \
                  "python3" \
                  "python3-pip" \
                  "python3-geoip" \
                  "python3-libtorrent" \
                  "deluged" \
                  "deluge-console" \
                  "deluge-web" \
                || break
                ;;
            "Ubuntu24.04")
                ADD_APT_PPA "ppa:deluge-team/stable" || break
                APT_UPDATE || break
                APT_INSTALL \
                  "python3" \
                  "python3-pip" \
                  "python3-geoip" \
                  "python3-libtorrent" \
                  "deluged" \
                  "deluge-console" \
                  "deluge-web" \
                || break
                ;;
            *)
                DEL_APT_REPO "ppa:deluge-team/stable"
                APT_UPDATE || break
                ;;
          esac
          APT_AUTOREMOVE || break
#          APT_INSTALL \
#              "python3" \
#              "python3-geoip" \
#              "python3-libtorrent" \
#              "deluged" \
#              "deluge-console" \
#              "deluge-web" \
#            || break
          ;;
      *)
          ERROR "${LSB_VENDOR}: Unsupported distribution!"
          main_rc=113
          break
          ;;
    esac


    # Disable/stop "stock" services
    SVC_DISABLE "deluged"
    SVC_STOP    "deluged"
    SVC_DISABLE "deluge-web"
    SVC_STOP    "deluge-web"

    # Upgrade `twisted`, `pyOpenSSL` & `cryptography`
    PIP3_INSTALL --upgrade "pip" || break
    PIP3_INSTALL --upgrade "pyOpenSSL twisted cryptography attrs" || break

    # Patch Deluge
    case "${LSB_VER}" in
      "Ubuntu20.04"|"Ubuntu22.04"|"Ubuntu24.04")
          cat <<-EOF > "${TMP_DIR}/deluge2_logging.patch"
		--- log.py.ORIG 2020-05-22 12:43:41.192986682 +0000
		+++ log.py      2020-05-22 12:44:17.701873007 +0000
		@@ -86,7 +86,7 @@
		     def exception(self, msg, *args, **kwargs):
		         yield LoggingLoggerClass.exception(self, msg, *args, **kwargs)

		-    def findCaller(self, stack_info=False):  # NOQA: N802
		+    def findCaller(self, *args, **kwargs):  # NOQA: N802
		         f = logging.currentframe().f_back
		         rv = '(unknown file)', 0, '(unknown function)'
		         while hasattr(f, 'f_code'):
		EOF
          RUN_LOG "patch -b -d /usr/lib/python3/dist-packages/deluge < '${TMP_DIR}/deluge2_logging.patch'"
#          RUN_LOG "patch -b -d /usr/lib/python3/dist-packages/deluge < '${TMP_DIR}/deluge2_logging.patch'" \
#              || break
#          RUN_LOG "pip3 install --upgrade twisted" \
#              || break
#          RUN_LOG "pip3 install --upgrade cryptography" \
#              || break
          ;;
    esac


    INFO "Configuring '${APP}' environment"

    if [ ! -d "${APP_DIRECTORY}" ] ; then
        MKDIR "${APP_DIRECTORY}" || break
    fi

    cat <<-EOF > "${APP_DIRECTORY}/changedelugepass.py"
	#!/usr/bin/env python3
	# Changes the password for Deluge's Web UI

	from deluge.config import Config
	import hashlib
	import os.path
	import sys

	if len(sys.argv) == 3:
	    deluge_dir = os.path.expanduser(sys.argv[1])
	    password = sys.argv[2]

	    if os.path.isdir(deluge_dir):
	        try:
	            config = Config("web.conf", config_dir=deluge_dir)
	        except IOError as e:
	            print ("Can't open web ui config file: " % e)
	        else:
	            salt = hashlib.sha1(os.urandom(32)).hexdigest()
	            s = hashlib.sha1(salt.encode('utf-8'))
	            s.update(password.encode('utf8'))
	            config['pwd_salt'] = salt
	            config['pwd_sha1'] = s.hexdigest()
	            try:
	                config.save()
	            except IOError as e:
	                print ("Couldn't save new password: " % e)
	            else:
	                print ("New password successfully set!")
	    else:
	        print ("%s is not a directory!" % deluge_dir)
	else:
	    print ("Usage: %s <deluge config dir>" % (os.path.basename(sys.argv[0])))
	EOF

    CHMOD_FILE 0755 "${APP_DIRECTORY}/changedelugepass.py"

    DELUGE_DAEMON_PORT="$(( USERUID + 58846 - FIRST_UID ))"
    DELUGE_WEBUI_PORT="$(( USERUID + 8112 - FIRST_UID ))"
    DELUGE_DAEMON_LISTEN_PORT_MIN="$(( USERUID - FIRST_UID ))"
    DELUGE_DAEMON_LISTEN_PORT_MIN="$(( DELUGE_DAEMON_LISTEN_PORT_MIN * 10 + 1 ))"
    DELUGE_DAEMON_LISTEN_PORT_MIN="$(( DELUGE_DAEMON_LISTEN_PORT_MIN + 6880 ))"
    DELUGE_DAEMON_LISTEN_PORT_MAX="$(( DELUGE_DAEMON_LISTEN_PORT_MIN + 10 ))"

    cat <<-EOF > "${APP_DIRECTORY}/core.conf"
	{
	    "file": 1,
	    "format": 1
	}{
	    "add_paused": false,
	    "allow_remote": true,
	    "auto_manage_prefer_seeds": false,
	    "auto_managed": true,
	    "cache_expiry": 60,
	    "cache_size": 512,
	    "copy_torrent_file": false,
	    "daemon_port": ${DELUGE_DAEMON_PORT},
	    "del_copy_torrent_file": false,
	    "dht": true,
	    "dont_count_slow_torrents": false,
	    "download_location": "${USERHOME}/Downloads",
	    "download_location_paths_list": [],
	    "enabled_plugins": [],
	    "enc_in_policy": 1,
	    "enc_level": 2,
	    "enc_out_policy": 1,
	    "geoip_db_location": "/usr/share/GeoIP/GeoIP.dat",
	    "ignore_limits_on_local_network": true,
	    "info_sent": 0.0,
	    "listen_interface": "",
	    "listen_ports": [
	        ${DELUGE_DAEMON_LISTEN_PORT_MIN},
	        ${DELUGE_DAEMON_LISTEN_PORT_MAX}
	    ],
	    "listen_random_port": 65156,
	    "listen_reuse_port": true,
	    "listen_use_sys_port": false,
	    "lsd": true,
	    "max_active_downloading": 3,
	    "max_active_limit": 8,
	    "max_active_seeding": 5,
	    "max_connections_global": 200,
	    "max_connections_per_second": 20,
	    "max_connections_per_torrent": -1,
	    "max_download_speed": -1.0,
	    "max_download_speed_per_torrent": -1,
	    "max_half_open_connections": 50,
	    "max_upload_slots_global": 4,
	    "max_upload_slots_per_torrent": -1,
	    "max_upload_speed": -1.0,
	    "max_upload_speed_per_torrent": -1,
	    "move_completed": false,
	    "move_completed_path": "${USERHOME}/Downloads",
	    "move_completed_paths_list": [],
	    "natpmp": true,
	    "new_release_check": false,
	    "outgoing_interface": "",
	    "outgoing_ports": [
	        0,
	        0
	    ],
	    "path_chooser_accelerator_string": "Tab",
	    "path_chooser_auto_complete_enabled": true,
	    "path_chooser_max_popup_rows": 20,
	    "path_chooser_show_chooser_button_on_localhost": true,
	    "path_chooser_show_hidden_files": false,
	    "peer_tos": "0x00",
	    "plugins_location": "${APP_DIRECTORY}/plugins",
	    "pre_allocate_storage": false,
	    "prioritize_first_last_pieces": false,
	    "proxy": {
	        "anonymous_mode": false,
	        "force_proxy": false,
	        "hostname": "",
	        "password": "",
	        "port": 8080,
	        "proxy_hostnames": true,
	        "proxy_peer_connections": true,
	        "proxy_tracker_connections": true,
	        "type": 0,
	        "username": ""
	    },
	    "queue_new_to_top": false,
	    "random_outgoing_ports": true,
	    "random_port": true,
	    "rate_limit_ip_overhead": true,
	    "remove_seed_at_ratio": false,
	    "seed_time_limit": 180,
	    "seed_time_ratio_limit": 7.0,
	    "send_info": false,
	    "sequential_download": false,
	    "share_ratio_limit": 2.0,
	    "shared": false,
	    "stop_seed_at_ratio": false,
	    "stop_seed_ratio": 2.0,
	    "super_seeding": false,
	    "torrentfiles_location": "${USERHOME}/Downloads",
	    "upnp": true,
	    "utpex": true
	}
	EOF

    cat <<-EOF > "${APP_DIRECTORY}/web.conf"
	{
	    "file": 2,
	    "format": 1
	}{
	    "base": "/",
	    "cert": "ssl/daemon.cert",
	    "default_daemon": "",
	    "enabled_plugins": [],
	    "first_login": false,
	    "https": false,
	    "interface": "127.0.0.1",
	    "language": "",
	    "pkey": "ssl/daemon.pkey",
	    "port": ${DELUGE_WEBUI_PORT},
	    "pwd_salt": "",
	    "pwd_sha1": "",
	    "session_timeout": 3600,
	    "show_session_speed": false,
	    "show_sidebar": true,
	    "sidebar_multiple_filters": true,
	    "sidebar_show_zero": false,
	    "theme": "gray"
	}
	EOF

    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}" || break

    MKDIR "/var/log/deluge/${USERNAME}" \
        && CHOWN_DIR "${USERNAME}":"${USERNAME}" "/var/log/deluge/${USERNAME}"
 
#    # Change user password
#    INFO "Changing Deluge password for \"${USERNAME}\"..."
#    RUN_LOG "'${APP_DIRECTORY}/changedelugepass.py' \
#                 '${APP_DIRECTORY}/' \
#                 '${USERPASSWORD}' 2>&1"

    # Configure services
    __log_level="info"
    [ "${DEBUG}" = "yes" ] && __log_level="debug"
#    if [ ! -f "/etc/systemd/system/deluged@.service" ] ; then
        cat <<-EOF > "/etc/systemd/system/deluged@.service" 2>> "${LOGFILE}"
	[Unit]
	Description=Deluge Bittorrent Client Daemon
	After=network.target

	[Service]
	Type=simple
	UMask=007
	User=%i
	Group=%i
	ExecStart=${_app_bin_path}/deluged -d -c /home/%i/.config/deluge -l /var/log/deluge/%i/daemon.log -L ${__log_level} --logrotate
	Restart=always
	TimeoutStopSec=300

	[Install]
	WantedBy=multi-user.target
	EOF

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

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

        cat <<-EOF > "/etc/systemd/system/deluged@.service.d/15-IOScheduling.conf"
	[Service]
	IOSchedulingClass=2
	IOSchedulingPriority=7
	EOF
#        SYSTEMD_RELOAD
#    fi
#    if [ ! -f "/etc/systemd/system/deluge-web@.service" ] ; then
        cat <<-EOF > "/etc/systemd/system/deluge-web@.service" 2>> "${LOGFILE}"
	[Unit]
	Description=Deluge Bittorrent Client Web Interface
	After=deluged.target

	[Service]
	Type=simple
	UMask=027
	User=%i
	Group=%i
	ExecStart=${_app_bin_path}/deluge-web -d -c /home/%i/.config/deluge -l /var/log/deluge/%i/web.log -L ${__log_level} --logrotate
	ExecStartPost=/bin/sh -c "echo \$MAINPID > /home/%i/.config/deluge/deluge-web.pid"
	Restart=always

	[Install]
	WantedBy=multi-user.target
	EOF
        SYSTEMD_RELOAD
#    fi
    
#    # enable/start services
#    for svc in "deluged" "deluge-web" ; do
#        SVC_ENABLE "${svc}@${USERNAME}"
#        SVC_START  "${svc}@${USERNAME}"
#    done

    SVC_ENABLE "deluged@${USERNAME}"
    SVC_START  "deluged@${USERNAME}"

    RUN_LOG "sleep 15"

#    _password="$( awk -F ":" '$1 == "localclient" {print $2}' "${APP_DIRECTORY}/auth" )"
#    cat <<-EOF > "${APP_DIRECTORY}/hostlist.conf"
#	{
#	    "file": 3,
#	    "format": 1
#	}{
#	    "hosts": [
#	        [
#	            "446259c4ce51443a8dd213cc0d211aee",
#	            "127.0.0.1",
#	            ${DELUGE_DAEMON_PORT},
#	            "localclient",
#	            "${_password}"
#	        ]
#	    ]
#	}
#	EOF

    SVC_ENABLE "deluge-web@${USERNAME}"
    SVC_START  "deluge-web@${USERNAME}"

#    # Change user password - We will change/restore the password in SCRIPTEXIT function :) 
#    INFO "Changing Deluge password for \"${USERNAME}\"..."
#    RUN_LOG "changeseedboxpass '${USERNAME}' deluge '${USERPASSWORD}' 2>&1"

    # Configure Apache
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        if [ "${USERUID}" = "${FIRST_UID}" ] ; then
            cat <<-EOF > "/etc/apache2/userconf-enabled/deluge-${USERNAME}.conf" 2>> "${LOGFILE}"
		<Location /deluge>
		ProxyPass http://127.0.0.1:${DELUGE_WEBUI_PORT}/
		ProxyPassReverse http://127.0.0.1:${DELUGE_WEBUI_PORT}/
		ProxyPassReverseCookieDomain 127.0.0.1 %{HTTP:Host}
		ProxyPassReverseCookiePath / /deluge/
		RequestHeader append X-Deluge-Base "/deluge/"
		</Location>
		EOF
        fi
        cat <<-EOF >> "/etc/apache2/userconf-enabled/deluge-${USERNAME}.conf" 2>> "${LOGFILE}"
		<Location /deluge-${USERNAME}>
		ProxyPass http://127.0.0.1:${DELUGE_WEBUI_PORT}/
		ProxyPassReverse http://127.0.0.1:${DELUGE_WEBUI_PORT}/
		ProxyPassReverseCookieDomain 127.0.0.1 %{HTTP:Host}
		ProxyPassReverseCookiePath / /deluge-${USERNAME}/
		RequestHeader append X-Deluge-Base "/deluge-${USERNAME}/"
		</Location>
		EOF
        SVC_RESTART "${APACHE_SVC}"
    fi

    #
    # -- monit configs
    if [ -d "/etc/monit/conf.d" ] ; then
         cat <<-EOF > "/etc/monit/conf.d/deluged@${USERNAME}" 2>> "${LOGFILE}"
		check process deluged-${USERNAME} with pidfile /home/${USERNAME}/.config/deluge/deluged.pid
		  start program = "/usr/sbin/service deluged@${USERNAME} restart"
		  stop program  = "/usr/sbin/service deluged@${USERNAME} stop"
		  if failed host localhost port ${DELUGE_DAEMON_PORT} type tcp then restart
		  if 5 restarts within 5 cycles then timeout
		EOF
         cat <<-EOF > "/etc/monit/conf.d/deluge-web@${USERNAME}" 2>> "${LOGFILE}"
		check process deluge-web-${USERNAME} with pidfile "${APP_DIRECTORY}/deluge-web.pid"
		  start program = "/usr/sbin/service deluge-web@${USERNAME} restart"
		  stop program  = "/usr/sbin/service deluge-web@${USERNAME} stop"
		  if failed host localhost port ${DELUGE_WEBUI_PORT} type tcp then restart
		  if 5 restarts within 5 cycles then timeout
		EOF
        MONIT_RELOAD
    fi


    main_rc=0
    break

done


SCRIPTEXIT
