#!/bin/bash

#
# Name:         set-ratio
# Version:      2.0.0
#
# (c) 2025, Rapidseedbox, waleed@rapidseedbox.com
#

export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

SC_NAME="$( basename "${0}" )"
SC_VER="$( grep -m 1 -E '^#\s*Version:\s+' "${0}" | awk '{print $NF}' )"

_usage () {
    cat <<-EOF
	${SC_NAME} ${SC_VER}

	Usage:
	    ${SC_NAME} on | off

	EOF
    return 0
}

# -- Parse command line
case "${1,,}" in
  "-h"|"--help"|"help")
      _usage
      exit 0
      ;;
  "off"|"--off")
      CMD="OFF"
      ;;
  "on"|"--on")
      CMD="ON"
      ;;
  *)
      _usage
      exit 0
      ;;
esac

# User variables:
USERNAME="user"
if ! id "${USERNAME}" > /dev/null 2>&1 ; then
    >&2 echo "ERROR: '${USERNAME}': Account not found!"
    exit 1
fi

USERHOME="$( getent passwd "${USERNAME}" | awk -F':' '{print $6}' )"
if [ ! -d "${USERHOME}" ] ; then
    >&2 echo "ERROR: '${USERHOME}': Home directory not found!"
    exit 1
fi


# ------------------------------------
# -- Configure torrent clients ratio
# ------------------------------------
TORRENTS_RATIO="3"
OLD_TORRENTS_RATIO="10"

# ------------------------------------
# -- Deluge
# ------------------------------------
_cfg="${USERHOME}/.config/deluge/core.conf"
_cfg_dir="$( dirname "${_cfg}" )"
# --
if [ -e "${_cfg}" ] ; then
    if [[ -e "${_cfg_dir}/.rsb.set-ratio" ]] ; then
        old_deluge_ratio="$( cat "${_cfg_dir}/.rsb.set-ratio" )"
    else
        old_deluge_ratio="${OLD_TORRENTS_RATIO}"
    fi
    if grep -q -E '^\s*"stop_seed_ratio":\s*".*".*' "${_cfg}" > /dev/null 2>&1 ; then
        RM_FILES "${_cfg_dir}/.rsb.set-ratio"
    fi
    _stop_seed_at_ratio="$( jq -r 'select(.file == null).stop_seed_at_ratio' "${_cfg}" 2> /dev/null )"
    _stop_seed_ratio="$( jq -r 'select(.file == null).stop_seed_ratio' "${_cfg}" 2> /dev/null )"
    if [[ "${CMD}" = "OFF" && "${old_deluge_ratio}" != "x" ]] ; then
        if [[ "${_stop_seed_at_ratio}" != "false" && "${old_deluge_ratio}" == "${_stop_seed_ratio}" ]] ; then
            cp "${_cfg}" "${_cfg}".tmp > /dev/null 2>&1
            echo "INFO: Deluge: Setting stop_seed_at_ratio = false ..."
            if    jq 'select(.file == null).stop_seed_at_ratio = false' "${_cfg}".tmp \
                       > "${_cfg}".tmp1 2> /dev/null \
               && jq --arg ratio "${TORRENTS_RATIO}" \
                     'select(.file == null).stop_seed_ratio = ($ratio|tonumber)' "${_cfg}".tmp1 \
                       > "${_cfg}".tmp 2> /dev/null
            then
                _svc_restart="no"
                if systemctl is-active "deluged@${USERNAME}" > /dev/null 2>&1 ; then
                    echo "INFO: Deluge: Stopping the service ..."
                    systemctl stop "deluged@${USERNAME}"
                    _svc_restart="yes"
                fi
                cp -f "${_cfg}".tmp "${_cfg}"
                if [ "${_svc_restart}" = "yes" ] ; then
                    echo "INFO: Deluge: Restarting the service ..."
                    systemctl restart "deluged@${USERNAME}"
                fi
                rm -f "${_cfg}".tmp "${_cfg}".tmp1
            else
                >&2 echo "ERROR: Deluge: JQ error!"
            fi
            echo "-1" > "${_cfg_dir}/.rsb.set-ratio"
        elif [[ "${_stop_seed_at_ratio}" == "false" && "${old_deluge_ratio}" == "-1" ]] ; then
            echo "INFO: Deluge: Nothing to do ..."
            echo "-1" > "${_cfg_dir}/.rsb.set-ratio"
        else
            echo "INFO: Deluge: User enabled ratios. Will not modify."
            echo "x" > "${_cfg_dir}/.rsb.set-ratio"
        fi


    elif [[ "${CMD}" = "ON" && "${old_deluge_ratio}" != "x" ]] ; then
        if    [[ "${_stop_seed_at_ratio}" == "true" && "${old_deluge_ratio}" != "-1" \
              && "${_stop_seed_ratio}" == "${old_deluge_ratio}" && "${_stop_seed_ratio}" != "${TORRENTS_RATIO}" ]] \
           || [[ "${_stop_seed_at_ratio}" == "false" && "${old_deluge_ratio}" == "-1" ]] \
           || grep -q -E '^\s*"stop_seed_ratio":\s*".*".*' "${_cfg}" > /dev/null 2>&1
        then
            echo "INFO: Deluge: Setting stop_seed_at_ratio = true, stop_seed_ratio = ${TORRENTS_RATIO} ..."
            cp -f "${_cfg}" "${_cfg}".tmp
            if    jq 'select(.file == null).stop_seed_at_ratio = true' "${_cfg}".tmp \
                       > "${_cfg}".tmp1 2>&1 \
               && jq --arg ratio "${TORRENTS_RATIO}" \
                     'select(.file == null).stop_seed_ratio = ($ratio|tonumber)' "${_cfg}".tmp1 \
                       > "${_cfg}".tmp 2>&1
            then
                _svc_restart="no"
                if systemctl is-active "deluged@${USERNAME}" > /dev/null 2>&1 ; then
                    echo "INFO: Deluge: Stopping the service ..."
                    systemctl stop "deluged@${USERNAME}"
                    _svc_restart="yes"
                fi
                cp -f "${_cfg}".tmp "${_cfg}"
                if [ "${_svc_restart}" = "yes" ] ; then
                    echo "INFO: Deluge: Restarting the service ..."
                    systemctl restart "deluged@${USERNAME}"
                fi
                rm -f "${_cfg}".tmp "${_cfg}".tmp1
            else
                >&2 echo "ERROR: Deluge: JQ error!"
            fi
            echo "${TORRENTS_RATIO}" > "${_cfg_dir}/.rsb.set-ratio"
        elif [[ "${_stop_seed_at_ratio}" == "true" && "${old_deluge_ratio}" != "-1" \
              && "${_stop_seed_ratio}" == "${old_deluge_ratio}" && "${_stop_seed_ratio}" == "${TORRENTS_RATIO}" ]]; then
            echo "INFO: Deluge: Nothing to do ..."
            echo "${TORRENTS_RATIO}" > "${_cfg_dir}/.rsb.set-ratio"
        else 
            echo "INFO: Deluge: User modified ratios. Will not modify."
            echo "x" > "${_cfg_dir}/.rsb.set-ratio"
        fi
    fi
