#!/usr/bin/python2.4

import sys, os
import logging, signal
import gettext
import locale
import codecs

LOGGING_LEVEL = logging.INFO
ALLOWED_LANGUAGES = ('en', 'ja')


if __name__ == '__main__':
    """
    Set up environment for n1sh loop.

    Strip out non-n1sh command line options:
        * --debug:  Turns on logging to stderr.  Redirect stderr
          to a file to capture.  (n1sh --debug 2> logfile.out)
        * --nocacao:  Use non-cacao executor which loads tabdata
          from "n1sh.xml" file in current directory.

    Configure gettext for the rest of the app.
    """


    # Ignore <ctrl>-C.
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    # Adjust search path to include rest of n1sh files.
    # Note:  If using symlinks for n1sh.py, the "sys.path[0]" trick may not
    #        work.  Use the commented out line (hardcoded path) instead.
    #sys.path.append(os.path.join(sys.path[0], 'cli'))
    sys.path.append('/opt/sun/n1gc/bin/cli')

    # Import the rest of the N1 modules.
    import n1shmain
    import n1common

    # Add some codec aliases.  (See n1common.ENC_ALIASES for list.)
    codecs.register(n1common.enc_alias)

    #
    # Collect args.
    argv = sys.argv[1:]

    # Configure logger.  Off by default, prints to stderr otherwise.
    logger = logging.getLogger()
    try:
        argv.remove('--debug')

        handler = logging.StreamHandler()
        #formatter = logging.Formatter(
        #    '%(levelname)s [%(filename)s:%(lineno)d]\n%(message)s')
        formatter = logging.Formatter('[%(levelname)8s] %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        logger.setLevel(LOGGING_LEVEL)
    except ValueError:
        # Disable the root logger.
        logger.setLevel(sys.maxint)

    # Choose which executor to use.
    try:
        argv.remove('--nocacao')
        n1shmain.USE_CACAO = False
    except ValueError:
        pass


    #
    # Set up locale and message catalog.
    """
    Note on supported languages:
    Any languages which are to be supported should have a valid
    lang_region and lang_region.UTF-8 locales.  (e.g. en_US and
    en_US.UTF-8)  Those languages that don't will need special
    consideration in CacaoExecutor.start() in executor.py.
    """

    # Make sure locale is set correctly.
    lang = ''     # Terminal language, used by executor
    termenc = ''  # Terminal encoding, used in n1shmain for codecs.writer
    try:
        loc = locale.normalize(locale.setlocale(locale.LC_MESSAGES, ''))
        logging.info('LC_MESSAGES = %s' % loc)
        try:
            lang, termenc = loc.split('.', 1)   # Language, terminal encoding
            termenc = termenc.split('@', 1)[0]  # Strip off comment
        except ValueError:
            lang = loc
            termenc = ''

        lang_base = lang.split('_', 1)[0]

        # Some "en" language regions aren't supported on all systems,
        # so force any "en" locales into "en_US".
        if lang_base not in ALLOWED_LANGUAGES \
                or lang_base == 'en':
            # Set to a default locale if none set.  Let system determine
            # the default encoding.
            lang = 'en_US'

            logging.info('Locale "%s" not in %s.  Using "%s".'
                         % (loc, str(ALLOWED_LANGUAGES), lang))
            locale.setlocale(locale.LC_MESSAGES, lang)

        if not termenc:
            termenc = locale.getpreferredencoding()
            logging.info('No terminal encoding found, using preferred "%s"'
                         % termenc)

        # Make sure codec exists and locale is known.
        codecs.lookup(termenc)
        locale.getlocale(locale.LC_MESSAGES)

    except (locale.Error, ValueError):
        logging.error('Locale error; start trace', exc_info=True)
        print 'The current locale is not supported.'
        sys.exit(n1shmain.CODE_INTERNAL_ERROR)
    except LookupError:
        logging.error('Encoding error; start trace', exc_info=True)
        print 'The current encoding "%s" is not supported.' % termenc
        sys.exit(n1shmain.CODE_INTERNAL_ERROR)

    langvar = 'LANGUAGE'
    try:
        l = locale.getlocale(locale.LC_MESSAGES)[0]
        language = os.environ[langvar].split('.')[0]
        logging.info('%s = %s; should be "%s"' % (langvar, language, l))
        if language != l:
            raise locale.Error  # Borrow so we don't need our own exception.
    except (KeyError, locale.Error):
        # Use the current locale (which may be from default) to
        # set 'langvar' environment variable for the duration of this run.
        l = locale.getlocale(locale.LC_MESSAGES)
        os.environ[langvar] = '%s' % (l[0])
        logging.info('Setting default %s = "%s"'
                     % (langvar, os.environ[langvar]))


    # Note:  If using symlinks for n1sh.py, the "sys.path[0]" trick may not
    #        work.  Use the commented out line (hardcoded path) instead.
    #gettext.bindtextdomain('n1sh', os.path.join(sys.path[0], 'cli/locale'))
    gettext.bindtextdomain('n1sh', '/opt/sun/n1gc/bin/cli/locale')
    gettext.textdomain('n1sh')

    logging.info('gettext binding: %s' % (gettext.bindtextdomain('n1sh')))


    # Done configuring.  Engage!
    status = n1shmain.main(argv, (lang, termenc))
    sys.exit(status)




