#!/bin/bash

SCRIPT_VER="1.5"

APP="Transmission Daemon"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
SYS_PKG_NAME="transmission-daemon"
STORED_PASSWORD_SERVICE="transmission"
SUPPORTED_ON="Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=9091
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}/.config/transmission-daemon"

while : ; do

    main_rc=1

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


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

    # -- Distribution specific configuration
    case "${LSB_VER}" in
      "Ubuntu16.04"|"Ubuntu18.04"|"Ubuntu20.04")
          ADD_APT_REPO "ppa:transmissionbt/ppa" || break
          APT_UPDATE || break
          ;;
      *)
          ;;
    esac

    APT_INSTALL \
        "transmission-cli" \
        "transmission-common" \
        "transmission-daemon" \
      || break

    SVC_STOP "transmission-daemon"
    SVC_DISABLE "transmission-daemon"
    SVC_MASK "transmission-daemon"
    if [ -e "/etc/systemd/system/multi-user.target.wants/transmission-daemon.service" ] ; then
        RM_FILES "/etc/systemd/system/multi-user.target.wants/transmission-daemon.service"
    fi
    SYSTEMD_RELOAD

    JOB_START "Configuring '${APP}' environment"

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

    for __d in "blocklists" "resume" "torrents" ; do
        if [ ! -d "${APP_DIRECTORY}/${__d}" ] ; then
            MKDIR "${APP_DIRECTORY}/${__d}" || break 2
        fi
    done

    TRANSMISSION_DAEMON_PORT="$(( USERUID + 9091 - FIRST_UID ))"
    TRANSMISSION_PEER_PORT="$(( USERUID + 51413 - FIRST_UID ))"
    if [ ! -d "/etc/skel/.config/transmission-daemon" ] ; then
        MKDIR "/etc/skel/.config/transmission-daemon" \
            || break
    fi
    for __d in "blocklists" "resume" "torrents" ; do
        if [ ! -d "/etc/skel/.config/${__d}" ] ; then
            MKDIR "/etc/skel/.config/${__d}" || break 2
        fi
    done
    cat <<-EOF > "/etc/skel/.config/transmission-daemon/settings.json"
	{
	    "blocklist-enabled": 0, 
	    "download-dir": "###USERHOME###/Downloads",
	    "download-limit": 100, 
	    "download-limit-enabled": 0, 
	    "encryption": 1, 
	    "max-peers-global": 200, 
	    "peer-port": ###TRANSMISSION_PEER_PORT###, 
	    "pex-enabled": 1, 
	    "port-forwarding-enabled": 0, 
	    "rpc-authentication-required": false,
	    "rpc-password": "transmission", 
	    "rpc-port": ###TRANSMISSION_DAEMON_PORT###,
	    "rpc-url": "/transmission-###USERNAME###/",
	    "rpc-username": "transmission", 
	    "rpc-whitelist": "127.0.0.1", 
	    "upload-limit": 100, 
	    "upload-limit-enabled": 0
	}
	EOF

    cat <<-EOF > "${APP_DIRECTORY}/settings.json"
	{
	    "blocklist-enabled": 0, 
	    "download-dir": "${USERHOME}/Downloads",
	    "download-limit": 100, 
	    "download-limit-enabled": 0, 
	    "encryption": 1, 
	    "max-peers-global": 200, 
	    "peer-port": 51413, 
	    "pex-enabled": 1, 
	    "port-forwarding-enabled": 0, 
	    "rpc-authentication-required": false,
	    "rpc-password": "transmission", 
	    "rpc-port": ${TRANSMISSION_DAEMON_PORT},
	    "rpc-url": "/transmission-${USERNAME}/",
	    "rpc-username": "transmission", 
	    "rpc-whitelist": "127.0.0.1", 
	    "upload-limit": 100, 
	    "upload-limit-enabled": 0
	}
	EOF
    if [ "${USERUID}" = "${FIRST_UID}" ] ; then
        echo 's|\(.*\)"rpc-url":.*|\1"rpc-url": "/transmission/",|g' | \
                sed -f - -i "${APP_DIRECTORY}/settings.json"
    fi

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

    MKDIR "/var/log/transmission/${USERNAME}" \
        && CHOWN_DIR "${USERNAME}":"${USERNAME}" "/var/log/transmission/${USERNAME}"

    # -- Configure services
    if [ ! -f "/etc/systemd/system/transmission-daemon@.service" ] ; then
        cat <<-EOF > "/etc/systemd/system/transmission-daemon@.service" 2>> "${LOGFILE}"
	[Unit]
	Description=Transmission BitTorrent Daemon
	After=network.target

	[Service]
	User=%I
	Group=%I
	Type=notify
	ExecStart=/usr/bin/transmission-daemon -f --log-error --config-dir /home/%I/.config/transmission-daemon --logfile /var/log/transmission/%I/daemon.log
	ExecStartPost=/bin/sh -c "echo \$MAINPID > /home/%I/.config/transmission-daemon/transmission-daemon.pid"
	ExecReload=/bin/kill -s HUP \$MAINPID

	[Install]
	WantedBy=multi-user.target
	EOF

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

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

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

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

    # -- Install Transmission Web Control
    if WGET "https://github.com/ronggang/twc-release/raw/master/src.tar.gz" ; then
        # -- Save original `index.html` copy:
        CP_FILE "/usr/share/transmission/web/index.html" \
                "/usr/share/transmission/web/index.original.html"
        TAR_ZXF "${TMP_DIR}/src.tar.gz" "/usr/share/transmission/web/"
    fi

    # -- Configure Apache
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        if [ "${USERUID}" = "${FIRST_UID}" ] ; then
            cat <<-EOF > "/etc/apache2/userconf-enabled/transmission-daemon-${USERNAME}.conf" 2>> "${LOGFILE}"
		ProxyRequests on
		ProxyPreserveHost Off
		RewriteEngine on
		RewriteRule ^/transmission[/]?\$ /transmission/web/ [R=permanent]
		ProxyPass /transmission http://127.0.0.1:${TRANSMISSION_DAEMON_PORT}/transmission
		ProxyPassReverse /transmission http://127.0.0.1:9091/transmission

		<Location /transmission>
		   Order Allow,Deny
		   Allow from All
		   AuthType Digest
		   AuthName "Transmission"
		   AuthDigestProvider file
		   AuthUserFile "/etc/apache2/transmission.users.password"
		   Require user ${USERNAME}
		</Location>


		EOF
        else
            cat <<-EOF > "/etc/apache2/userconf-enabled/transmission-daemon-${USERNAME}.conf" 2>> "${LOGFILE}"
		ProxyRequests on
		ProxyPreserveHost Off
		RewriteEngine on
		RewriteRule ^/transmission-${USERNAME}[/]?\$ /transmission-${USERNAME}/web/ [R=permanent]
		ProxyPass /transmission-${USERNAME} http://127.0.0.1:${TRANSMISSION_DAEMON_PORT}/transmission-${USERNAME}
		ProxyPassReverse /transmission-${USERNAME} http://127.0.0.1:${TRANSMISSION_DAEMON_PORT}/transmission-${USERNAME}

		<Location /transmission-${USERNAME}>
		   Order Allow,Deny
		   Allow from All
		   AuthType Digest
		   AuthName "Transmission"
		   AuthDigestProvider file
		   AuthUserFile "/etc/apache2/transmission.users.password"
		   Require user ${USERNAME}
		</Location>
		EOF
        fi
        SVC_RESTART "${APACHE_SVC}"
    fi

    passwd_file="/etc/apache2/transmission.users.password"
    pline="$( \
        ( echo -n "${USERNAME}:Transmission:" && echo -n "${USERNAME}:Transmission:${USERPASSWORD}" \
           | md5sum | awk '{print $1}' \
        ) \
      )"
    if [    -e "${passwd_file}" ] \
         && grep -q -e "^${USERNAME}:Transmission:" "${passwd_file}"
    then
        RUN_LOG "echo 's#^${USERNAME}:Transmission:.*#${pline}#' | \
                    sed -f - -i '${passwd_file}'"
    else
        echo "${pline}" >> "${passwd_file}"
    fi

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

    JOB_END "Configuring '${APP}' environment"


    main_rc=0
    break

done


SCRIPTEXIT
