~azzar1/unity/add-show-desktop-key

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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/python
# IVLE - Informatics Virtual Learning Environment
# Copyright (C) 2007-2009 The University of Melbourne
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# Author: Matt Giuca, Refactored by David Coles

'''Configures IVLE with machine-specific details, most notably, various paths.
Either prompts the administrator for these details or accepts them as
command-line args.

Creates etc/ivle.conf
'''

import optparse
import getopt
import os
import sys
import stat
import hashlib
import uuid

import ivle.config

import configobj

class ConfigOption:
    """A configuration option; one of the things written to conf.py."""
    def __init__(self, option_name, default, prompt, comment, ask=True):
        """Creates a configuration option.
        option_name: Name of the variable in conf.py. Also name of the
            command-line argument to setup.py conf.
        default: Default value for this variable.
        prompt: (Short) string presented during the interactive prompt in
            setup.py conf.
        comment: (Long) comment string stored in conf.py. Each line of this
            string should begin with a '#'.
        ask: Whether to ask the question in the default config run.
        """
        self.option_name = option_name
        self.default = default
        self.prompt = prompt
        self.comment = comment
        self.ask = ask

# Configuration options, defaults and descriptions
config_options = []

config_options.append(ConfigOption("urls/root", "/",
    """Root directory where IVLE is located (in URL space):""",
    """
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
# with this).
# eg. "/" or "/ivle".""", ask=False))

config_options.append(ConfigOption("paths/prefix", "/usr/local",
    """In the local file system, the prefix to the system directory where IVLE
is installed. (This should either be /usr or /usr/local):""",
    """
# In the local file system, the prefix to the system directory where IVLE is
# installed. This should either be '/usr' or '/usr/local'.
# ('/usr/local' for the usual install, '/usr' for distribution packages)""",
    ask=False))

config_options.append(ConfigOption("paths/data",
    "/var/lib/ivle",
    "In the local file system, where user-modifiable data files should be "
    "located:",
    """
# In the local file system, where user-modifiable data files should be
# located.""", ask=False))

config_options.append(ConfigOption("paths/logs",
    "/var/log/ivle",
    """Directory where IVLE log files are stored (on the local
file system). Note - this must be writable by the user the IVLE server 
process runs as (usually www-data):""",
    """
# In the local file system, where IVLE error logs should be located.""",
    ask=False))

config_options.append(ConfigOption("urls/public_host",
    "public.ivle.localhost",
    """Hostname which will cause the server to go into "public mode",
providing login-free access to student's published work:""",
    """
# The server goes into "public mode" if the browser sends a request with this
# host. This is for security reasons - we only serve public student files on a
# separate domain to the main IVLE site.
# Public mode does not use cookies, and serves only public content.
# Private mode (normal mode) requires login, and only serves files relevant to
# the logged-in user."""))

config_options.append(ConfigOption("media/version", None,
    """Version of IVLE media resources (must change on each upgrade):""",
    """
# Version string for IVLE media resource URLs. When set, they are aggressively
# cached by the browser, so it must be either left unset or changed each time
# a media file is changed.""", ask=False))

config_options.append(ConfigOption("database/host", "localhost",
    """PostgreSQL Database config
==========================
Hostname of the DB server:""",
    """
# Database server hostname"""))

config_options.append(ConfigOption("database/port", "5432",
    """Port of the DB server:""",
    """
# Database server port"""))

config_options.append(ConfigOption("database/name", "ivle",
    """Database name:""",
    """
# Database name"""))

config_options.append(ConfigOption("database/username", "postgres",
    """Username for DB server login:""",
    """
# Database username"""))

config_options.append(ConfigOption("database/password", "",
    """Password for DB server login:
    (Caution: This password is stored in plaintext!)""",
    """
# Database password"""))

config_options.append(ConfigOption("auth/modules", "",
    """Authentication config
=====================
Comma-separated list of authentication modules.""",
    """
# Comma-separated list of authentication modules.
# Note that auth is always enabled against the local database, and NO OTHER
# auth is enabled by default. This section is for specifying additional auth
# modules.
# These refer to importable Python modules in the www/auth directory.
# Modules "ldap_auth" and "guest" are available in the source tree, but
# other modules may be plugged in to auth against organisation-specific
# auth backends.""", ask=False))

config_options.append(ConfigOption("auth/ldap_url", "ldaps://www.example.com",
    """(LDAP options are only relevant if "ldap" is included in the list of
auth modules).
URL for LDAP authentication server:""",
    """
# URL for LDAP authentication server""", ask=False))

config_options.append(ConfigOption("auth/ldap_format_string",
    "uid=%s,ou=users,o=example",
    """Format string for LDAP auth request:
    (Must contain a single "%s" for the user's login name)""",
    """
# Format string for LDAP auth request
# (Must contain a single "%s" for the user's login name)""", ask=False))

config_options.append(ConfigOption("auth/subject_pulldown_modules", "",
    """Comma-separated list of subject pulldown modules.
Add proprietary modules to automatically enrol students in subjects.""",
    """
# Comma-separated list of subject pulldown modules.
# These refer to importable Python modules in the lib/pulldown_subj directory.
# Only "dummy_subj" is available in the source tree (an example), but
# other modules may be plugged in to pulldown against organisation-specific
# pulldown backends.""", ask=False))

config_options.append(ConfigOption("urls/svn_addr",
    "http://svn.ivle.localhost/",
    """Subversion config
=================
The base url for accessing subversion repositories:""",
    """
# The base url for accessing subversion repositories."""))

config_options.append(ConfigOption("usrmgt/host", "localhost",
    """User Management Server config
============================
The hostname where the usrmgt-server runs:""",
    """
# The hostname where the usrmgt-server runs."""))

config_options.append(ConfigOption("usrmgt/port", "2178",
    """The port where the usrmgt-server runs:""",
    """
# The port where the usrmgt-server runs.""", ask=False))

config_options.append(ConfigOption("usrmgt/magic", None,
    """The password for the usrmgt-server:""",
    """
# The password for the usrmgt-server.""", ask=False))

config_options.append(ConfigOption("jail/suite", "hardy",
    """The distribution release to use to build the jail:""",
    """
# The distribution release to use to build the jail.""", ask=True))

config_options.append(ConfigOption("jail/mirror", "archive.ubuntu.com",
    """The archive mirror to use to build the jail:""",
    """
# The archive mirror to use to build the jail.""", ask=True))

config_options.append(ConfigOption("jail/devmode", False,
    """Whether jail development mode be activated:""",
    """
# Should jail development mode be activated?""", ask=False))

# The password for the usrmgt-server.""", ask=False))
def query_user(default, prompt):
    """Prompts the user for a string, which is read from a line of stdin.
    Exits silently if EOF is encountered. Returns the string, with spaces
    removed from the beginning and end.

    Returns default if a 0-length line (after spaces removed) was read.
    """
    if default is None:
        # A default of None means the value will be computed specially, so we
        # can't really tell you what it is
        defaultstr = "computed"
    elif isinstance(default, basestring):
        defaultstr = '"%s"' % default
    else:
        defaultstr = repr(default)
    sys.stdout.write('%s\n    (default: %s)\n>' % (prompt, defaultstr))
    try:
        val = sys.stdin.readline()
    except KeyboardInterrupt:
        # Ctrl+C
        sys.stdout.write("\n")
        sys.exit(1)
    sys.stdout.write("\n")
    # If EOF, exit
    if val == '': sys.exit(1)
    # If empty line, return default
    val = val.strip()
    if val == '': return default
    return val

