#! /usr/bin/env python
# -*- coding: UTF-8 -*-

# Copyright (C) 2005, 2006 Canonical Ltd.
# Written by Colin Watson <cjwatson@ubuntu.com>.
#
# 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

# This program handles OEM installations: it is run on the first boot after
# the end user receives the system, to configure settings specific to that
# end user.

import sys
import os
import optparse
import subprocess

sys.path.insert(0, '/usr/lib/oem-config')

from oem_config import im_switch

class Wizard:
    def __init__(self, frontend_name=None):
        if frontend_name is None:
            frontend_names = ['gtk_ui', 'kde_ui']
        else:
            frontend_names = [frontend_name]
        mod = __import__('oem_config.frontend', globals(), locals(),
                         frontend_names)
        chosen = None
        for f in frontend_names:
            if hasattr(mod, f):
                chosen = f
                ui = getattr(mod, f)
                break
        else:
            raise AttributeError, ('No frontend available; tried %s' %
                                   ', '.join(frontend_names))
        self.frontend = ui.Frontend()
        os.environ['OEM_CONFIG_FRONTEND'] = chosen

    def run(self):
        self.frontend.run()

def disable_autologin():
    import traceback

    # Reverse actions of finish-install.d/07oem-config-user.
    for name in ('/etc/gdm/gdm-cdd.conf', '/etc/gdm/gdm.conf',
                 '/etc/kde3/kdm/kdmrc'):
        if os.path.exists('%s.oem' % name):
            try:
                os.rename('%s.oem' % name, name)
            except OSError:
                traceback.print_exc()
    if os.path.exists('/etc/kde3/kpersonalizerrc.created-by-oem'):
        try:
            os.unlink('/etc/kde3/kpersonalizerrc')
        except OSError:
            traceback.print_exc()
        try:
            os.unlink('/etc/kde3/kpersonalizerrc.created-by-oem')
        except OSError:
            traceback.print_exc()

def run_hooks():
    """Run hook scripts from /usr/lib/oem-config/post-install."""

    hookdir = '/usr/lib/oem-config/post-install'

    if os.path.isdir(hookdir):
        # Exclude hooks containing '.', so that *.dpkg-* et al are avoided.
        hooks = filter(lambda entry: '.' not in entry, os.listdir(hookdir))
        child_env = dict(os.environ)
        child_env['DEBIAN_FRONTEND'] = 'noninteractive'
        if 'DEBIAN_HAS_FRONTEND' in child_env:
            del child_env['DEBIAN_HAS_FRONTEND']
        for hookentry in hooks:
            hook = os.path.join(hookdir, hookentry)
            if os.access(hook, os.X_OK):
                # Errors are ignored at present, although this may change.
                subprocess.call([hook], env=child_env)

if __name__ == '__main__':
    usage = ("usage: %prog [options]\n\n"
             "Use oem-config-prepare to prepare the system for an end user.")
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('-f', '--frontend', metavar='FRONTEND',
                      help="Use the given frontend (gtk_ui).")
    parser.add_option('-d', '--debug', dest='debug', action='store_true',
                      help='debug mode (warning: passwords will be logged!)')
    parser.add_option('--pdb', dest='debug_pdb', action='store_true',
                      help='drop into Python debugger on a crash')
    parser.add_option('--old-tzmap', dest='old_tzmap', action='store_true',
                      help='use the old timezone map.')
    parser.set_defaults(frontend=None, debug_pdb=False)
    (options, args) = parser.parse_args()

    if args:
        parser.print_help(sys.stderr)
        sys.exit(2)

    if options.debug:
        os.environ['OEM_CONFIG_DEBUG'] = '1'

    if options.debug_pdb:
        os.environ['OEM_CONFIG_DEBUG_PDB'] = '1'

    if options.old_tzmap:
        os.environ['UBIQUITY_OLD_TZMAP'] = '1'

    if 'OEM_CONFIG_DEBUG' in os.environ:
        if 'DEBCONF_DEBUG' not in os.environ:
            os.environ['DEBCONF_DEBUG'] = 'developer|filter'

    wizard = Wizard(frontend_name=options.frontend)
    wizard.run()
    disable_autologin()
    run_hooks()
    im_switch.kill_im()
    sys.exit(0)
