#! /bin/bash
# Throttle rTorrent for a certain amount of time

#
# CONFIGURATION
#
timeout="now + 10 minutes" # default timeout
throttled=42 # throttled speed
unit=1024 # unit on command line, default KiB/s
queue=r

#
# HERE BE DRAGONS!
#
set -e
set +x

case "$1" in
    -h | --help)
        echo >&2 "Usage: $0 [«speed» [«timespec»]]"
        exit 1
        ;;
    *) : ;;
esac

if test -n "$(echo $1 | tr -d 0-9)"; then
    echo >&2 "ERROR: Non-numeric speed"
    exit 1
fi

if test -n "$1"; then
    throttled="$1"
    shift
fi
throttled=$(( $throttled * $unit ))

if test -n "$1"; then
    timeout="$@"
fi

if test -n "$(atq -q $queue)"; then
    # If there are jobs pending, run 1st one now, and then delete them
    at -c $(atq -q $queue | cut -f1 | head -n1) | /bin/sh
    atrm $(atq -q $queue | cut -f1)
fi

current=$(rtxmlrpc get_download_rate)

# Schedule new job to reset rate, and then throttle it
result=$(at -q $queue $timeout <<EOF 2>&1
rtxmlrpc -q set_download_rate $current
EOF
) || :
if [[ $result =~ .*(error|arbled).* ]]; then
    echo >&2 "ERROR: $result"
    exit 1
fi
echo $result | sed -re "s~warning: commands will be executed using /bin/sh~~"
rtxmlrpc -q set_download_rate $throttled

echo "Speed throttled to $(( $throttled / 1024 )) KiB/s, back to $(( $current / 1024 )) KiB/s at $timeout."

