#!/usr/bin/env python3

import re
import sys

from io import StringIO


def Config(filename):
    globals = {}
    module = "/usr/share/checkbox/install/config"
    exec(open(module), globals)
    config = globals["Config"]()
    config.read(filename)

    return config

def main(args):
    config_file = "/etc/checkbox.d/%s.ini" % args[0]
    config = Config(config_file)

    for section_name in config.sections():
        if section_name in ["checkbox/plugins",
                "checkbox/registries",
                "checkbox/plugins/user_interface"]:
            # Remove persist_filename option
            option = "persist_filename"
            if config.has_option(section_name, option):
                config.remove_option(section_name, option)
        else:
            # Remove everything else
            config.remove_section(section_name)

    # Rename options
    file = StringIO()
    config.write(file)

    file.seek(0)
    buffer = file.read()
    buffer = re.sub(r"directories = ", "modules = ", buffer)
    buffer = re.sub(r"gtk_path = ", "data_path = ", buffer)

    file = open(config_file, "w")
    file.write(buffer)


if __name__ == "__main__":
    main(sys.argv[1:])