fi

# ------------------------------------
# -- qBittorrent
# ------------------------------------
_cfg="${USERHOME}/.config/qBittorrent/qBittorrent.conf"
_cfg_dir="$( dirname "${_cfg}" )"
# --
if [ -e "${_cfg}" ] && command -v "crudini" > /dev/null 2>&1 ; then
    if [[ -e "${_cfg_dir}/.rsb.set-ratio" ]] ; then
        old_qbit_ratio="$( cat "${_cfg_dir}/.rsb.set-ratio" )"
    else
        old_qbit_ratio="${OLD_TORRENTS_RATIO}"
    fi
    _s="$( crudini --get "${_cfg}" "Preferences" "Bittorrent\MaxRatio" 2> /dev/null )"
    if [[ "${CMD}" = "OFF" && "${old_qbit_ratio}" != "x" ]] ; then
        if [[ -n "${_s}" && "${_s}" == "${old_qbit_ratio}" ]] ; then
            echo "INFO: qBittorrent: Removing Preferences -> Bittorrent\MaxRatio ..."
            _svc_restart="no"
            if systemctl is-active "qbittorrent@${USERNAME}" > /dev/null 2>&1 ; then
                echo "INFO: qBittorrent: Stopping the service ..."
                systemctl stop "qbittorrent@${USERNAME}"
                _svc_restart="yes"
            fi
            crudini --del "${_cfg}" "Preferences" "Bittorrent\MaxRatio" 2> /dev/null
            if [ "${_svc_restart}" = "yes" ] ; then
                echo "INFO: qBittorrent: Restarting the service ..."
                systemctl restart "qbittorrent@${USERNAME}"
            fi
            echo "-1" > "${_cfg_dir}/.rsb.set-ratio"
        elif [[ ! -n "${_s}" && "${old_qbit_ratio}" == "-1" ]]; then
            echo "INFO: qBittorrent: Nothing to do ..."
            echo "-1" > "${_cfg_dir}/.rsb.set-ratio"
        else
            echo "INFO: qBittorrent: User modified ratios. Will not modify."
            echo "x" > "${_cfg_dir}/.rsb.set-ratio"
        fi
    elif [[ "${CMD}" = "ON" && "${old_qbit_ratio}" != "x" ]] ; then
        if [[ -z "${_s}" && "${old_qbit_ratio}" == "-1" ]] || \
           [[ "${old_qbit_ratio}" == "${_s}" && "${TORRENTS_RATIO}" != "${_s}" ]]; then
            echo "INFO: qBittorrent: Setting Preferences -> Bittorrent\MaxRatio = ${TORRENTS_RATIO} ..."
            _svc_restart="no"
            if systemctl is-active "qbittorrent@${USERNAME}" > /dev/null 2>&1 ; then
                echo "INFO: qBittorrent: Stopping the service ..."
                systemctl stop "qbittorrent@${USERNAME}"
                _svc_restart="yes"
            fi
            crudini --set "${_cfg}" \
                          "Preferences" \
                          "Bittorrent\MaxRatio" \
                          "${TORRENTS_RATIO}"
            sed -i -r -e 's/\s+=\s+/=/' "${_cfg}"
            if [ "${_svc_restart}" = "yes" ] ; then
                echo "INFO: qBittorrent: Restarting the service ..."
                systemctl restart "qbittorrent@${USERNAME}"
            fi
            echo "${TORRENTS_RATIO}" > "${_cfg_dir}/.rsb.set-ratio"
        elif [[ "${_s}" == "${TORRENTS_RATIO}" && "${_s}" == "${old_qbit_ratio}" ]]; then
            echo "INFO: qBittorrent: Nothing to do ..."
            echo "${TORRENTS_RATIO}" > "${_cfg_dir}/.rsb.set-ratio"
        else
            echo "INFO: qBittorrent: User modified ratios. Will not modify."
            echo "x" > "${_cfg_dir}/.rsb.set-ratio"
        fi
    fi
