#!/usr/bin/python3
#
# This file is part of Checkbox.
#
# Copyright 2009 Canonical Ltd.
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3,
# as published by the Free Software Foundation.

#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.
#
import re
import sys
import posixpath

from subprocess import check_output, PIPE

from checkbox_support.lib.conversion import string_to_type


# Command to retrieve gconf information.
COMMAND = "gconftool-2 -R / --direct --config-source xml:readwrite:$source"

# Source directory containing gconf information.
SOURCE = "~/.gconf"


def get_gconf(output):
    id = None
    id_pattern = re.compile(r"\s+(?P<id>\/.+):")
    key_value_pattern = re.compile(r"\s+(?P<key>[\w\-]+) = (?P<value>.*)")
    list_value_pattern = re.compile(r"\[(?P<list>[^\]]*)\]")

    # TODO: add support for multi-line values

    gconf = {}
    for line in output.decode("utf-8").split("\n"):
        if not line:
            continue

        match = id_pattern.match(line)
        if match:
            id = match.group("id")
            continue

        match = key_value_pattern.match(line)
        if match:
            key = match.group("key")
            value = match.group("value")
            if value == "(no value set)":
                value = None
            else:
                match = list_value_pattern.match(value)
                if match:
                    list_string = match.group("list")
                    if len(list_string):
                        value = list_string.replace(",", " ")
                    else:
                        value = ""
                else:
                    value = string_to_type(value)

            name = "%s/%s" % (id, key)
            gconf[name] = value
            continue

    return gconf


def main():
    source = posixpath.expanduser(SOURCE)
    command = COMMAND.replace("$source", source)
    command_output = check_output(command, stderr=PIPE, shell=True)
    gconf = get_gconf(command_output)

    for name, value in gconf.items():
        print("name: %s" % name)
        print("value: %s" % value)

        # Empty line
        print()

    return 0


if __name__ == "__main__":
    sys.exit(main())
