#!/usr/bin/env python

################################################################################
# Ganga Project. http://cern.ch/ganga
#
# $Id: ganga,v 1.1 2008-07-17 16:40:05 moscicki Exp $
################################################################################

""" Executable for starting Ganga

    If a Python script is given as argument then it is executed
    within the Ganga environment. 

    If no argument is given then the Python interpreter is invoked
    within the Ganga environment"""

# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Perform setup needed for using Ganga Public Interface (GPI)
# This is a Copy/Paste logic which must stay in THIS file

from __future__ import print_function


def standardSetup():
    """Function to perform standard setup for Ganga.
    """   
    import sys, os.path

    # insert the path to Ganga itself
    exeDir = os.path.abspath(os.path.normpath(os.path.dirname(os.path.realpath(__file__))))

    gangaDir = os.path.join(os.path.dirname(exeDir), 'python' )

    sys.path.insert(0, gangaDir)

    from Ganga.PACKAGE import standardSetup
    standardSetup()

standardSetup()
del standardSetup
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

from Ganga.Core.exceptions import GangaException
import Ganga.Runtime
Ganga.Runtime._prog = None
import sys

def log(level, err):
    # FIXME: for some reason self.logger.critical does not print any
    # messages here
    if level == 'DEBUG':
        sys.stderr.write(str(err)+'\n')
        import traceback
        traceback.print_exc(file=sys.stderr)
    else:
        sys.stderr.write(str(err)+'\n')
        sys.stderr.write('(consider --debug option for more information)\n')

try:
    # Import GPI and run Ganga
    Ganga.Runtime.setupGanga()
    from Ganga import GPI
    Ganga.Runtime._prog.run(GPI.__dict__)
except GangaException as err:
    if Ganga.Runtime._prog:
        log(Ganga.Runtime._prog.options.force_loglevel, err)
    sys.exit(-1)

