#! /usr/bin/env python
#
# A script that runs a solver to optimize a pyomo model:
#
#   pyomo <model.py> <model.dat>
#
#  _________________________________________________________________________
#
#  Coopr: A COmmon Optimization Python Repository
#  Copyright (c) 2008 Sandia Corporation.
#  This software is distributed under the BSD License.
#  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
#  the U.S. Government retains certain rights in this software.
#  For more information, see the FAST README.txt file.
#  _________________________________________________________________________

import sys

if sys.version_info[0:2] < (2, 4):
    # Not choosing a bug fix revision b/c some distros don't update, but patch
    print "\nERROR: Pyomo requires Python 2.4 or newer"
    sys.exit(1)

from os.path import abspath, dirname
import logging
import os

Logger = logging.getLogger('Pyomo')


sys.path.insert(0, dirname(dirname(abspath(__file__))))
sys.path.append(".")
currdir = dirname(abspath(__file__))
coopr_path = dirname(currdir)
pyutilib_path = dirname(coopr_path)+os.sep+"pyutilib"
sys.path.append(coopr_path)
sys.path.append(pyutilib_path)
sys.path.append(abspath(os.getcwd()))
#
# Adjust the user path if it looks like this script is being used
# from an Acro build (adds the Acro bin directory, if it exists).
#
# Recurse up the current path, looking for a subdirectory that
# contains 'python' and 'bin'
#
curr = os.path.abspath(os.getcwd())
while os.sep in curr:
    if os.path.exists(curr+os.sep+"python") and                               \
       os.path.exists(curr+os.sep+"bin"):
        os.environ["PATH"] = curr+os.sep+"bin:"+os.environ["PATH"]
        break
    if os.path.basename(curr) == "":
        break
    curr = os.path.dirname(curr)

import coopr.pyomo.scripting.pyomo

class PyomoLogHandler ( logging.Handler ):
    def __init__ ( self, base, *args, **kwargs ):
        import logging  # why?  Shouldn't the import above be enough?
        logging.Handler.__init__(self, *args, **kwargs )

        self.basepath = base

    def emit(self, record):
        import sys   # why?  Isn't this imported above?
                     # Doesn't work w/o it though ... ?

        level    = record.levelname
        filename = record.pathname  # file path
        lineno   = record.lineno
        function = record.funcName
        msg      = record.getMessage()

        filename = filename.replace( self.basepath, '[coopr base]' )

        sys.stderr.write('%(level)s: "%(fpath)s", %(lineno)d, '               \
                         '%(caller)s\n\t%(msg)s\n' % \
            {
              'level'  : level,
              'fpath'  : filename,
              'lineno' : lineno,
              'caller' : function,
              'msg'    : msg,
            }
        )


try:
    Logger.addHandler( PyomoLogHandler(coopr_path) )
    Logger.setLevel( 30 )  # magic number to be updated via conf file soon.
    # 1 = lowest possible output.  i.e. everything

    coopr.pyomo.scripting.pyomo.run(args=sys.argv[1:])
except SystemExit:
    pass
