#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
gtk.glade.textdomain("displayconfig-gtk")
import gobject

import sys, os

from gettext import gettext as _
import gettext
gettext.textdomain("displayconfig-gtk")

(RESPONSE_CONFIGURE,
 RESPONSE_CONTINUE,
 RESPONSE_SHUTDOWN) = range(3)

class FailSafeOptions(object):
    def __init__(self):
        self.xconfigpath = "/etc/X11/xorg.conf"
        self.failsafemode = os.getenv("BPX_XORG_CONF", "%s.failsafe" % self.xconfigpath)
        self.pcitable = None
        self.dumpfile = None
        self.locationspath = "/var/lib/displayconfig-gtk/locations.conf"
        self.datadir = "/usr/share/displayconfig-gtk"
        self.instantapply = False

class FailSafeDialog:
    def __init__(self):
        self.options = FailSafeOptions()
        # Homage to glade
        gtk.window_set_default_icon_name("display-capplet")
        header = _("Ubuntu is running in low-graphics mode")
        msg = _("Your screen and graphics card could not be detected "
                "correctly. To use higher resolutions, visual effects "
                "or multiple screens, you have to configure the display "
                "yourself.")
        dia = gtk.Dialog(parent=None)
        dia.realize()
        dia.set_position(gtk.WIN_POS_CENTER)
        dia.window.set_functions(gtk.gdk.FUNC_MOVE)
        dia.add_button(_("C_onfigure..."), RESPONSE_CONFIGURE)
        dia.add_button(_("_Shut Down"), RESPONSE_SHUTDOWN)
        dia.add_button(_("_Continue"), RESPONSE_CONTINUE)
        dia.set_default_response(RESPONSE_CONTINUE)
        dia.set_has_separator(False)
        dia.set_resizable(False)
        dia.set_title("")
        dia.set_border_width(6)
        dia.vbox.set_spacing(12)
        vbox = gtk.VBox()
        vbox.set_spacing(12)
        hbox = gtk.HBox()
        hbox.set_spacing(12)
        img = gtk.image_new_from_stock(gtk.STOCK_DIALOG_WARNING,
                                       gtk.ICON_SIZE_DIALOG)
        img.set_alignment(0, 0)
        dia.vbox.pack_start(hbox)
        hbox.set_border_width(6)
        hbox.pack_start(img, expand=False)
        label = gtk.Label()
        label.set_line_wrap(True)
        label.set_markup("<b><big>%s</big></b>\n\n%s" % (header, msg))
        label.set_alignment(0, 0)
        vbox.pack_start(label)
        check = gtk.CheckButton(_("_Always run in low-graphics mode"))
        vbox.pack_start(check)
        hbox.pack_start(vbox)
        dia.show_all()
        res = dia.run()
        dia.hide()
        if res == RESPONSE_CONFIGURE:
            # The users wants to configure the system
            self.run_displayconfig()
            print "configure"
        elif res == RESPONSE_CONTINUE:
            if check.get_active():
                self.use_failsafe_as_default()
                print "persistent"
            else:
                print "temporarily"
                sys.exit()
        elif res == RESPONSE_SHUTDOWN:
            print "shutdown"
            os.system("/sbin/shutdown -h now")

    def use_failsafe_as_default(self):
        if not os.path.exists(self.options.failsafemode):
            # Without a failsafe xorg, nothing we can do
            header = _("Failsafe mode configuration is not available")
            msg = "%s\n%s" % (_("The file '%s' is missing. ") % self.options.failsafemode,
                              _("Please check your system for software "
                                "installation or file system errors."))
            dia = gtk.MessageDialog(parent=None,
                                    flags=0,
                                    type=gtk.MESSAGE_ERROR,
                                    buttons=gtk.BUTTONS_CLOSE,
                                    message_format=header)
            dia.format_secondary_text(msg)
            dia.run()
            # FIXME: Perhaps we should disable gdm or allow to start an editor
            sys.exit(1)
        else:
            if os.path.exists(self.options.xconfigpath):
                try:
                    # Save user's current xorg.conf
                    os.rename(self.options.xconfigpath, 
                              "%s.broken" % self.options.xconfigpath)
                except (OSError, os.error), why:
                    header = _("Backup of the current configuration failed")
                    msg = _("Please check your system for software "
                            "installation or file system errors.")
                    dia = gtk.MessageDialog(parent=None,
                                            flags=0, 
                                            type=gtk.MESSAGE_ERROR, 
                                            buttons=gtk.BUTTONS_CLOSE,
                                            message_format=header)
                    dia.format_secondary_text(msg)
                    dia.run()
                    sys.exit(1)
            try:
                # Switch to this failsafe xorg.conf
                os.rename(self.options.failsafemode, "/etc/X11/xorg.conf")
            except (OSError, os.error), why:
                header = _("Saving failsafe mode configuration as "
                           "default failed")
                msg = "%s\n%s" % (_("Please check your system for "
                                    "software installation or file system "
                                    "errors."),
                                  str(why))
                dia = gtk.MessageDialog(parent=None,
                                        flags=0, 
                                        type=gtk.MESSAGE_ERROR, 
                                        buttons=gtk.BUTTONS_CLOSE,
                                        message_format=header)
                dia.format_secondary_text(msg)
                dia.run()
                sys.exit(1)

    def run_displayconfig(self):
        from displayconfiggtk.DisplayConfig import DisplayConfig
        app = DisplayConfig(self.options)
        app.run()

def main():
    app = FailSafeDialog()

if __name__ == "__main__":
    main()
# vim:ts=4:sw=4:et