def configure(args):
    # Try importing existing conf, but if we can't just set up defaults
    # The reason for this is that these settings are used by other phases
    # of setup besides conf, so we need to know them.
    # Also this allows you to hit Return to accept the existing value.
    try:
        conf = ivle.config.Config()
    except ivle.config.ConfigError:
        # Couldn't find a config file anywhere.
        # Create a new blank config object (not yet bound to a file)
        # All lookups (below) will fail, so it will be initialised with all
        # the default values.
        conf = ivle.config.Config(blank=True)

    # Check that all the options are present, and if not, load the default
    for opt in config_options:
        try:
            conf.get_by_path(opt.option_name)
        except KeyError:
            # If the default is None, omit it
            # Else ConfigObj will write the string 'None' to the conf file
            if opt.default is not None:
                conf.set_by_path(opt.option_name, opt.default)

    # Store comments in the conf object
    for opt in config_options:
        # Omitted if the key doesn't exist
        conf.set_by_path(opt.option_name, comment=opt.comment)

    # Set up some variables
    cwd = os.getcwd()

    # the files that will be created/overwritten
    try:
        confdir = os.environ['IVLECONF']
    except KeyError:
        confdir = '/etc/ivle'

    conffile = os.path.join(confdir, 'ivle.conf')
    plugindefaultfile = os.path.join(confdir, 'plugins.d/000default.conf')

    # Get command-line arguments to avoid asking questions.

    optnames = []
    for opt in config_options:
        optnames.append(opt.option_name + "=")
    (opts, args) = getopt.gnu_getopt(args, "", optnames)

    if args != []:
        print >>sys.stderr, "Invalid arguments:", ' '.join(args)
        return 2

    if opts == []:
        # Interactive mode. Prompt the user for all the values.

        print """This tool will create %s, prompting you for details about
your configuration. The file will be updated with modified options if it already
exists. If it does not already exist, it will be created with sane defaults and
restrictive permissions.

%s will also be overwritten with the default list of plugins.

Please hit Ctrl+C now if you do not wish to do this.
""" % (conffile, plugindefaultfile)

        # Get information from the administrator
        # If EOF is encountered at any time during the questioning, just exit
        # silently

        for opt in config_options:
            if opt.ask:
                conf.set_by_path(opt.option_name,
                    query_user(conf.get_by_path(opt.option_name), opt.prompt))
    else:
        opts = dict(opts)
        # Non-interactive mode. Parse the options.
        for opt in config_options:
            if '--' + opt.option_name in opts:
                conf.set_by_path(opt.option_name,
                                 opts['--' + opt.option_name])

    # Error handling on input values
    try:
        conf['database']['port'] = int(conf['database']['port'])
        if (conf['database']['port'] < 0
            or conf['database']['port'] >= 65536):
            raise ValueError()
    except ValueError:
        if conf['database']['port'] == '' or conf['database']['port'] is None:
            pass
        else:
            print >>sys.stderr, (
            "Invalid DB port (%s).\n"
            "Must be an integer between 0 and 65535." %
                repr(conf['database']['port']))
            return 1
    try:
        conf['usrmgt']['port'] = int(conf['usrmgt']['port'])
        if (conf['usrmgt']['port'] < 0 or conf['usrmgt']['port'] >= 65536):
            raise ValueError()
    except ValueError:
        print >>sys.stderr, (
        "Invalid user management port (%s).\n"
        "Must be an integer between 0 and 65535." %
            repr(conf['usrmgt']['port']))
        return 1

    # By default we generate the magic randomly.
    try:
        conf['usrmgt']['magic']     # Throw away; just check for KeyError
    except KeyError:
        conf['usrmgt']['magic'] = hashlib.md5(uuid.uuid4().bytes).hexdigest()

    clobber_permissions = not os.path.exists(conffile)

    # Write ./etc/ivle.conf (even if we loaded from a different filename)
    conf.filename = conffile
    conf.initial_comment = ["# IVLE Configuration File"]
    conf.write()

    # We need to restrict permissions on a new file, as it contains
    # a nice database password.
    if clobber_permissions:
        os.chown(conffile, 33, 33) # chown to www-data
        os.chmod(conffile, stat.S_IRUSR | stat.S_IWUSR) # No g/o perms!

    print "Successfully wrote %s" % conffile

    plugindefault = open(plugindefaultfile, 'w')
    plugindefault.write("""# IVLE default plugin configuration file
[ivle.webapp.core#Plugin]
[ivle.webapp.admin.user#Plugin]
[ivle.webapp.tutorial#Plugin]
[ivle.webapp.admin.subject#Plugin]
[ivle.webapp.filesystem.browser#Plugin]
[ivle.webapp.filesystem.diff#Plugin]
[ivle.webapp.filesystem.svnlog#Plugin]
[ivle.webapp.filesystem.serve#Plugin]
[ivle.webapp.groups#Plugin]
[ivle.webapp.console#Plugin]
[ivle.webapp.security#Plugin]
[ivle.webapp.media#Plugin]
[ivle.webapp.help#Plugin]
[ivle.webapp.tos#Plugin]
[ivle.webapp.userservice#Plugin]
[ivle.webapp.fileservice#Plugin]
[ivle.webapp.submit#Plugin]
""")
    plugindefault.close()
    print "Successfully wrote %s" % plugindefaultfile

    print
    print "You may modify the configuration at any time by editing " + conffile
    
    return 0

def main(argv=None):
    if argv is None:
        argv = sys.argv

    # Print the opening spiel including the GPL notice

    print """IVLE - Informatics Virtual Learning Environment Setup
Copyright (C) 2007-2009 The University of Melbourne
IVLE comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See LICENSE.txt for details.

IVLE Configuration
"""

    return configure(argv[1:])

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