#!/usr/bin/env python3

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', encoding='utf-8') 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 = 0
                while True:
                    pos = l.find(':decl_configoption:`', pos)
                    if pos < 0:
                        break
                    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)
                    pos = endpos


with open(outfile, "wt", encoding='utf-8') 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)
