#!/usr/bin/python3

'''
Installer

This is a installer program for a Ubuntu or Metadistros Live system.
This is the main program, but there are also a couple of libraries to
help it to work, such as the frontend.
The way it works is simple. It detects the frontend to use, then
load the module for that frontend. After that, it makes some calls
through the frontend in order to get the info necessary to install.

Once it has the info, partitioning, format, copy the distro to the disk
and configure everything.
'''

from __future__ import print_function

import atexit
import errno
import fcntl
import importlib
import locale
from operator import attrgetter
import optparse
import os
import pwd
import shutil
import subprocess
import sys
import syslog

sys.path.insert(0, '/usr/lib/ubiquity')

from ubiquity import im_switch, misc, osextras


VERSION = '@VERSION@'
TARGET = '/target'
LOCKFILE = '/var/lock/ubiquity'
lock = None


def force_utf8_locale():
    """We must have a UTF-8 locale.  Try to get one."""

    # apt now follows LC_NUMERIC; we must make sure it's set appropriately
    # so that debconf-apt-progress and uses of python-apt will be able to
    # parse pmstatus messages. (LP: #1611010)
    os.environ["LC_NUMERIC"] = "C.UTF-8"

    if locale.getpreferredencoding() != "UTF-8":
        try:
            os.environ["LC_ALL"] = "C.UTF-8"
            locale.setlocale(locale.LC_ALL, "")
        except locale.Error:
            # Abandon hope.
            print("Ubiquity requires a UTF-8 locale and cannot proceed "
                  "without one.", file=sys.stderr)
            sys.exit(1)


def distribution():
    """Returns the name of the running distribution."""
    proc = subprocess.Popen(
        ['lsb_release', '-is'], stdout=subprocess.PIPE,
        universal_newlines=True)
    return proc.communicate()[0].strip()


def disable_autologin():
    import traceback

    # Reverse actions of user-setup-apply.
    for name in ('/etc/gdm3/custom.conf', '/etc/kde4/kdm/kdmrc',
                 '/etc/lxdm/lxdm.conf', '/etc/xdg/lubuntu/lxdm/lxdm.conf',
                 '/etc/lightdm/lightdm.conf'):
        if os.path.exists('%s.oem' % name):
            try:
                os.rename('%s.oem' % name, name)
            except OSError:
                traceback.print_exc()


def open_terminal():
    """Set up the terminal to run ubiquity's debconf frontend."""
    # Set up a framebuffer and start bterm if debian-installer/framebuffer
    # says to do so. See, in rootskel:
    #   src/lib/debian-installer-startup.d/S40framebuffer-module-linux-x86
    # TODO: more careful architecture handling

    import debconf

    # Start a new session and start a controlling terminal. Approach loosely
    # borrowed from util-linux.

    if 'UBIQUITY_CTTY' not in os.environ:
        os.environ['UBIQUITY_CTTY'] = '1'

        import termios

        try:
            os.setsid()
        except OSError:
            pass

        ttyn = os.ttyname(0)
        tty = os.open(ttyn, os.O_RDWR | os.O_NONBLOCK)
        flags = fcntl.fcntl(tty, fcntl.F_GETFL)
        fcntl.fcntl(tty, fcntl.F_SETFL, flags)
        # Leave stderr alone in the following; it's already redirected to
        # our log file.  We also need to avoid closing the FD for
        # /dev/urandom (http://bugs.python.org/issue21207).
        dev_ino = attrgetter("st_dev", "st_ino")
        urandom_dev_ino = dev_ino(os.stat("/dev/urandom"))
        for i in range(tty):
            if i != 2 and dev_ino(os.fstat(i)) != urandom_dev_ino:
                os.close(i)
        for i in range(2):
            if tty != i:
                os.dup2(tty, i)
        if tty >= 3:
            os.close(tty)

        fcntl.ioctl(0, termios.TIOCSCTTY, 1)

    if 'UBIQUITY_BTERM' not in os.environ:
        os.environ['UBIQUITY_BTERM'] = '1'

        framebuffer = False
        dccomm = subprocess.Popen(['debconf-communicate',
                                   '-fnoninteractive', 'ubiquity'],
                                  stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE, close_fds=True,
                                  universal_newlines=True)
        try:
            dc = debconf.Debconf(read=dccomm.stdout, write=dccomm.stdin)
            try:
                if dc.get('debian-installer/framebuffer') == 'true':
                    framebuffer = True
            except debconf.DebconfError:
                pass
        finally:
            dccomm.stdin.close()
            dccomm.wait()

        if framebuffer:
            def fb_has(substring):
                try:
                    with open('/proc/fb') as fb:
                        for line in fb:
                            if substring in line:
                                return True
                except IOError:
                    pass
                return False

            got_fb = False
            if fb_has('VESA'):
                got_fb = True

            devnull = open('/dev/null', 'w')

            if not got_fb:
                subprocess.call(['modprobe', '-q', 'vesafb'],
                                stdout=devnull, stderr=devnull)
                if fb_has(''):
                    got_fb = True

            if not got_fb:
                subprocess.call(['modprobe', '-q', 'vga16fb'],
                                stdout=devnull, stderr=devnull)
                if fb_has(''):
                    got_fb = True

            if got_fb:
                if not os.path.isdir('/sys/class/graphics/fbcon'):
                    subprocess.call(['modprobe', '-q', 'fbcon'],
                                    stdout=devnull, stderr=devnull)

                # TODO: import debian-installer-utils and use update-dev?
                subprocess.call(['udevadm', 'settle'])

            devnull.close()

            if os.path.exists('/dev/fb0'):
                bterm_args = ['bterm',
                              '-f', '/usr/share/ubiquity/unifont.bgf', '--']
                bterm_args.extend(sys.argv)
                os.execvp('bterm', bterm_args)


