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


# Launch the Python-Tkinter Hypatheon client

import os, sys, time, glob, subprocess

PVSPATH = os.environ.get('PVSPATH', '')
PVS_LIBRARY_PATH = os.environ.get('PVS_LIBRARY_PATH')
HYPATHEON = os.environ.get('HYPATHEON', '')
if not HYPATHEON and sys.argv[0]:
    HYPATHEON = os.path.abspath(sys.argv[0] + '/../..')

if PVSPATH:
    core_libs = [os.path.join(PVSPATH, 'lib')]
    if PVS_LIBRARY_PATH:
        all_paths = PVS_LIBRARY_PATH.split(':') + core_libs
    else:
        all_paths = core_libs

    if not HYPATHEON:
        for p in all_paths:
            hyp_dir = glob.glob(os.path.join(p, 'Hypatheon'))
            if hyp_dir:
                HYPATHEON = hyp_dir[0]
                break

if not HYPATHEON:
    print 'ERROR: The Hypatheon directory was not found.'
    print 'Try setting the HYPATHEON environment variable.'
    sys.exit(1)

os.environ['HYPATHEON'] = HYPATHEON

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

print '''The Hypatheon process has been started.
Its window should appear in a few seconds.'''

spawn_stderr = os.path.join(HYPATHEON, 'log', 'spawn_stderr')

# The client logs its own stderr but here we collect errors that
# issue from processes spawned by the client.

on_osx = sys.platform      == 'darwin'

# Environment variable PYTHON_BINARY can be set to override the
# default version of Python on the user's platform.

python_cmd = os.environ.get('PYTHON_BINARY')
if not python_cmd:
    python_cmd = 'pythonw' if on_osx else 'python'

cmd_template = '''echo "Starting Hypatheon client session on %s.
" >> "%s"
export PYTHONPATH="$HYPATHEON"/lib
%s -u "%s" 0 2>> "%s" &'''

launch_cmd = cmd_template % (time.asctime(),
                             spawn_stderr,
                             python_cmd,
                             os.path.join(HYPATHEON, 'client', 'hypatheon.py'),
                             spawn_stderr)
subprocess.call(launch_cmd, shell=True)
