#!/usr/bin/python3
# Mythbuntu Live CD Session Startup Script
# Copyright (C) 2007, Mario Limonciello <superm1@mythbuntu.org>
#
#
# Exit error codes:
# 0: normal exit
# 1: permissions error
# 2: --help called
# 3: didn't find file
#
#
# 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 3 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


#Text backend requirements
import os
import subprocess
import sys

#Gui requirements
from gi.repository import Gtk

#For TZ fixup
import MythTV
import time

from mythbuntu_common.mysql import MySQLHandler

# Define global path
PATH = '/usr/share/mythbuntu/ui'
UBIQUITY_PATH = '/usr/share/ubiquity/gtk'

UBIQUITY_PAGE = 'mythbuntu_stepPasswords'

class MythbuntuStartup():
    def __init__(self):
        #initialize gui
        top_builder = Gtk.Builder()
        top_builder.add_from_file('%s/mythbuntu_live_autostart.ui' % PATH)

        vbox = top_builder.get_object('vbox')
        ubiquity_builder = Gtk.Builder()
        ubiquity_builder.add_from_file("%s/%s.ui" %(UBIQUITY_PATH, UBIQUITY_PAGE))
        ubiquity_page = ubiquity_builder.get_object(UBIQUITY_PAGE)
        vbox.add(ubiquity_page)

        #set icon
        if os.path.exists('/usr/share/pixmaps/mythbuntu.png'):
            Gtk.Window.set_default_icon_from_file('/usr/share/pixmaps/mythbuntu.png')
        elif os.path.exists('/usr/share/icons/Human/48x48/places/start-here.png'):
            Gtk.Window.set_default_icon_from_file('/usr/share/icons/Human/48x48/places/start-here.png')

        #make widgets referencable from top level
        for builder in [top_builder, ubiquity_builder]:
            for widget in builder.get_objects():
                if not isinstance(widget, Gtk.Widget):
                    continue
                widget.set_name(Gtk.Buildable.get_name(widget))
                setattr(self, widget.get_name(), widget)
            builder.connect_signals(self)

        self.mysql=MySQLHandler()

        #for some reason, that above initialization doesn't catch the about
        #dialog, so we need to manually do it too
        setattr(self, "about_dialog", builder.get_object("about_dialog"))

    def fixup_timezone(self):
        """Queries the backend for the TZ and sets it properly for the FE"""
        mythtv=MythTV.MythBE()
        os.environ['TZ']=tz=mythtv.backendCommand('QUERY_TIME_ZONE').split('[]:[]')[0]
        time.tzset()

    def start_frontend(self):
        """Starts the frontend"""
        start_command = ["mythfrontend.real", "--logfile", "/tmp/mythfrontend.log"]
        self.main_window.hide()
        while Gtk.events_pending():
            Gtk.main_iteration()
        subprocess.call(start_command)

#Callback handlers
    def run(self):
        """Runs the PyGTK gui for the user"""
        self.main_window.show()
        Gtk.main()

    def do_connection_test(self,widget):
        """Tests to make sure that the backend is accessible"""
        if widget is not None:
            if not os.path.exists(os.path.join(os.environ['HOME'],'.mythtv')):
                os.makedirs(os.path.join(os.environ['HOME'],'.mythtv'))
            result = self.mysql.do_connection_test(self.security_entry.get_text())
            if not result:
                result = "Success"
                self.start.set_sensitive(True)
            self.connection_results.set_text(result)
            self.connection_results_label.show()

    def menu_clicked(self,widget):
        """Catches signals sent from all menu items"""
        if (widget is not None and widget.get_name() == 'quit_menuitem'):
            self.destroy(None)
        elif (widget is not None and widget.get_name() == 'about_menuitem'):
            self.about_dialog.run()
            self.about_dialog.hide()

    def start_session(self,widget=None):
        """Starts the session"""
        self.fixup_timezone()
        self.start_frontend()
        sys.exit(0)

    def destroy(self, widget, data=None):
        Gtk.main_quit()

    def display_error(self,message):
        """Displays an error message"""
        dialog = Gtk.MessageDialog(self.main_window, Gtk.DialogFlags.MODAL,
                                   Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE,
                                   message)
        dialog.run()
        sys.exit(1)

def display_help():
    """Shows the help for this application"""
    print("")
    print("mythbuntu-startup is used to create and run a custom Mythbuntu Live Session")
    print("")
    print("USAGE:")
    print("")
    print("mythbuntu-startup [--help]")
    print("    Display this help")
    print("")
    print("mythbuntu-startup")
    print("    Opens the GUI and allows you to input a security key")
    sys.exit(2)

if __name__ == '__main__':

    for arg in sys.argv:
        if arg == "--help" or arg == "-help" or arg == "--h" or arg == "-h":
            display_help()

    mythbuntu = MythbuntuStartup()
    mythbuntu.run()
