#!/usr/bin/env python

from stem.descriptor.remote import DescriptorDownloader

RATE_MIN = 10*1024*1024
# Only boost relays that can take 10x as much traffic as they are currently
# getting
RATE_RATIO_MIN = 0.1

# Only take relays at 500 kBps and below
OBSERVED_MAX = 500*1024

# Only take relays at 500 consensus weight and below
ALLOCATED_MAX = 500
BOOST_UNMEASURED = True

downloader = DescriptorDownloader()
consensus = downloader.get_consensus().run()
desc = downloader.get_server_descriptors().run()

for rs in consensus:
  # find the ri
  ri = None
  for d in desc:
    if d.fingerprint == rs.fingerprint:
      ri = d
  if ri is None:
    continue
  # check the desired bandwidth is high, that it wants more, and that observed
  # bandwidth is low
  if (ri.average_bandwidth >= RATE_MIN
      and ri.average_bandwidth*RATE_RATIO_MIN >= ri.observed_bandwidth
      and ri.observed_bandwidth < OBSERVED_MAX):
    # check the allocated bandwidth is low (or unmeasured)
    if ((rs.bandwidth < ALLOCATED_MAX)
        or (BOOST_UNMEASURED and rs.is_unmeasured)):
      #print "#{:10} {:10} {:10} {} {} {}".format(ri.average_bandwidth, ri.observed_bandwidth, rs.bandwidth, rs.is_unmeasured, ri.nickname, ri.fingerprint)
      if rs.dir_port is not None:
        print "echo '{:10} {:10} {:10} {} {} {}'".format(ri.average_bandwidth, ri.observed_bandwidth, rs.bandwidth, rs.is_unmeasured, ri.nickname, ri.fingerprint)
        print "curl --connect-timeout 5 --max-time 20 -X GET --data-binary @100MB http://{}:{}/tor/server/authority.z > /dev/null &".format(rs.address, rs.dir_port)
        print "curl --connect-timeout 5 --max-time 20 http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z http://{0}:{1}/tor/server/all.z > /dev/null &".format(rs.address, rs.dir_port)
        print "wait"
      else:
        pass
        #print "# No DirPort"
