#!/bin/sh
#set -x
#
# Automatic Torrent Download Queue Manager
# 
# Create a dedicated user "autorrent-user" for running this script.
#
# Start this script from unslung/rc.local and it will run indefinitely:
#
#   su autorrent-user -c "sh /autorrent-root/autorrent.sh" &
#

getNextFile()
{
	cd $TORRENTDIR
	TORRENTFILE_FULLPATH=`find . -maxdepth 2 -name "*.torrent" | head -n 1 | cut -d "/" -f 2-`
	TORRENTFILE=`find . -maxdepth 2 -name "*.torrent" | head -n 1 | cut -d "/" -f 3-`
}

# Main block starts

TORRENTDIR="/autorrent-root/torrents/queue"
WORKDIR="/autorrent-root/torrents/processing"
FINISHED_DIR="/autorrent-root/torrents/done"
CLIENT="/opt/bin/enhanced-ctorrent"
CLIENT_OPTION="-C 4 -e 24 -S localhost:2780"
while [ 1 ]; do
	getNextFile
	while [ "$TORRENTFILE" != "" ]; do
		mv "$TORRENTFILE_FULLPATH" $WORKDIR
		cd $WORKDIR
		echo $TORRENTFILE > $TORRENTDIR/Working.txt
		$CLIENT $CLIENT_OPTION "$TORRENTFILE"
		mv $WORKDIR/* $FINISHED_DIR/
		rm $TORRENTDIR/Working.txt
		getNextFile
	done
	sleep 60
done

# Main block ends
