#!/usr/bin/env python

#
# mkprot.py
#

import string, re

output = """/* protocols.h generated by mkprot.py from protocols.txt */
PROTOCOL_INFO MoreKnownProtocols[] = {
"""

re_empty = re.compile(r"\s*$")
re_comment = re.compile(r"\s*#.*$")
re_namesplit = re.compile(r"(\S+)\s+(\S.*?)\s*$")
re_guid1 = re.compile(r"0x([0-9a-f]{1,8}),\s*0x([0-9a-f]{1,4}),\s*0x([0-9a-f]{1,4}),\s*0x([0-9a-f]{1,2}),\s*0x([0-9a-f]{1,2}),\s*0x([0-9a-f]{1,2}),\s*0x([0-9a-f]{1,2}),\s*0x([0-9a-f]{1,2}),\s*0x([0-9a-f]{1,2}),\s*0x([0-9a-f]{1,2}),\s*0x([0-9a-f]{1,2})", re.I)
re_guid2 = re.compile(r"([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})", re.I)

f = file("protocols.txt", "r")
for line in f:
    if re_empty.match(line) is not None:
        continue
    if re_comment.match(line) is not None:
        continue
    match = re_namesplit.match(line)
    if match is None:
        print "Skipping line '%s'" % line
        continue
    name = match.group(1)
    value = match.group(2)
    
    guid_v = None
    
    match = re_guid1.match(value)
    if match is not None:
        guid_v = list(match.groups())
    
    match = re_guid2.match(value)
    if match is not None:
        m4 = match.group(4)
        m5 = match.group(5)
        guid_v = [ match.group(1), match.group(2), match.group(3), m4[0:2], m4[2:4], m5[0:2], m5[2:4], m5[4:6], m5[6:8], m5[8:10], m5[10:12] ]
    
    if guid_v is None:
        print "Didn't recognize line '%s'" % line
        continue
    
    guid_v[0] = guid_v[0].zfill(8)
    guid_v[1] = guid_v[1].zfill(4)
    guid_v[2] = guid_v[2].zfill(4)
    guid_v[3] = guid_v[3].zfill(2)
    guid_v[4] = guid_v[4].zfill(2)
    guid_v[5] = guid_v[5].zfill(2)
    guid_v[6] = guid_v[6].zfill(2)
    guid_v[7] = guid_v[7].zfill(2)
    guid_v[8] = guid_v[8].zfill(2)
    guid_v[9] = guid_v[9].zfill(2)
    guid_v[10] = guid_v[10].zfill(2)
    guid_c = "0x%s, 0x%s, 0x%s, { 0x%s, 0x%s, 0x%s, 0x%s,\n        0x%s, 0x%s, 0x%s, 0x%s }" % tuple(guid_v)
    
    output = output + """    { { %s },     L"%s", NULL },
""" % (guid_c, name)

f.close()

output = output + """    { {0,0,0,0,0,0,0,0,0,0,0},          NULL, NULL },
};
"""

f = file("protocols.h", "w")
f.write(output)
f.close()

# EOF
