#!/usr/bin/python

import os
import re
import sys
import json
import pycurl
import subprocess32 as subprocess
from StringIO import StringIO
from netaddr import IPNetwork, IPAddress

def error(s):
    print s
    sys.exit(1)

metadata_url = "https://metadata.packet.net/metadata"
ipcmd = "/usr/sbin/ip"
routecmd = "/usr/sbin/route"

try:
    iface = sys.argv[1]
    op = sys.argv[2]
except:
    error("Usage: %s INTERFACE OPERATION" % sys.argv[0])

if not iface.startswith("br"):
    sys.exit(0)

if op != "up":
    sys.exit(0)

proc = subprocess.Popen("%s a l %s 2>/dev/null | grep inet | awk '{print $2}' | sed \"s,\/.*,,g\"" % (ipcmd, iface),
                        shell=True,
                        stderr=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stdin=subprocess.PIPE)
(output, err) = proc.communicate()
ret = proc.returncode
if ret:
    error("Failedto execute %s" % ipcmd)

iface_ips = []

for ip in output.split("\n"):
    # Skip ipv6 and non-private IPs
    if not ip or ':' in ip or (IPAddress(ip) not in IPNetwork("10.0.0.0/8") and \
        IPAddress(ip) not in IPNetwork("192.168.0.0/16") and \
        IPAddress(ip) not in IPNetwork("172.16.0.0/12")):
        continue
    iface_ips.append(ip)

if not iface_ips:
    sys.exit(0)

try:
    buffer = StringIO()
    c = pycurl.Curl()
    c.setopt(c.URL, metadata_url)
    c.setopt(c.WRITEFUNCTION, buffer.write)
    #c.setopt(c.VERBOSE, True)
    c.setopt(c.FOLLOWLOCATION, True)
    c.perform()
    c.close()
except:
    error("Failed to retrieve %s" % metadata_url)

buffer.seek(0)

try:
    data = json.load(buffer)
except:
    error("Failed to parse %s" % metadata_url)

buffer.close()

address = None
gateway = None
network = None
netmask = None
for n in [ n for n in data["network"]["addresses"] if n["public"] == False ]:
    address = n["address"]
    if address not in iface_ips:
        continue
    gateway = n["gateway"]
    network = n["parent_block"]["network"]
    netmask = n["parent_block"]["netmask"]

if not address or not gateway or not network or not netmask:
    sys.exit(0)

cmd = [routecmd, "add", "-net", network, "netmask", netmask, "gw", gateway]
ret = subprocess.call(cmd)
if ret:
    error("Failed to add routing '%s': %i" % (cmd, ret))

sys.exit(0)