fi


# ------------------------------------
# -- rTorrent
# ------------------------------------
_cfg="${USERHOME}/.rtorrent.rc"
_cfg_dir="$( dirname "${_cfg}" )"
_ratio="$(( TORRENTS_RATIO * 100 ))"
# --


if [ -e "${_cfg}" ] ; then
    if [[ -e "${_cfg_dir}/.rsb.set-ratio" ]] ; then
        old_rtorrent_ratio="$( cat "${_cfg_dir}/.rsb.set-ratio" )"
    else
        old_rtorrent_ratio="$(( OLD_TORRENTS_RATIO * 100))"
    fi
    current_rtorrent_ratio="$(awk -F'=' '/^ratio.max.set=/ {print $2}' "${_cfg}" )"
    if [[ "${CMD}" = "OFF" && "${old_rtorrent_ratio}" != "x" ]] ; then
        _svc_reconfigure="no"
        for _s in \
            "ratio\.enable=.*"    \
            "ratio\.min\.set=.*"  \
            "ratio\.max\.set=.*"  \
            "method\.set = group\.seeding\.ratio.command, d\.stop=.*"
        do
            grep -q -E "^${_s}$" "${_cfg}" > /dev/null 2>&1 \
                && _svc_reconfigure="yes"
        done
        if [[ "${_svc_reconfigure}" = "yes" && "${old_rtorrent_ratio}" != "-1" ]] ; then
            _svc_restart="no"
            if systemctl is-active "rtorrent@${USERNAME}" > /dev/null 2>&1 ; then
                echo "INFO: rTorrent: Stopping the service ..."
                systemctl stop "rtorrent@${USERNAME}"
                _svc_restart="yes"
            fi
            sed -i -r \
                   -e '/^ratio\.enable/d' \
                   -e '/^ratio\.min\.set/d' \
                   -e '/^ratio\.max\.set/d' \
                   -e '/^method\.set = group\.seeding\.ratio.command/d' \
                   -e '/^# Default reasonable seed ratio/d' \
                "${_cfg}"
            if [ "${_svc_restart}" = "yes" ] ; then
                echo "INFO: rTorrent: Restarting the service ..."
                systemctl restart "rtorrent@${USERNAME}"
            fi
            echo "-100" > "${_cfg_dir}/.rsb.set-ratio"
        elif [[ "${_svc_reconfigure}" = "no" && "${old_rtorrent_ratio}" == "-100" ]] ; then
            echo "INFO: rTorrent: Nothing to do ..."
            echo "-100" > "${_cfg_dir}/.rsb.set-ratio"
        else
            echo "INFO: rTorrent: User modified ratios. Will not modify."
            echo "x" > "${_cfg_dir}/.rsb.set-ratio"
        fi
    elif [[ "${CMD}" = "ON" && "${old_rtorrent_ratio}" != "x" ]] ; then
        _svc_reconfigure="no"
        for _s in \
            "ratio\.enable=.*" \
            "ratio\.min\.set=.*" \
            "ratio\.max\.set=.*" \
            "method\.set = group\.seeding\.ratio.command, d\.stop=.*"
        do
            grep -q -E "^${_s}$" "${_cfg}" > /dev/null 2>&1 \
                || _svc_reconfigure="yes"
        done
        if    [[ "${_svc_reconfigure}" = "yes" && "${old_rtorrent_ratio}" == "-100" ]] \
           || [[ "${_svc_reconfigure}" = "no" && "${current_rtorrent_ratio}" == "${old_rtorrent_ratio}" \
                 && "${current_rtorrent_ratio}" != "${_ratio}" ]]; then
            echo "INFO: rTorrent: Setting ratio ..."
            sed -i -r \
                   -e '/^ratio\.enable/d' \
                   -e '/^ratio\.min\.set/d' \
                   -e '/^ratio\.max\.set/d' \
                   -e '/^method\.set = group\.seeding\.ratio.command/d' \
                   -e '/^# Default reasonable seed ratio/d' \
                "${_cfg}"
            _svc_restart="no"
            if systemctl is-active "rtorrent@${USERNAME}" > /dev/null 2>&1 ; then
                echo "INFO: rTorrent: Stopping the service ..."
                systemctl stop "rtorrent@${USERNAME}"
                _svc_restart="yes"
            fi
            cat <<-EOF >> "${_cfg}"

		# Default reasonable seed ratio
		ratio.enable=
		ratio.min.set=${_ratio}
		ratio.max.set=${_ratio}
		method.set = group.seeding.ratio.command, d.stop=
		EOF
            if [ "${_svc_restart}" = "yes" ] ; then
                echo "INFO: rTorrent: Restarting the service ..."
                systemctl restart "rtorrent@${USERNAME}"
            fi
            echo "${_ratio}" > "${_cfg_dir}/.rsb.set-ratio"
        elif [[ "${_svc_reconfigure}" = "no" && "${current_rtorrent_ratio}" == "${_ratio}" \
                && "${current_rtorrent_ratio}" == "${old_rtorrent_ratio}" ]]; then
            echo "INFO: rTorrent: Nothing to do ..."
            echo "${_ratio}" > "${_cfg_dir}/.rsb.set-ratio"
        else
            echo "INFO: rTorrent: User modified ratios. Will not modify."
            echo "x" > "${_cfg_dir}/.rsb.set-ratio"
        fi
    fi
    echo "${TORRENTS_RATIO}" > "${_cfg_dir}/.rsb.rtorrent.set-ratio"
