#!/usr/bin/python

import argparse

from uuid import UUID, uuid5

def uuidFromName(namespace, name):
    """
    Generate a version 5 (SHA-1) UUID from a namespace UUID and a name.
    See http://www.ietf.org/rfc/rfc4122.txt, section 4.3.
    @param namespace: a UUID denoting the namespace of the generated UUID.
    @param name: a byte string to generate the UUID from.
    """
    # We don't want Unicode here; convert to UTF-8
    if type(name) is unicode:
        name = name.encode("utf-8")

    return str(uuid5(UUID(namespace), name))

def normalizeUUID(value):
    """
    Convert strings which the uuid.UUID( ) method can parse into normalized
    (uppercase with hyphens) form.  Any value which is not parsed by UUID( )
    is returned as is.
    @param value: string value to normalize
    """
    try:
        return str(UUID(value)).upper()
    except (ValueError, TypeError):
        return value

def main():
    parser = argparse.ArgumentParser(description='Given the realm, record type and uid, generate the corresponding GUID')
    parser.add_argument("--realm", required=True)
    parser.add_argument("--record-type", required=True,
                        choices=["users","groups","locations","resources"])
    parser.add_argument("--uid", required=True)
    args = parser.parse_args()

    baseGUID = "9CA8DEC5-5A17-43A9-84A8-BE77C1FB9172"
    serviceGUID = uuidFromName(baseGUID, args.realm)
    guid = uuidFromName(serviceGUID,
                        "%s:%s" % (args.record_type, ",".join([args.uid])))
    guid = normalizeUUID(guid)

    print guid

if __name__ == "__main__":
    main()
