#!/usr/bin/env python

import fnmatch
import os
import sys

dirname = sys.argv[1]
outfile = sys.argv[2]

matches = []
for root, dirnames, filenames in os.walk(dirname):
    for filename in fnmatch.filter(filenames, '*.rst'):
        matches.append(os.path.join(root, filename))

configoptions = {}

for filename in matches:
    with open(filename, 'rt') as f:
        link = None
        for l in f.readlines():
            l = l.rstrip('\n')
            if not link:
                if not l.startswith('.. _') and l.endswith(':'):
                    break
                link = l[len('.. _'):-1]
            else:
                pos = l.find(':decl_configoption:`')
                if pos >= 0:
                    endpos = l.find('`', pos+len(':decl_configoption:`'))
                    configoption = l[pos+len(':decl_configoption:`'):endpos]
                    if not configoption in configoptions:
                        configoptions[configoption] = set()
                    configoptions[configoption].add(link)


with open(outfile, "wt") as f:
    f.write('..\n')
    f.write('  This file is generated by build_configoptions_index.py. DO NOT EDIT !!!\n')
    f.write('  Do not put in git !!!\n')
    f.write('..\n')
    f.write('\n')

    for key in sorted(configoptions.keys()):
        f.write('* %s:' % key)
        if len(configoptions[key]) >= 2:
            f.write('\n')
            f.write('\n')
            for link in configoptions[key]:
                f.write('  - :ref:`%s`\n' % link)
        else:
            for link in configoptions[key]:
                f.write(' :ref:`%s`\n' % link)
