Last active
June 24, 2016 11:36
-
-
Save dpoggi/db48f6f329ed6e366ad1 to your computer and use it in GitHub Desktop.
rtorrent ctl script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
c_reset="\033[0m" | |
c_date="\033[0;37m" | |
c_fatal="\033[1;37;41m" | |
log_msg() { | |
printf >&2 "${c_date}[%s]:${c_reset} " "$(date +"%H:%M:%S")" | |
if [[ "$1" = "-n" ]]; then | |
printf >&2 "$2" | |
else | |
printf >&2 "$1\n" | |
fi | |
} | |
fatal() { | |
log_msg "${c_fatal}[FATAL]:${c_reset} $1" | |
local code="${2:-1}" | |
exit "${code}" | |
} | |
find_pid() { | |
ps x \ | |
| grep -F rtorrent \ | |
| grep -Fv grep \ | |
| grep -Fvi screen \ | |
| grep -Fv bash \ | |
| awk '{ print $1 }' | |
} | |
auto_restart() { | |
local path="${HOME}/private/rtorrent/.prevent-restart" | |
if [[ "$1" = "on" && -e "${path}" ]]; then | |
log_msg "Enabling auto-restart for rtorrent..." | |
rm -f "${path}" | |
elif [[ "$1" = "off" && ! -e "${path}" ]]; then | |
log_msg "Disabling auto-restart for rtorrent..." | |
touch "${path}" | |
fi | |
} | |
clean_socket() { | |
local path="${HOME}/private/rtorrent/.socket" | |
if [[ -e "${path}" ]]; then | |
log_msg "Deleting orphaned socket file..." | |
rm -f "${path}" | |
fi | |
} | |
stop_rtorrent() { | |
local pid="$(find_pid)" | |
if [[ -z "${pid}" ]]; then | |
clean_socket | |
fatal "can't find rtorrent's PID" | |
fi | |
log_msg "Killing rtorrent process (${pid})..." | |
kill -INT "${pid}" | |
log_msg -n "Waiting for rtorrent to announce and quit..." | |
while [[ -n "${pid}" ]]; do | |
pid="$(find_pid)" | |
printf >&2 "." | |
perl -e "select(undef, undef, undef, 0.25);" &> /dev/null | |
done | |
printf >&2 " done.\n" | |
clean_socket | |
} | |
start_rtorrent() { | |
local pid="$(find_pid)" | |
[[ -z "${pid}" ]] || fatal "rtorrent is already started" | |
clean_socket | |
log_msg "Starting rtorrent..." | |
screen -S rtorrent -fa -d -m rtorrent | |
} | |
case "$1" in | |
start) | |
auto_restart off | |
start_rtorrent | |
;; | |
stop) | |
auto_restart off | |
stop_rtorrent | |
;; | |
restart) | |
auto_restart off | |
stop_rtorrent | |
start_rtorrent | |
;; | |
auto-on) | |
auto_restart on | |
;; | |
auto-off) | |
auto_restart off | |
;; | |
*) | |
fatal "invalid argument" | |
esac | |
log_msg "Done!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment