#!/usr/bin/perl use warnings; use strict; use POSIX ":sys_wait_h"; our $TORRENTQ = "/home/fserve/downloads/torrent-queue"; our $DLDIR = "/home/fserve/downloads"; our $BTCLIENT = "/usr/bin/btdownloadcurses"; our @BTPARAMS = ( qw( --max_upload_rate 10 )); our @torrents; &main_loop(); sub scan_torrent_queue { opendir(DH,$TORRENTQ) or die "Failed to open torrent queue: $!\n"; my @tlist = grep /\.torrent$/, readdir(DH); closedir(DH); push @tlist, @torrents; @tlist = sort @tlist; my $last = ""; @torrents = (); for (@tlist) { next if ($_ eq $last); next if (! -f $TORRENTQ . "/" . $_); push @torrents, $_; $last = $_; } } sub main_loop { while (1) { scan_torrent_queue; my $delay = 60 * 60 * 24 / scalar @torrents; for (@torrents) { printf("\n\n\nRunning this torrent for %d seconds.\n",$delay); sleep(5); do_torrent(-delay => $delay, -torrent => $_); } } } sub do_torrent { my %params = @_; my $pid = fork(); if ($pid > 0) { # Parent my $delay = $params{-delay}; do { sleep($delay); scan_torrent_queue; $delay /= 2 if ($delay > 120); } while (@torrents == 1); kill 1, $pid; my ($kid, $wait) = (0,0); do { sleep 1; $kid = waitpid(-1,WNOHANG); $wait++; if ($wait > 5) { kill 9, $pid; } } until $kid == -1; } elsif ($pid == 0) { # Child chdir($DLDIR); exec $BTCLIENT, @BTPARAMS, "--responsefile", $TORRENTQ . "/" . $params{-torrent} or die "Failed to exec: $!\n"; } else { die "Error forking? Waaaah? $!"; } }