#!/usr/bin/python
# -*- encoding: utf-8 -*-
# Small tool to replace one tracker URL to another in torrent files.
# Binary formats are awful!
# -- ugly ad-hackery by Leonid 'darkk' Evdokimov

import os, sys, re

FROM = 'torrents.ru'
TO = 'rutracker.org'

if len(sys.argv) != 3:
    print "Usage: %s <input.torrent> <output.torrent>" % sys.argv[0]
    sys.exit(1)

input_fname, output_fname = sys.argv[1], sys.argv[2]

data = open(input_fname).read()

regexp = re.compile('[0-9]+:http://[-\.a-z0-9]*%s' % re.escape(FROM))
chunks_with = re.findall(regexp, data)
chunks_without = re.split(regexp, data)
assert len(chunks_without) == len(chunks_with) + 1

if not chunks_with:
    print "No %s found in %s" % (FROM, input_fname)
    sys.exit(1)

def process_chunk(chunk):
    chunklen, urlprefix = chunk.split(':', 1)
    new_chunklen = int(chunklen) + len(TO) - len(FROM)
    new_urlprefix = urlprefix[:-len(FROM)] + TO
    assert new_chunklen > 0
    return str(new_chunklen) + ':' + new_urlprefix

new_chunks_with = map(process_chunk, chunks_with)

new_data = ''.join(reversed(reduce(lambda accum, x: accum + [x[0], x[1]], reversed(zip(new_chunks_with, chunks_without)), [chunks_without[-1]])))
open(output_fname, 'w').write(new_data)

# vim:set tabstop=4 softtabstop=4 shiftwidth=4 expandtab: 
