#!/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

from umitCore.Name import APP_NAME, APP_DISPLAY_NAME
from umitCore.UmitOptionParser import option_parser

DEVELOPMENT = os.environ.get(APP_NAME.upper() + "_DEVELOPMENT", False)

if not DEVELOPMENT:
    from tempfile import mktemp
    # Generating temporary files names
    stdout_output = mktemp()
    stderr_output = mktemp()

    old_stdout = sys.stdout
    old_stderr = sys.stderr

    _stdout = open(stdout_output, "w")
    _stderr = open(stderr_output, "w")

    sys.stdout = _stdout
    sys.stderr = _stderr

    # This will catch exceptions and send them to bugzilla
    def excepthook(type, value, tb):
        if type == type(ImportError):
            sys.exist(1)

        import traceback
        import gtk

        from umitCore.I18N import _
        from umitCore.Version import VERSION
        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\
SYS.PLATFORM: %s\n\
OS.NAME: %s\n\
%s Version: %s\n\
%s\nSTDOUT\n%s\n\n\
%s\nSTDERR\n%s\n\nHOOK:\n%s" % \
        (sys.platform, os.name,
         APP_DISPLAY_NAME,
         VERSION, "-"*80,
         open(stdout_output).read(),
         "-"*80,
         open(stderr_output).read(),
         hook)

        report_result = False
        try:
            old_stdout.write("Bug reported!")
            c = CrashReport("%s Crash - '%s'" % (APP_DISPLAY_NAME, value), 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 %s 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""") % (APP_DISPLAY_NAME, 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 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
    app = App()

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

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

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