def start_debconf():
    """debconf_ui needs to run within a debconf frontend."""
    if 'DEBIAN_HAS_FRONTEND' in os.environ:
        # debconf already started, so just clean up the configuration file
        # if any (debconf has already read it by now).
        if 'DEBCONF_SYSTEMRC' in os.environ:
            osextras.unlink_force(os.environ['DEBCONF_SYSTEMRC'])
        return

    print("debconf_ui selected; starting debconf frontend", file=sys.stderr)

    if 'UBIQUITY_AUTOMATIC' in os.environ:
        # In automatic mode, we don't want debconf to reshow seen questions,
        # since that defeats the purpose of preseeding.
        pass
    elif 'DEBCONF_USE_CDEBCONF' not in os.environ:
        # This is rather unsatisfactory. Perhaps it would be better to
        # have a custom debconf program, a bit like dpkg-reconfigure.
        import tempfile
        debconfrc_fd, debconfrc = tempfile.mkstemp()
        os.chmod(debconfrc, 0o644)
        debconfrc_file = os.fdopen(debconfrc_fd, 'w')
        orig_debconfrc = open('/etc/debconf.conf')
        state = 0
        for line in orig_debconfrc:
            if (state == 0 and
                    line.rstrip('\n') and not line.startswith('#')):
                state = 1
            elif state == 1 and not line.rstrip('\n'):
                print('Reshow: true', file=debconfrc_file)
                state = 2
            print(line, end="", file=debconfrc_file)
        orig_debconfrc.close()
        debconfrc_file.close()
        os.environ['DEBCONF_SYSTEMRC'] = debconfrc
    else:
        os.environ['DEBCONF_SHOWOLD'] = 'true'

    if 'DEBCONF_USE_CDEBCONF' not in os.environ:
        os.environ['DEBCONF_PACKAGE'] = 'ubiquity'
    # TODO: need to set owner somehow for the cdebconf case

    import debconf
    debconf.runFrontEnd()  # re-execs this program


def install(frontend=None, query=False):
    """Get the type of frontend to use and load the module for that.

    If frontend is None, defaults to the first of gtk_ui, kde_ui, and
    debconf_ui that exists.
    """
    if frontend is None:
        frontends = ['gtk_ui', 'kde_ui', 'debconf_ui']
    else:
        frontends = [frontend]
    chosen = None
    for f in frontends:
        try:
            ui = importlib.import_module('ubiquity.frontend.%s' % f)
        except ImportError:
            continue
        chosen = f
        # Noninteractive implies automatic mode.
        if f == 'noninteractive':
            os.environ['UBIQUITY_AUTOMATIC'] = '1'
        break
    else:
        raise AttributeError('No frontend available; tried %s' %
                             ', '.join(frontends))
    os.environ['UBIQUITY_FRONTEND'] = chosen
    if query:
        print(os.environ['UBIQUITY_FRONTEND'], file=sys.__stdout__)
        sys.exit(0)

    unmount_target()
    distro = distribution().lower()
    wizard = ui.Wizard(distro)
    if os.environ['UBIQUITY_FRONTEND'] == 'debconf_ui':
        open_terminal()
        start_debconf()
    ret = wizard.run()
    wizard.stop_debconf()
    if ret != 10 and 'UBIQUITY_GREETER' in os.environ:
        import traceback
        try:
            apply_keyboard()
        except Exception:
            traceback.print_exc()
    copy_debconf()
    unmount_target()
    if ret == 10:
        wizard.do_reboot()
    if ret == 11:
        wizard.do_shutdown()


