#!/usr/local/bin/perl

# Adds DHT nodes to BitTorrent files
# see http://www.bittorrent.org/beps/bep_0005.html#torrent-file-extensions

use warnings;
use strict;

use Bencode qw(bencode bdecode);
use Getopt::Std;
#use Data::Dumper;

my $defport = 6881;

my %opts;
getopts('f:', \%opts);

if(!$opts{f} || ! $ARGV[0]) {
	print <<EOH;
  Usage: $0 -f file.torrent host:port ... hostN:port
         port defaults to 6881
EOH
  exit(1);
}

open(IN, $opts{f}) || die "Open $opts{f}: $!";
$/=undef;
my $t = bdecode(scalar <IN>);
close(IN) || die "Close $opts{f}: $!";

ARGS: while(my $arg = shift) {
	my($h,$p) = split /:/,$arg,2;
	if(!$p) {
		$p = $defport;
	}
	my $pd = $p;
	$pd =~ tr/0-9//dc;
	if($pd ne $p) {
		die "$arg: Non-numeric port";
	}
	if($t->{nodes}) {
		foreach my $r (@{$t->{nodes}}) {
			if($$r[0] eq $h && $$r[1] eq $p) {
				# Don't add if already exists
				next ARGS;
			}
		}
	}
	push @{$t->{nodes}}, [$h,$p];
}

open(OUT, "> $opts{f}") || die "Open out $opts{f}: $!";
print OUT bencode $t;
close(OUT) || die "Close out $opts{f}: $!";
