#!/usr/bin/env python
# -*- coding: utf-8; Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*-

# Copyright (C) 2012 Canonical Ltd.
# Written by Yu Ning <ning.yu@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

import os

import debconf

from ubiquity import plugin
from ubiquity import misc

NAME = 'apt-setup'
AFTER = 'timezone'
WEIGHT = 10

class Install(plugin.InstallPlugin):
    def prepare(self, unfiltered=False):
        # TODO: check debian-installer/{locale,country}
        self.db.reset('mirror/country')

        path = os.environ['PATH']
        path = '/usr/lib/ubiquity/apt-setup:' + path
        path = '/usr/lib/ubiquity/choose-mirror:' + path

        environ = {}
        environ['OVERRIDE_BASE_INSTALLABLE'] = '1'
        environ['PATH'] = path

        return (['/usr/lib/ubiquity/apt-setup/apt-setup', '--log-output'],
                [], environ)

    def install(self, target, progress, *args, **kwargs):
        if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
            progress.info('ubiquity/install/apt-setup')

            sourceslist = target + '/etc/apt/sources.list'
            backup = sourceslist + '.old'

            # backup original sources.list
            if os.access(sourceslist, os.F_OK):
                os.rename(sourceslist, backup)

            # create an empty sources.list
            with open(sourceslist, 'w'):
                # nothing to do
                pass

            rv = plugin.InstallPlugin.install(self, target, progress, *args, **kwargs)
            if rv:
                # failed. restore from backup
                if os.access(sourceslist, os.F_OK):
                    os.unlink(sourceslist)
                if os.access(backup, os.F_OK):
                    os.rename(backup, sourceslist)
            else:
                # succeed. remove backup
                if os.access(backup, os.F_OK):
                    os.unlink(backup)

                # disable CD image in sources.list:
                misc.execute('chroot', target, 'sed', '-i',
                        '/^deb cdrom:/s/^/#/', '/etc/apt/sources.list')

            return rv

# vim: set sts=4 sw=4 et:
