#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (C) 2005 Insecure.Com LLC.
#
# Authors: Adriano Monteiro Marques <py.adriano@gmail.com>
#          Cleber Rodrigues <cleber.gnu@gmail.com>
#          Frederico Silva Ribeiro <ribeiro.fsilva@gmail.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

import os
import sys
import signal
import webbrowser
from os.path import split

# This will get modified
MODULE_DIR = "/usr/lib/python2.5/site-packages"

sys.path.append(MODULE_DIR)

UMIT_DEVELOPMENT = os.environ.get("UMIT_DEVELOPMENT", False)
if not UMIT_DEVELOPMENT:
    from tempfile import mktemp
    # Generating temporary files names
    stdout_output = mktemp()
    stderr_output = mktemp()

    old_stdout = sys.stdout
    old_stderr = sys.stderr
    
    sys.stdout = open(stdout_output, "w")
    sys.stderr = open(stderr_output, "w")

    # This will catch exceptions and send them to bugzilla
    def excepthook(type, value, tb):
        import traceback
        import gtk
        
        from umitCore.I18N import _
        from higwidgets.higdialogs import HIGAlertDialog
        from umitGUI.CrashReport import CrashReport

        traceback.print_tb(tb)

        sys.stdout.close()
        sys.stderr.close()

        sys.stdout = old_stdout
        sys.stderr = old_stderr

        hook = "Type: %s\nValue: %s\n" % (type, value)
        outputs = "CRASH REPORTED:\n\n\
%s\nSTDOUT\n%s\n\n\
%s\nSTDERR\n%s\n\nHOOK:\n%s" % \
                       ("-"*80,
                        open(stdout_output).read(),
                        "-"*80,
                        open(stderr_output).read(),
                        hook)

        report_result = False
        try:
            old_stdout.write("Bug reported!")
            c = CrashReport("Umit Crash - STDOUT and STDERR", outputs)
            c.show_all()
            gtk.main()
        except:
            d = HIGAlertDialog(type=gtk.MESSAGE_ERROR,
                               message_format=_("Bug not reported"),
                               secondary_text=_("""A critical error \
occourried during Umit execution,
and it was not properly reported to our bug tracker. Please,
copy the error message bellow and report it on our bug tracker.

The following error message was NOT reported:
%s""") % (outputs))
            d.run()
            d.destroy()
        else:
            # Showing a message on the terminal
            old_stdout.write("Bug reported!")
            old_stdout.write("\n")

            # Calling a browser to open the result from bug tracker
            if report_result:
                webbrowser.open("file://%s" % report_result)

    sys.excepthook = excepthook

if __name__ == '__main__':
    ######################################
    # Setting the umit home directory

    from umitCore.Paths import Path
    Path.set_umit_conf(split(sys.argv[0])[0])

    ######################################

    from umitCore.UmitLogging import log
    from umitGUI.App import App
    umit_app = App()

    if UMIT_DEVELOPMENT:
        log.critical(">>> Not in development mode.")

    if os.name == "posix":
        signal.signal(signal.SIGHUP, umit_app.safe_shutdown)

    signal.signal(signal.SIGTERM, umit_app.safe_shutdown)
    signal.signal(signal.SIGINT, umit_app.safe_shutdown)

    try:
        umit_app.run()
    except KeyboardInterrupt:
        sys.exit(signal.SIGINT)