@misc.raise_privileges
def apply_keyboard():
    """Set the keyboard layout to the default layout for the language selected.

    If a user wants a different layout, they can be reasonably expected to
    change it in System -> Preferences -> Keyboard.
    """

    # Mostly taken from ubi-console-setup.

    # We need to get rid of /etc/default/keyboard, or keyboard-configuration
    # will think it's already configured and behave differently. Try to save
    # the old file for interest's sake, but it's not a big deal if we can't.
    osextras.unlink_force('/etc/default/keyboard.pre-ubiquity')
    try:
        os.rename('/etc/default/keyboard',
                  '/etc/default/keyboard.pre-ubiquity')
    except OSError:
        osextras.unlink_force('/etc/default/keyboard')

    import debconf
    dccomm = subprocess.Popen(['debconf-communicate',
                               '-fnoninteractive', 'ubiquity'],
                              stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE, close_fds=True,
                              universal_newlines=True)
    try:
        dc = debconf.Debconf(read=dccomm.stdout, write=dccomm.stdin)
        try:
            # Make sure debconf doesn't do anything with crazy "preseeded"
            # answers to these questions. If you want to preseed these, use the
            # *code variants.
            dc.fset('keyboard-configuration/layout', 'seen', 'false')
            dc.fset('keyboard-configuration/variant', 'seen', 'false')
            dc.fset('keyboard-configuration/model', 'seen', 'false')
            dc.fset('console-setup/codeset47', 'seen', 'false')
        except debconf.DebconfError:
            return
    finally:
        dccomm.stdin.close()
        dccomm.wait()

    # Accept all the defaults, given the preseeded language.
    child_env = dict(os.environ)
    child_env['OVERRIDE_ALLOW_PRESEEDING'] = '1'
    subprocess.call(['dpkg-reconfigure', '-fnoninteractive',
                     'keyboard-configuration'],
                    env=child_env)
    misc.execute('setupcon', '--save-only')
    # Reprocess /lib/udev/rules.d/64-xorg-xkb.rules
    misc.execute('udevadm', 'trigger', '--subsystem-match=input',
                 '--action=change')
    misc.execute('udevadm', 'settle')


def copy_debconf():
    """Copy a few important questions into the installed system."""
    if not TARGET:
        return
    targetdb = TARGET + '/var/cache/debconf/config.dat'
    patterns = ['^oem-config/']
    oem = False

    import debconf
    dccomm = subprocess.Popen(['debconf-communicate',
                               '-fnoninteractive', 'ubiquity'],
                              stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE, close_fds=True,
                              universal_newlines=True)
    try:
        dc = debconf.Debconf(read=dccomm.stdout, write=dccomm.stdin)
        try:
            if dc.get('oem-config/enable') == 'true':
                oem = True
        except debconf.DebconfError:
            pass
    finally:
        dccomm.stdin.close()
        dccomm.wait()

    if not oem:
        patterns.append('^keyboard-configuration/')
        patterns.append('^console-setup/')

    for q in patterns:
        misc.execute_root(
            'debconf-copydb', 'configdb', 'targetdb', '-p', q,
            '--config=Name:targetdb', '--config=Driver:File',
            '--config=Mode:0644', '--config=Filename:%s' % targetdb)


def unmount_target():
    if not TARGET:
        return
    paths = []
    pools = set()
    with open('/proc/mounts') as mounts:
        for line in mounts:
            source, path, fstype = line.split(' ')[:3]
            if path == TARGET or path.startswith(TARGET + '/'):
                paths.append(path)
                if fstype == 'zfs':
                    pools.add(source.split('/')[0])
    paths.sort()
    paths.reverse()
    for path in paths:
        misc.execute_root('fuser', '-cv', path)
        misc.execute_root('umount', path)
    keystore_mapper = "/dev/mapper/keystore-rpool"
    if os.path.exists(keystore_mapper):
        misc.execute_root('umount', keystore_mapper)
        misc.execute_root('cryptsetup', 'luksClose', keystore_mapper)
    swap_mapper = "/dev/mapper/cryptoswap"
    if os.path.exists(swap_mapper):
        misc.execute_root('swapoff', swap_mapper)
        misc.execute_root('cryptsetup', 'luksClose', swap_mapper)
    for pool in pools:
        misc.execute_root('/sbin/zpool', 'export', pool)


