#!/usr/bin/env python

import sys

"""Parses input of stats.org format (originally from ep-engine) into
   JSON format for use as metadata."""

# List of sub-commands supported by cbstats...
#
#   ('all', stats_all, 'all')
#   ('allocator', stats_allocator, 'allocator')
#   ('checkpoint', stats_checkpoint, 'checkpoint [vbid]')
#   ('config', stats_config, 'config')
#   ('dispatcher', stats_dispatcher, 'dispatcher [logs]')
#   ('hash', stats_hash, 'hash [detail]')
#   ('items', stats_items, 'items (memcached bucket only)')
#   ('key', stats_key, 'key keyname vbid')
#   ('kvstore', stats_kvstore, 'kvstore')
#   ('kvtimings', stats_kvtimings, 'kvtimings')
#   ('memory', stats_memory, 'memory')
#   ('prev-vbucket', stats_prev_vbucket, 'prev-vbucket')
#   ('raw', stats_raw, 'raw argument')
#   ('reset', reset, 'reset')
#   ('restore', stats_restore, 'restore')
#   ('slabs', stats_slabs, 'slabs (memcached bucket only)')
#   ('tap', stats_tap, 'tap')
#   ('tapagg', stats_tapagg, 'tapagg')
#   ('timings', stats_timings, 'timings')
#   ('vbucket', stats_vbucket, 'vbucket')
#   ('vbucket-details', stats_vbucket_details, 'vbucket-details')
#   ('vkey', stats_vkey, 'vkey keyname vbid')

etnry_section = None
entry_name = None
entry_desc = ''
entry_more = ''

def start_entry(section, name, desc, more=''):
    global entry_section, entry_name, entry_desc, entry_more
    if entry_name and entry_desc and entry_section is not None:
        # Record the last entry when we a new entry is started.
        entry_section[1].append((entry_name, entry_desc, entry_more))
    entry_section = section
    entry_name = name
    entry_desc = desc
    entry_more = more

sections = []

with open(sys.argv[1]) as f:
    for line in f.readlines():
        parts = line.strip().split("|")
        if '*' in parts[0]:
            name = ' '.join(parts[0].split(' ')[1:])
            sections.append((name, []))
        elif len(parts) > 1:
            n = parts[1].strip()
            if n:
                start_entry(sections[-1], n, parts[2].strip(), '')
            else:
                entry_desc = entry_desc + ' ' + parts[2].strip()

start_entry(None, None, '')

def clean(s):
    return s.replace('"', '')

seen = {}

i = 1
print "{"
for section, entries in sections:
    if len(entries) > 0:
        for entry_name, entry_desc, entry_more in entries:
            if seen.get(entry_name):
                sys.exit("error: saw %s twice" % entry_name)

            if i > 0:
                print ","

            print '  "mc-%s": {' % clean(entry_name)
            print '    "col": "%s",' % clean(entry_name)
            print '    "desc": "%s",' % clean(entry_desc)
            print '    "section": "%s",' % clean(section)
            print '    "pos": %s,' % i
            print '    "visit": "fast"'
            if entry_more:
                print '    ,'
                print entry_more
            print '  }'

            i = i + 1
print "}"

