#!/usr/bin/env python

'''
    Porthole
    A graphical frontend to Portage

    Copyright (C) 2003 - 2004 Fredrik Arnerup and Daniel G. Taylor

    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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'''

APP = 'porthole'

# setup our path so we can load our custom modules
from sys import path
#path.append('/usr/lib/porthole')

# Add path to portage module if 
# missing from path (ref bug # 924100)

PORTAGE_MOD_PATH = '/usr/lib/portage/pym'
try:
    path.index(PORTAGE_MOD_PATH) 
except ValueError:
    path.append(PORTAGE_MOD_PATH)


pycrash_found = False
try:
    from pycrash.utils import *
    pycrash_found = True
    class MyCrash(HTMLPyCrash):
        #def onExit(self):
	def onExceptionRaised(self, time):
	    save_file = "/var/log/porthole/crash.html"
	    # saveToFile does not yet return a result: feature request submitted
	    self.saveToFile(save_file)
	    print "PORTHOLE: Crash detected.  Please submit a bug report &"
	    print "         include the " + save_file
except ImportError:
    print "pycrash module not found.  For best debug info Please emerge >= dev-python/pycrash-0.4pre2"
    

from thread import *
from sys import argv, exit, stderr
import pygtk; pygtk.require("2.0") # make sure we have the right version
import gtk, time
from getopt import getopt, GetoptError
import locale, gettext

def usage():
    tabs = "\t\t"
    print "Usage: porthole [OPTION...]\n"
    print "  -h, --help" + tabs + "Show this help message"
    print "  -l, --local" + tabs + \
          "Run a local version (use modules in current directory)"
    print "  -v, --version" + tabs + "Output version information and exit"
    print "  -d, --debug" + tabs + "Output debugging information to stderr (terminal)"
    print "             " + tabs + "Also if PyCrash-0.4pre3 or newer is found it will use it"
    print "             " + tabs + "to try to save additional crash info to send in for debugging"



if __name__ == "__main__":
    try:
        opts, args = getopt(argv[1:], 'lvdh', ["local", "version", "debug",
                                              "help"])
    except GetoptError, e:
        print >>stderr, e.msg
        exit(1)
    # run thru the options and set the DATA_PATH & imported modules properly
    # bug ==> any porthole script can be used to load both --local and installed modules
    path_set = False
    for opt, arg in opts:
        if opt in ("-l", "--local"):
            # running a local version (i.e. not installed in /usr/*)
            from os import getcwd
            DATA_PATH = getcwd() + "/"
	    from version import version
	    import utils as _utils
	    from mainwindow import MainWindow
	    i18n_DIR = DATA_PATH + 'i18n'

	    path_set = True

    if not path_set: # then run the installed modules
	try:
	    from porthole.version import version
	    # set data path for our glade and pixmap files
	    DATA_PATH = "/usr/share/porthole/"
	    from porthole import utils as _utils
	    from porthole.mainwindow import MainWindow
	    i18n_DIR = DATA_PATH + 'i18n'
	except:
	    print "NO installed porthole modules found!   Please run with the --local flag"

    for opt, arg in opts:
        if opt in ("-v", "--version"):
            # print version info
            print "Porthole " + version
            exit(0)
        elif opt in ("-d", "--debug"):
            _utils.debug = True
            _utils.dprint("Debug printing is enabled")
        elif opt in ("-h", "--help"):
            usage()
            exit()
 
    locale.setlocale (locale.LC_ALL, '')
    gettext.bindtextdomain (APP, i18n_DIR)
    gettext.textdomain (APP)
    gettext.install (APP, i18n_DIR, unicode=1)
    gtk.glade.bindtextdomain (APP, i18n_DIR)
    gtk.glade.textdomain (APP)

    if pycrash_found == True:
        _utils.dprint("pycrash module initializing")
        _utils.dprint("If a crash occurs check the /var/log/porthole/crash.html file and post it to porthole bugs")
        p = MyCrash({'AppName': 'Porthole', 'Version': version, 'SendTo': 'porthole bugs'})
        p.enable() #New in PyCrash-0.4pre2
    # make sure gtk lets threads run
    gtk.threads_init()
    # setup our app icon
    myicon = gtk.gdk.pixbuf_new_from_file(DATA_PATH + "pixmaps/porthole-icon.png")
    gtk.window_set_default_icon_list(myicon)
    # load prefs
    prefs = _utils.PortholePreferences()
    prefs.DATA_PATH = DATA_PATH
    prefs.APP = APP
    prefs.i18n_DIR = i18n_DIR
    # load config info
    config = _utils.PortholeConfiguration(DATA_PATH)
    # create the main window
    myapp = MainWindow(prefs, config)
    # start the program loop
    gtk.main() # gtk.mainloop() depricated
    print "PORTHOLE: normal quit"
    # save the prefs to disk for next time
    prefs.save()
