#!/usr/bin/env python3

"""See this page for more details:
http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kernel-configuration
"""

from __future__ import print_function

import os
import re
import sys

allconfigs = {}

# Parse config files
for config in os.listdir("."):
    # Only config.*
    if not config.endswith(".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 = None
for config in allconfigs:
    if common is None:
        common = allconfigs[config].copy()
    else:
        common &= allconfigs[config]
for config in allconfigs:
    allconfigs[config] -= common
allconfigs["common.config"] = common

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

    f.close()
