#!/usr/bin/python3
import apt
import apt.cdrom
import aptsources.sourceslist
import gettext
import os
import sys
import time

from gi.repository import Gtk
_ = gettext.gettext
gettext.textdomain("langpack-installer")

if os.environ['LANG'].startswith("en_"):
    sys.exit(0)

dialog = Gtk.Dialog(parent=None, flags=Gtk.DialogFlags.MODAL)

dialog.add_button(Gtk.STOCK_YES, Gtk.ResponseType.ACCEPT)
dialog.add_button(Gtk.STOCK_NO, Gtk.ResponseType.REJECT)
dialog.set_title(_("Edubuntu live desktop translations."))

label = Gtk.Label()
label.set_markup(_("""
The live session doesn't include the translations for your language by default.
These can be installed from the installation media now so you can try Edubuntu
in your language.

However, this will use up to 150MB of RAM and can be a problem on low memory
systems.

Do you want to install these extra translations?""").strip())
label.set_padding(12, 12)

dialog.vbox.pack_start(label, True, True, 0)
dialog.set_resizable(False)
dialog.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
dialog.set_modal(True)
dialog.show_all()

if dialog.run() == Gtk.ResponseType.REJECT:
    sys.exit(0)
dialog.destroy()

while Gtk.events_pending():
    Gtk.main_iteration();

# Get the needed package list
import language_support_pkgs
pkg_depends = "/usr/share/language-selector/data/pkg_depends"
ls = language_support_pkgs.LanguageSupport(None, pkg_depends)
packages = ls.by_locale(os.environ['LANG'], False)

# Comment all non-cdrom sources
sources = aptsources.sourceslist.SourcesList()
sources.backup("langpack")
for entry in sources:
    if not entry.line.startswith("deb cdrom") and not entry.invalid:
        entry.set_enabled(False)
sources.save()

# Refresh the cache
cache = apt.Cache()
cache.update()

# Mark the packages for installation
for pkg in packages:
    if pkg in cache:
        cache[pkg].mark_install()

print("changes: %s" % cache.get_changes())
print("%s will be required" % cache.required_space)

# Install them
cache.commit()

# Cleanup
sources.restore_backup("langpack")
