#! /bin/sh
# encoding: utf-8
# Title: generic ArtCom start wrapper for all applications written in Python
# *** NOTE: The sourcecode of applications is found in bits/python/
#
# The following magic is needed as a safeguard to make sure that a reasonable
# error message is displayed if the required python2.7 is not available 
# on the target Linux system.
# The shell passes all arguments over to the Python interpreter running the
# same file here.  The following line is the start of a long multiline doc 
# string in Python syntax and a NOP statemenet in Shell syntax.
""":"
PATH=$PATH:/usr/local/bin
if which python2.7 >/dev/null
then exec python2.7 $0 ${1+"$@"}
else echo "python2.7 is missing on your system!
Please reinstall the ArtCom software."
     exit 1
fi
"""
__doc__ = """generic application starter; uses the call name to figure out, what to do

This file is placed in a directory sibling our python directory.  Normally
this will be /opt/artcom/current/bin with our python resources living in
/opt/artcom/current/python.
At this bin-destination directory it should be linked to many names:
It should be linked to the name of any application to call or it should
be called startXXXX, startYYYY, startZZZZ where XXXX, YYYY, ZZZZ are the
names of the application modules to start.
This directory should be in $PATH"""
#  Created      :       Wed, 19-Jan-2000 / 17:12 / (pf)
#  Version      : $Id: start.py,v 1.12 2017-03-23 10:11:01 hz Exp $
import os, sys, string

__version__ = "$Revision: 1.12 $"[11:-2]
__author__ = "Peter Funk"

def adjust_sys_path(application_home, verbose=0):
    """insert directories into sys.path required to import other modules

    Assume a standard subdirectory tree organisation on Unix/Linux."""
    possibilities = [
        (application_home, "python", "lib"),
    ]
    if os.name == "posix":
        # Allow users to use there own private plugins:
        if os.environ.has_key("HOME"):
            possibilities.append((os.environ["HOME"], ".acpyplugins"))
    else:
        possibilities.extent([("plugins",), ("artcom",), ("python", "lib"),])
    for d in possibilities:
        d = os.path.abspath(os.path.normpath(apply(os.path.join, d)))
        if not d in sys.path and os.path.isdir(d):
            if verbose: print "use  path:", d
            sys.path.insert(0, d)
        elif verbose: print "skip path:", d
    if verbose: print "resulting sys.path:", sys.path

def mangle_called(argv0):
    called_in, called_as = os.path.split(argv0)
    called_in = os.path.abspath(called_in)
    if called_in[-3:] == "bin": # standard Unix/linux installation
        application_home = os.path.normpath(os.path.join(called_in, os.pardir))
    else:
        application_home = called_in
    # Get rid of the .py extension, if the command has one
    called_as, dot_py = os.path.splitext(called_as)
    return (application_home, called_as)

def import_and_call(called_as):
    try:
        module = __import__(called_as)
    except ImportError:
        if called_as[:len('start')] == 'start':
            called_as = called_as[len('start'):]
            if verbose:
                print "trying again with substring 'start' teared of the name:",
                print called_as
            if called_as:
                module = __import__(called_as)
            else:
                raise # reraise the ImportError, no way to find module
        else:
            sys.stderr.write("sys.path = "+str(sys.path)+"\n")
            raise # reraise the ImportError after showing the sys.path
    if hasattr(module, 'main'):
        module.main(sys.argv)

if __name__ == "__main__":
    application_home, called_as = mangle_called(sys.argv[0])
    verbose = "-v" in sys.argv[1:] or os.environ.has_key("DBG_SH") # nostalgic
    adjust_sys_path(application_home, verbose=verbose)
    if not os.environ.has_key("BITSLIB"):
        # Initialize the standard ArtCom environment first:
        import acstd
    import_and_call(called_as)
else:
    # Importing this file as Python module doesn't make any sense.
    # So don't link to this file to a filename with a '.py' suffix
    raise SystemExit, "***Error: Don't import start.py as a module."

# vim: set et sw=4 sts=4 tw=78 nowrap fo+=l:
