#!/usr/bin/python

f = open('cats.txt', 'r')

opts = {}

for line in f:
    line = eval('(' + line.strip('\r\n\t ') + ')')
    opt, section, group = line
    #print opt, section, group
    pair = ['','']
    if opt in opts:
        pair = opts[opt]
    else:
        opts[opt] = pair

    if section != '':
        pair[0] = section

    if group != '':
        pair[1] = group

f.close()

#print opts

f = open('../mysqld_new.xml', 'r')
lines = f.readlines()
f.close()

#-------------------------------------------------------------------------------
def move_option(name, section, group, linenr):
    end_line_nr = None
    i = linenr
    while end_line_nr is None:
        if lines[i].find('</mysqloption>') >= 0:
            end_line_nr = i + 1
            break
        i += 1

    ui = None
    for i in range(linenr,end_line_nr):
        line = lines[i]
        if line.find('<ui') >= 0:
            print "Found ui at line", line
            ui = i
            break

    if ui is not None:
        # Have ui section
        print "'" + name + "', '" + section + "', '" + group + "'"
        #print lines[linenr:end_line_nr]
        #print "======================================\n\n\n"
    else:
        # Add ui section
        insert_linenr = end_line_nr - 1
        uibody = []
        uibody.append('    <ui>\n')
        uibody.append('      <section class="mycnf" collection="' + section + '" group="' + group + '">\n')
        uibody.append('        <caption value="' + name + '"/>\n')
        uibody.append('        <description value="' + name + '"/>\n')
        uibody.append('      </section>\n')
        uibody.append('    </ui>\n')

        for uiline in uibody:
            lines.insert(insert_linenr, uiline)
            insert_linenr += 1

#-------------------------------------------------------------------------------
for name, (section, group) in opts.iteritems():
    for i, line in enumerate(lines):
        if line.find('<mysqloption') > 0:
            if line.find("\"" + name + "\"") > 0:
                move_option(name, section, group, i)
                break

f = open('new.xml', 'w')
for line in lines:
    f.write(line)
f.close()
