#!/bin/bash

SCRIPT_VER="1.2"

APP="Transmission 4 Daemon"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="transmission"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=9101
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

#TR4_VERSION="4.0.0"

APP_DIRECTORY="${USERHOME}/.config/transmission4-daemon"

while : ; do

    main_rc=1

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


    [ -d "${USERHOME}" ] || 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

    APT_INSTALL \
        "cmake" \
        "libcurl4-openssl-dev" \
        "libssl-dev" \
      || break

    _tr4_ver="$( curl -Ls -m 30 -o /dev/null -w "%{url_effective}" \
                      https://github.com/transmission/transmission/releases/latest 2> /dev/null \
                   | awk -F/ "{print \$NF}" )"
    if [ -z "${_tr4_ver}" ] ; then
        ERROR "Can't retrieve new '${APP}' version info"
        break
    fi

    JOB_START "Building '${APP}'"

    [ ! -d "/usr/local/src" ] \
        && MKDIR "/usr/local/src"

    _src_dir="/usr/local/src/transmission4"

    if [ ! -d "${_src_dir}" ] ; then
#        RUN_LOG \
#            "git clone https://github.com/transmission/transmission ${_src_dir} --branch ${TR4_VERSION} 2>&1" \
#                || break
        RUN_LOG \
            "git clone https://github.com/transmission/transmission ${_src_dir} --branch ${_tr4_ver} 2>&1" \
                || break
        pushd "${_src_dir}" > /dev/null 2>&1
        # --
        RUN_LOG "git submodule update --init --recursive 2>&1" || break
        MKDIR "${_src_dir}/build"
        pushd "${_src_dir}/build" > /dev/null 2>&1
        # -- Use -DCMAKE_BUILD_TYPE=RelWithDebInfo to build optimized binary.
        RUN_LOG "cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo .. 2>&1" || break
        RUN_LOG "make 2>&1" || break
        RUN_LOG "make install 2>&1" || break
        popd > /dev/null 2>&1
        # --
        popd > /dev/null 2>&1
    else
        pushd "${_src_dir}/build" > /dev/null 2>&1
        RUN_LOG "make clean 2>&1" || break
        RUN_LOG "git submodule foreach --recursive git clean -xfd 2>&1" || break
        RUN_LOG "git pull --rebase --prune 2>&1" || break
        RUN_LOG "git submodule update --recursive 2>&1" || break
        # -- Use -DCMAKE_BUILD_TYPE=RelWithDebInfo to build optimized binary.
        RUN_LOG "cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo .. 2>&1" || break
        RUN_LOG "make 2>&1" || break
        RUN_LOG "make install 2>&1" || break
        popd > /dev/null 2>&1
    fi

    JOB_END "Building '${APP}'"


    JOB_START "Configuring '${APP}' environment"

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

    TRANSMISSION_DAEMON_PORT="$(( USERUID + 9101 - FIRST_UID ))"
    TRANSMISSION_PEER_PORT="$(( USERUID + 52413 - FIRST_UID ))"

    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": ${TRANSMISSION_PEER_PORT}, 
	    "pex-enabled": 1, 
	    "port-forwarding-enabled": 0, 
	    "rpc-authentication-required": false,
	    "rpc-password": "transmission", 
	    "rpc-port": ${TRANSMISSION_DAEMON_PORT},
	    "rpc-url": "/transmission4-${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": "/transmission4/",|g' | \
                sed -f - -i "${APP_DIRECTORY}/settings.json"
    fi

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

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

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

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

	[Install]
	WantedBy=multi-user.target
	EOF

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

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

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

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

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

		<Location /transmission4>
		   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/transmission4-daemon-${USERNAME}.conf" 2>> "${LOGFILE}"
		ProxyRequests on
		ProxyPreserveHost Off
		RewriteEngine on
		RewriteRule ^/transmission4-${USERNAME}[/]?\$ /transmission4-${USERNAME}/web/ [R=permanent]
		ProxyPass /transmission4-${USERNAME} http://127.0.0.1:${TRANSMISSION_DAEMON_PORT}/transmission4-${USERNAME}
		ProxyPassReverse /transmission4-${USERNAME} http://127.0.0.1:${TRANSMISSION_DAEMON_PORT}/transmission4-${USERNAME}

		<Location /transmission4-${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/transmission4-daemon@${USERNAME}" 2>> "${LOGFILE}"
		check process transmission4-daemon-${USERNAME} with pidfile ${APP_DIRECTORY}/transmission4-daemon.pid
		  start program = "/usr/sbin/service transmission4-daemon@${USERNAME} restart"
		  stop program  = "/usr/sbin/service transmission4-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
