#!/bin/bash
args=( -C 128 )
if [[ -d /mnt/media ]] ; then
	args+=( -e $((24 * 7)) -E 20 -U 200 )
else
	args+=( -e $((24 * 4)) -E 2 -U 20 )
fi

if pgrep ctcs >/dev/null ; then
	args+=( -S localhost:2780 -d )
	w() { :; }
	kw() { :; }
	timeout=
else
	w() {
		watch -n 10 -t -x sync >& /dev/null &
		pid=$!
	}
	kw() { kill ${pid} ; }
	timeout="timeout -k 1m 1h"
fi

torrents=()
while [[ $# -gt 0 ]] ; do
	case $1 in
	-*) args+=( "$1" ) ;;
	*)  torrents+=( "$1" ) ;;
	esac
	shift
done

w

[[ ${#torrents[@]} -eq 0 ]] && torrents=( *.torrent )
for t in "${torrents[@]}" ; do
	${timeout} ctorrent "${args[@]}" "$t"
done

kw