fi


# ------------------------------------
# -- Transmission
# ------------------------------------
for _cfg in \
    "${USERHOME}/.config/transmission-daemon/settings.json"  \
    "${USERHOME}/.config/transmission4-daemon/settings.json"
do
    [ -e "${_cfg}" ] || continue
    command -v "jq" > /dev/null 2>&1 || continue
    _cfg_dir="$( dirname "${_cfg}" )"
    _svc="$( awk -F/ '{print $(NF-1)}' <<< "${_cfg}" )"
    _ratio_limit="$( jq -r '."ratio-limit"' "${_cfg}" 2> /dev/null )"
    _ratio_limit_enabled="$( jq '."ratio-limit-enabled"' "${_cfg}" 2> /dev/null )"
    if [[ -e "${_cfg_dir}/.rsb.set-ratio" ]] ; then
        old_transmission_ratio="$( cat "${_cfg_dir}/.rsb.set-ratio" )"
    else
        old_transmission_ratio="${OLD_TORRENTS_RATIO}"
    fi
    if [[ "${CMD}" = "OFF" && "${old_transmission_ratio}" != "x" ]] ; then
        if [[ "${_ratio_limit_enabled}" != "false" && "${old_transmission_ratio}" != "-1" ]] ; then
            echo "INFO: ${_svc}: Setting \"ratio-limit-enabled\" = false ..."
            cp -f "${_cfg}" "${_cfg}".tmp
            if    jq '."ratio-limit-enabled" = false' "${_cfg}".tmp > "${_cfg}".tmp1 \
               && jq --arg ratio "${TORRENTS_RATIO}" \
                     '."ratio-limit" = ($ratio|tonumber)' "${_cfg}".tmp1 > "${_cfg}".tmp
            then
                _svc_restart="no"
                if systemctl is-active "${_svc}@${USERNAME}" > /dev/null 2>&1 ; then
                    echo "INFO: ${_svc}: Stopping the service ..."
                    systemctl stop "${_svc}@${USERNAME}"
                    _svc_restart="yes"
                fi
                cp -f "${_cfg}".tmp "${_cfg}"
                if [ "${_svc_restart}" = "yes" ] ; then
                    echo "INFO: ${_svc}: Restarting the service ..."
                    systemctl restart "${_svc}@${USERNAME}"
                fi
                rm -f  "${_cfg}".tmp "${_cfg}".tmp1
            else
                >&2 echo "ERROR: ${_svc}: JQ error!"
            fi
            echo "-1" > "${_cfg_dir}/.rsb.set-ratio"
        elif [[ "${_ratio_limit_enabled}" == "false" && "${old_transmission_ratio}" == "-1" ]] ; then
            echo "INFO: ${_svc}: Nothing to do ..."
            echo "-1" > "${_cfg_dir}/.rsb.set-ratio"
        else
            echo "INFO: ${_svc}: User modified ratios. Will not modify."
            echo "x" > "${_cfg_dir}/.rsb.set-ratio"
        fi
    elif [[ "${CMD}" = "ON" && "${old_transmission_ratio}" != "x" ]] ; then
        if    [[ "${_ratio_limit_enabled}" != "true" && "${old_transmission_ratio}" == "-1" ]] \
           || [[ "${_ratio_limit}" != "${TORRENTS_RATIO}" && "${_ratio_limit}" == "${old_transmission_ratio}" \
                 && "${_ratio_limit_enabled}" == "true" ]] \
           || grep -q -E '^\s*"ratio-limit":\s*".*".*' "${_cfg}" > /dev/null 2>&1
        then
            echo "INFO: ${_svc}: Setting \"ratio-limit-enabled\" = true, \"ratio-limit\" = ${TORRENTS_RATIO} ..."
            cp -f "${_cfg}" "${_cfg}".tmp
            if    jq '."ratio-limit-enabled" = true' "${_cfg}".tmp > "${_cfg}".tmp1 \
               && jq --arg ratio "${TORRENTS_RATIO}" \
                     '."ratio-limit" = ($ratio|tonumber)' "${_cfg}".tmp1 > "${_cfg}".tmp
            then
                _svc_restart="no"
                if systemctl is-active "${_svc}@${USERNAME}" > /dev/null 2>&1 ; then
                    echo "INFO: ${_svc}: Stopping the service ..."
                    systemctl stop "${_svc}@${USERNAME}"
                    _svc_restart="yes"
                fi
                cp -f "${_cfg}".tmp "${_cfg}"
                if [ "${_svc_restart}" = "yes" ] ; then
                    echo "INFO: ${_svc}: Restarting the service ..."
                    systemctl restart "${_svc}@${USERNAME}"
                fi
                rm -f  "${_cfg}".tmp "${_cfg}".tmp1
            else
                >&2 echo "ERROR: ${_svc}: JQ error!"
            fi
            echo "${TORRENTS_RATIO}" > "${_cfg_dir}/.rsb.set-ratio"
        elif [[ "${_ratio_limit}" == "${TORRENTS_RATIO}" && "${_ratio_limit}" == "${old_transmission_ratio}" \
                && "${_ratio_limit_enabled}" == "true" ]]; then
            echo "INFO: ${_svc}: Nothing to do ..."
            echo "${TORRENTS_RATIO}" > "${_cfg_dir}/.rsb.set-ratio"
        else
            echo "INFO: ${_svc}: User modified ratios. Will not modify."
            echo "x" > "${_cfg_dir}/.rsb.set-ratio"
        fi
    fi
done


exit 0
