#!/usr/bin/env python

import os
import re
import sys

allconfigs = {}

# Parse config files
for config in os.listdir("."):
    # Only config.*
    if not config.startswith("config."):
        continue
    # Ignore emacs backups
    if config.endswith("~"):
        continue
    # Nothing that is disabled, or remnant
    if re.search("\.(default|disabled|stub)$", config):
        continue

    allconfigs[config] = set()

    for line in open(config):
        m = re.match("#*\s*CONFIG_(\w+)[\s=](.*)$", line)
        if not m:
            continue
        option, value = m.groups()
        allconfigs[config].add((option, value))

# Split out common config options
common = allconfigs.values()[0].copy()
for config in allconfigs.keys():
    common &= allconfigs[config]
for config in allconfigs.keys():
    allconfigs[config] -= common
allconfigs["config.common"] = common

# Generate new splitconfigs
for config in allconfigs.keys():
    f = open(config, "w")
    command = os.path.basename(sys.argv[0])
    print >>f, "#\n# Config options generated by %s\n#" % command
    for option, value in sorted(list(allconfigs[config])):
        if value == "is not set":
            print >>f, "# CONFIG_%s %s" % (option, value)
        else:
            print >>f, "CONFIG_%s=%s" % (option, value)

    f.close()
