#!/usr/bin/env python
##
## spy-i2c.py
## Started on  Tue Sept 02 15:17:28 2010
## $Id$
##
##
## Copyright (C) 2009 Aldebaran Robotics
##

import os
import sys
import subprocess
from optparse import OptionParser


#list of folder where we can find libbn-spy
libbndirs = [ os.getcwd(),
              os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..", "lib")),
              "/usr/lib/",
              "/usr/local/lib/",
              os.path.join("@CMAKE_INSTALL_PREFIX@", "lib") ]


def parseArgs(args):
  parser = OptionParser(usage="%prog [options] -- [program to launch]", version="%prog 1.0")
  parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
                    default=False, help="verbose output")
  parser.add_option("--library", action="store", type="string", dest="filename",
                    help="libbn-spy.so to be used")
  parser.add_option("--debug-level", action="store", type="string", dest="debug_level",
                    help="set DEBUG_VERBOSE level")

  (options, args) = parser.parse_args()
  if len(args) < 1:
      parser.error("you need to specify an application to run")
  return (options, args)



def execute(libbnspy, args, options):
    try:
        ldpreload = os.environ['LD_PRELOAD']
    except:
        ldpreload = ""
    if not os.path.exists(libbnspy):
        print "error " + libbnspy + " doesnt not exist"
        exit(1)
    print "preloading : " + libbnspy


    if options.debug_level is None:
      ddebug_level = "5"
    else:
      ddebug_level = options.debug_level

    os.environ['SPYI2C_FILTER']   = ""
    os.environ['LD_PRELOAD']      = libbnspy + " " + ldpreload
    os.environ['LD_LIBRARY_PATH'] = os.path.dirname(libbnspy)
    os.environ['DEBUG_VERBOSE']   = ddebug_level

    try:
      os.execvp(args[0], args)
    except (OSError):
        print "can't execute : " + args
        exit(1)



def findLibBn(libbndirs):
    libbnspy = ""
    for p in libbndirs:
        pname = os.path.join(p, "libbn-spy.so")
        if os.path.exists(pname):
            libbnspy = os.path.abspath(pname)
            break
    if (not libbnspy):
        print "can't find libbn-spy.so in :" + libbndirs
    return libbnspy;



def main(argv):
    (options, args) = parseArgs(argv)
    if (options.filename):
        libbnspy = os.path.abspath(options.filename)
    else:
        libbnspy = findLibBn(libbndirs)
    execute(libbnspy, args, options)


if __name__ == "__main__":
    main(sys.argv)