def prepend_path(directory):
    if 'PATH' in os.environ and os.environ['PATH'] != '':
        os.environ['PATH'] = '%s:%s' % (directory, os.environ['PATH'])
    else:
        os.environ['PATH'] = directory


def release_lock():
    global lock
    osextras.unlink_force(LOCKFILE)
    if lock is not None:
        lock.close()
        lock = None


def acquire_lock():
    global lock
    lock = open(LOCKFILE, 'w')
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError as e:
        if e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK):
            print("Ubiquity is already running!")
            sys.exit(1)
        raise
    atexit.register(release_lock)
    fcntl.fcntl(lock, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
    print(os.getpid(), file=lock)
    lock.flush()
    os.fsync(lock.fileno())

    if 'DEBIAN_HAS_FRONTEND' not in os.environ:
        # Do a quick check to see if the debconf database is locked by
        # something else.
        test_debconf = subprocess.Popen(
            ['debconf-communicate', '-fnoninteractive', 'ubiquity'],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True,
            universal_newlines=True)
        try:
            # It seems that in python3.4, the below print is not
            # flushed by default, thus adding "flush=True" kargs and
            # thus avoid a boot hang as seen in LP: #1326707 But flush
            # karg was only introduced in python3.3, instead this is a
            # big FIXME and should instead use
            # test_debconf.communicate() I'll propose a merge proposal
            # which does that, but not at 1 AM when it is still
            # boiling hot in London and I can't fall asleep.
            print('VERSION 2.0', file=test_debconf.stdin, flush=True)
            test_debconf.stdout.readline()
        except IOError:
            pass
        test_debconf.stdin.close()
        test_debconf.stdout.close()
        if test_debconf.wait() != 0:
            print("Debconf database is locked!")
            print("This may be because a package management program is "
                  "running.")
            sys.exit(1)


def run_oem_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 = [entry for entry in os.listdir(hookdir) if '.' not in entry]
        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)


