~ara/checkbox/fixes_554202

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/python
#
# This program is meant to be called by the debian installer in order to
# create configuration files for the hwtest package and derived packages
# based on the preseed values. The arguments are almost the same as used
# by debconf. The only difference is that the first argument passed to
# the script must be the name of the package. Also, the following options
# are supported:
#
# -v, --variable  Optional variables to preseed in the configuration file.

import os
import re
import sys
from ConfigParser import ConfigParser
from optparse import OptionParser

from debconf import Debconf, DebconfCommunicator, DebconfError, MEDIUM


DEFAULTSECT = "DEFAULT"


class Config(ConfigParser):

    def write(self, fp):
        """Write an .ini-format representation of the configuration state."""
        if self._defaults:
            fp.write("[%s]\n" % DEFAULTSECT)
            defaults = dict(self._defaults)

            # Write includes first
            if 'includes' in defaults:
                key = 'includes'
                value = defaults.pop(key)
                value = str(value).replace('\n', '\n\t')
                fp.write("%s = %s\n" % (key, value))

            for (key, value) in defaults.items():
                value = str(value).replace('\n', '\n\t')
                fp.write("%s = %s\n" % (key, value))

            fp.write("\n")

        for section in self._sections:
            fp.write("[%s]\n" % section)
            for (key, value) in self._sections[section].items():
                if key != "__name__":
                    fp.write("%s = %s\n" %
                             (key, str(value).replace('\n', '\n\t')))

            fp.write("\n")


class Install(object):
    """Install module for generating hwtest configuration files.

    The hwtest module and derivatives use a configuration file format
    compatible with ConfigParser. The values for the keys defined in
    this file can be preseeded during the installation of the package by
    using this module during the config phase of the package installation
    process.
    """
    separator = "/"
    configs_base = "/usr/share/%(base_name)s/configs/%(name)s.ini"
    examples_base = "/usr/share/%(base_name)s/examples/%(name)s.ini"

    def __init__(self, name, config_path=None, example_path=None, variables=[]):
        self.name = name
        self.base_name = re.sub(r"(-cli|-gtk)$", "", name)
        self._variables = variables
        self._configs_path = config_path or self.configs_base \
            % {"name": name, "base_name": self.base_name}
        self._examples_path = example_path or self.examples_base \
            % {"name": name, "base_name": self.base_name}

        # Create configs directory
        dirname = os.path.dirname(self._configs_path)
        if not os.path.exists(dirname):
            if os.path.islink(dirname):
                dirname = os.readlink(dirname)
            os.mkdir(dirname)

        self._config = Config()
        if os.environ.get("DEBIAN_HAS_FRONTEND"):
            if os.environ.get("DEBCONF_REDIR"):
                write = os.fdopen(3, "w")
            else:
                write = sys.stdout
            self._debconf = Debconf(write=write)
        else:
            self._debconf = DebconfCommunicator(self.name)

    def write(self, output):
        """
        Write phase of the config process which takes an output file
        as argument.
        """
        for path in [self._examples_path, self._configs_path]:
            if path and os.path.isfile(path):
                self._config.read(path)

        # Set configuration variables
        for variable in self._variables:
            section, name = variable.rsplit(self.separator, 1)
            value = self._debconf.get(variable)
            self._config.set(section, name, value)

        # Write config file
        descriptor = open(output, "w")
        self._config.write(descriptor)
        descriptor.close()

    def configure(self, priority=MEDIUM):
        """
        Configure phase of the config process.
        """
        path = self._configs_path
        if path and os.path.isfile(path):
            self._config.read(path)

        # Set debconf variables
        for variable in self._variables:
            section, name = variable.rsplit(self.separator, 1)
            if self._config.has_option(section, name):
                self._debconf.set(variable, self._config.get(section, name))

        # Ask questions and set new values, if needed.
        step = 0
        while step < len(self._variables):
            if step < 0:
                raise Exception, "Stepped too far back."
            variable = self._variables[step]
            try:
                self._debconf.input(priority, variable)
            except DebconfError, error:
                if error.args[0] != 30:
                    raise
                # Question previously answered and skipped.
                step += 1
            else:
                try:
                    self._debconf.go()
                except DebconfError, error:
                    if error.args[0] != 30:
                        raise
                    # User requested to go back.
                    step -= 1
                else:
                    step += 1


def main(args):
    """
    Main routine for running this script. The arguments are:

    package_name   Name of the package to configure.
    command        Name of the command to run as defined by debconf.
    optional       Optional arguments specific to the given command.
    """
    parser = OptionParser()
    parser.add_option("-v", "--variables",
      default=[],
      action="append",
      help="List of preseed variables.")
    args = sys.argv[1:]
    (options, args) = parser.parse_args(args)

    if len(args) < 2:
        return 1

    package = args[0]
    variables = options.variables
    install = Install(package, variables=variables)

    command = args[1]
    if command == "write":
        output = args[2]
        install.write(output)
    elif command == "configure":
        install.configure()

    return 0


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