#!/usr/bin/python2.5
import subprocess
 
def get_routes():
  # get the current routes
  p = subprocess.Popen(['ip', 'route', 'show'], stdout=subprocess.PIPE)
  routes=[]
  while True:
    s = p.stdout.readline()
    if s == '':
      break
    s = s.split()
    # take just the default routes
    if s[0] != 'default':
      continue
    routes.append(s)
  
  if p.wait() != 0:
    return []
  return routes

def test_ip(iface, ip):
  p = subprocess.Popen(['ping', '-w2', '-c1', '-I', iface, ip], 
      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  if p.wait() != 0:
    return False 
  return True

def test_link(iface):
  # Google(MTV)
  # Ebay(MTV)
  # slasdot
  # CMU
  # Google(MTV)
  # Ebay(MTV)
  # CMU
  # Google(MTV)
  return (test_ip(iface, '74.125.19.99') 
      or test_ip(iface, '66.135.194.100')
      or test_ip(iface, '66.35.250.151') 
      or test_ip(iface, '128.2.1.10') 
      or test_ip(iface, '74.125.19.103')
      or test_ip(iface, '66.135.214.176')
      or test_ip(iface, '128.2.1.11')
      or test_ip(iface, '74.125.19.147')
      )

def delete_route(mask):
  p = subprocess.Popen(['ip', 'route', 'del', mask])
  if p.wait() != 0:
    return False 
  return True

def add_route(mask, ip, metric):
  p = subprocess.Popen(['ip', 'route', 'add', mask, 'via', ip, 'metric', metric])
  if p.wait() != 0:
    return False 
  return True


#indices
ip=2
iface=4
metric=6

# get the routes
routes = get_routes()
if not routes:
  print 'no default routes found - nevermind'
  exit(1)

# sort the routes by iface
def compare(x,y): 
  if x[iface] > y[iface]:
    return 1
  elif x[iface] < y[iface]:
    return -1
  return 0
routes.sort(compare)

# alright, now test the links
#   we want the lowest numbered link that works
#   everything else just goes in order
new_metric = []
found = False
change = False
x=0
for route in routes:
  if not found and test_link(route[iface]):
    found = True
    new_metric.append(str(1))
  else:
    new_metric.append(str(x+10))
  try:
    if new_metric[x] != route[metric]:
      change = True
  except IndexError:
    change = True
  x += 1

# if there are no changes to be made... we're done!
if not change:
  exit(1) 

print 'changing route metrics'
x=0
for route in routes:
  print 'route:', route, 'new metric', new_metric[x]
  x += 1

# now change the routes
for route in routes:
  if not delete_route('default'):
    print 'ERROR: failed to remove a route'
x=0
for route in routes:
  if not add_route('default', route[ip], new_metric[x]):
    print 'ERROR: failed to add route:', route, 'with new metric:', new_metric
  x += 1  
