#! /usr/bin/env python

# Copyright (c) 2012 United States Government as represented by
# the National Aeronautics and Space Administration.  No copyright
# is claimed in the United States under Title 17, U.S.Code. All Other
# Rights Reserved.
#
# The software in this package has been released as open-source software
# under the NASA Open Source Agreement.  See the accompanying file
# NASA_Open_Source_Agreement.pdf for a full description of the terms.


# Perform Hypatheon library indexing in a background process.

# Args: collec_name, db_version, library_names, action="index",
#       delay=0, notify_flag=0, purge_old=0, update_stats=0, ordered=0

# If library_names is an absolute path name with extension '.all',
# it represents a manifest file containing library names.

# notify_flag is set to 1 to receive progress reports on
# standard output (intended for use with client).  Set flag to 0
# for batch use.  Set flags purge_old and update_stats to 0
# for quick indexing mode.

import os, sys, time

from StringIO import StringIO
from traceback import print_exc

trace = StringIO()

HYPATHEON = os.environ['HYPATHEON']

for dir in ('index', 'lib',):
    sys.path.insert(0, os.path.join(HYPATHEON, dir))

#err_log_path = os.path.join(HYPATHEON, 'log', 'index_err_log')
#sys.stderr = open(err_log_path, 'a')

# Reset Emacs path variables so the batch invocation of PVS
# won't inherit path lists for the wrong version of Emacs
# (mostly needed for OS X).
# Found the following problematic variables empirically.

for var in ('EMACSPATH', 'EMACSLOADPATH', 'EMACSDOC'):
    try:
        del os.environ[var]
    except KeyError:
        pass    # OK if it's missing


# Open new section of error log.

print >> sys.stderr, \
      "\n===== Starting Hypatheon indexing job on %s. =====\n" % \
      time.asctime()

# Check if we have a manifest file present instead of a list of library
# names.  If so, parse the library names within the file.  For every line
# beginning with an alphabetic character, its first word/identifier is
# assumed to be a library name.

lib_names = sys.argv[3]
if os.path.isabs(lib_names) and os.path.splitext(lib_names)[1] == '.all':
    lines = [ line.strip() for line in file(lib_names).readlines() ]
    words = [ line.split()[0] for line in filter(None, lines) ]
    name_list = [ name for name in words if name[0].isalpha() ]
    from preference_utilities import user_prefs
    try:
        excluded = eval(user_prefs.get('Indexing', 'excluded_libraries'))
        name_list = [ n for n in name_list if n not in excluded ]
        if excluded:
            print >> sys.stderr, \
                '*** Libraries %s\n*** are excluded by user preference.\n' \
                % excluded
    except:     # syntax and semantics errors
        print >> sys.stderr, \
            "*** The preference item 'excluded_libraries' is malformed.\n" \
            "*** Using the Client, edit the user preferences as needed."
    names = ' '.join(name_list)
    arg_list = sys.argv[1:3] + [names] + sys.argv[4:]
else:
    arg_list = sys.argv[1:]

print >> sys.stderr, 'Args: ', arg_list, '\n'
    
# ------

# Start the indexing function, directing messages to stderr.

try:
    import indexing_services
    if len(sys.argv) > 6:
        indexing_services.init_services(sys.argv[6])  # arg: client_mode/notify
    code = indexing_services.index_and_delete(*arg_list)
except SystemExit, code:
    pass
except Exception, exc_obj:
    print_exc(20, trace)
    print >> sys.stderr, \
          '*** Unhandled exception in indexing process:\n%s' % \
          ' ; '.join([ str(a) for a in exc_obj.args ])
    print >> sys.stderr, trace.getvalue()
    print >> sys.stderr, '\nSee file log/index_err_log for details.'
#    print >> sys.stderr, '\nSee file %s for details.' % err_log_path
    code = 3

sys.exit(code)