def main(oem_config):
    force_utf8_locale()

    usage = '%prog [options] [frontend]'
    parser = optparse.OptionParser(usage=usage, version=VERSION)
    parser.set_defaults(
        debug=('UBIQUITY_DEBUG' in os.environ),
        debug_pdb=False,
        cdebconf=False,
        automatic=False,
        query=False)
    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('--cdebconf', dest='cdebconf', action='store_true',
                      help='use cdebconf instead of debconf (experimental)')
    parser.add_option('--automatic', dest='automatic', action='store_true',
                      help='do not ignore the "seen" flag (useful for '
                           'unattended installations).')
    parser.add_option('--only', dest='only', action='store_true',
                      help='tell the application that it is the only desktop '
                           'program running so that it can customize its UI '
                           'to better suit a minimal environment.')
    parser.add_option('-q', '--query', dest='query', action='store_true',
                      help='find out which frontend will be used by default')
    parser.add_option('-g', '--greeter', dest='greeter', action='store_true',
                      help='allow the user to leave the installer and enter '
                           'a live desktop (for the initial boot).')
    parser.add_option('-b', '--no-bootloader', dest='bootloader',
                      default=True, action='store_false',
                      help='Do not install a bootloader.')
    parser.add_option('--ldtp', dest='ldtp',
                      action='store_true',
                      help='Name widgets in ATK by their GtkBuilder names, '
                           'to support LDTP testing.')
    parser.add_option('--autopilot', dest='autopilot',
                      action='store_true',
                      help='Export variables needed for autopilot to drive '
                           'ubiquity UI.')
    parser.add_option('--wireless', dest='wireless',
                      action='store_true',
                      help='Force enable the wireless page, even if network '
                           'is available.')

    (options, args) = parser.parse_args()

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

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

    if options.cdebconf:
        # Note that this needs to be set before DebconfCommunicate is
        # imported by anything.
        os.environ['DEBCONF_USE_CDEBCONF'] = '1'
        prepend_path('/usr/lib/cdebconf')
    prepend_path('/usr/lib/ubiquity/compat')

    if options.automatic:
        os.environ['UBIQUITY_AUTOMATIC'] = '1'

    if options.greeter:
        os.environ['UBIQUITY_GREETER'] = '1'

    if options.only:
        os.environ['UBIQUITY_ONLY'] = '1'

    if not options.bootloader:
        os.environ['UBIQUITY_NO_BOOTLOADER'] = '1'

    if oem_config:
        os.environ['UBIQUITY_OEM_USER_CONFIG'] = '1'
        global TARGET
        TARGET = ''

    if options.ldtp:
        os.environ['UBIQUITY_LDTP'] = '1'

    if options.wireless:
        os.environ['UBIQUITY_WIRELESS'] = '1'

    uid = os.getenv('PKEXEC_UID', False)
    if uid:
        # pkexec doesn't set username, but it's used in a few places.
        # fake it from PKEXEC =)
        os.environ['SUDO_USER'] = pwd.getpwuid(int(uid)).pw_name
        os.environ['HOME'] = pwd.getpwuid(int(uid)).pw_dir

    acquire_lock()

    try:
        os.makedirs('/var/log/installer')
    except OSError as e:
        # be happy if someone already created the path
        if e.errno != errno.EEXIST:
            raise
    syslog.openlog('ubiquity', syslog.LOG_NOWAIT | syslog.LOG_PID)

    if oem_config:
        syslog.syslog("Ubiquity %s (oem-config)" % VERSION)
    else:
        syslog.syslog("Ubiquity %s" % VERSION)
    with open('/var/log/installer/version', 'w') as version_file:
        print('ubiquity %s' % VERSION, file=version_file)

    if options.autopilot:
        os.environ['UBIQUITY_AUTOPILOT'] = '1'
        with open('/var/log/installer/autopilot', 'w') as autopilot_file:
            print('DBUS_SESSION_BUS_ADDRESS=%s' %
                  os.environ['DBUS_SESSION_BUS_ADDRESS'], file=autopilot_file)
            print('UBIQUITY_PID=%i' % os.getpid(), file=autopilot_file)

    if 'UBIQUITY_DEBUG' in os.environ:
        if 'UBIQUITY_DEBUG_CORE' not in os.environ:
            os.environ['UBIQUITY_DEBUG_CORE'] = '1'
        if 'DEBCONF_DEBUG' not in os.environ:
            os.environ['DEBCONF_DEBUG'] = 'developer'
    # The frontend should take care of displaying a helpful message if
    # we are being run without root privileges.
    if not (options.query and args and args[0] == 'noninteractive'):
        try:
            if oem_config:
                logfile = '/var/log/oem-config.log'
            else:
                logfile = '/var/log/installer/debug'
            log = os.open(logfile, os.O_WRONLY | os.O_CREAT | os.O_APPEND,
                          0o644)
            os.dup2(log, 2)
            os.close(log)
            sys.stderr = os.fdopen(2, 'a', 1)
            if oem_config:
                print("Ubiquity %s (oem-config)" % VERSION, file=sys.stderr)
            else:
                print("Ubiquity %s" % VERSION, file=sys.stderr)
        except (IOError, OSError) as err:
            if err.errno != errno.EACCES:
                raise

    # Default to enabling internal (non-debconf) debugging except for when
    # using --automatic.
    if 'UBIQUITY_DEBUG_CORE' not in os.environ:
        if options.automatic:
            os.environ['UBIQUITY_DEBUG_CORE'] = '1'

    # Initialise cdebconf if necessary, to work around
    # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=451130.
    if options.cdebconf:
        for package in ('ubiquity', 'keyboard-configuration', 'console-setup'):
            subprocess.call(['debconf-loadtemplate', package,
                             '/var/lib/dpkg/info/%s.templates' % package])

    # Clean up old state.
    for name in ('apt-installed', 'apt-install-direct', 'remove-kernels',
                 'apt-removed', 'encrypted-swap', 'started-installing'):
        osextras.unlink_force(os.path.join('/var/lib/ubiquity', name))
    shutil.rmtree("/var/lib/partman", ignore_errors=True)
    misc.remove_os_prober_cache()

    if oem_config and not options.query:
        disable_autologin()

    if args:
        install(args[0], query=options.query)
    else:
        install(query=options.query)

    if oem_config:
        run_oem_hooks()
    im_switch.kill_im()


if __name__ == '__main__':
    # Are we running as ubiquity or oem-config?
    oem_config = False
    script_name = os.path.basename(sys.argv[0])
    if script_name == 'oem-config':
        oem_config = True

    main(oem_config)

# vim:ai:et:sts=4:tw=80:sw=4:
