#!/usr/bin/python
import random
from sipb_xen_database import *
import sys

# stolen directly from xend/server/netif.py
def randomMAC():
    """Generate a random MAC address.

    Uses OUI (Organizationally Unique Identifier) 00-16-3E, allocated to
    Xensource, Inc. The OUI list is available at
    http://standards.ieee.org/regauth/oui/oui.txt.

    The remaining 3 fields are random, with the first bit of the first
    random field set 0.

    @return: MAC address string
    """
    mac = [ 0x00, 0x16, 0x3e,
            random.randint(0x00, 0x7f),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff) ]
    return ':'.join(map(lambda x: "%02x" % x, mac))

# ... and stolen from xend/uuid.py
def randomUUID():
    """Generate a random UUID."""

    return [ random.randint(0, 255) for _ in range(0, 16) ]

def uuidToString(u):
    return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
                     "%02x" * 6]) % tuple(u)


def usage():
    print >> sys.stderr, "USAGE: " + sys.argv[0] + " <ip>"

def addip(ip):
    n = NIC(machine_id=None, mac_addr=randomMAC(), ip=ip, hostname=None)
    ctx.current.save(n)
    ctx.current.flush()


if __name__ == '__main__':
    if len(sys.argv) == 2:
        ip = sys.argv[1]
    else:
        usage()
        sys.exit(1)
    connect('postgres://sipb-xen@sipb-xen-dev/sipb_xen')
    addip(ip)