#!@PYTHON_EXECUTABLE@

# set environment variables

from __future__ import print_function

import os, subprocess, sys
from optparse import OptionParser

# the environment needed to find the lib depend on the system
# I'm really not sure that's needed on all the systems...
# TODO: can we replace os.name by os.uname()[0] for all systems ?
env_lib_path = {"posix": "LD_LIBRARY_PATH", "mac": "DYLD_LIBRARY_PATH", "nt": "PATH"}[os.name]
# the environment needed to find the lib depend on the system
if os.name == "posix":
  if os.uname()[0] == "Darwin" :
    env_lib_path = "DYLD_LIBRARY_PATH"
  else :
    env_lib_path = "LD_LIBRARY_PATH"
elif os.name == "nt":
  env_lib_path = "PATH"
else:
  raise "Please add the library path for your system."
lib_path_list = "@PYTHON_TEST_LIB_PATH@".split(';')
if os.environ.has_key(env_lib_path) :
  os.environ[env_lib_path] = os.pathsep.join(lib_path_list + [os.environ[env_lib_path]])
else:
  os.environ[env_lib_path] = os.pathsep.join(lib_path_list)

env_python_path = "PYTHONPATH"
python_path_list = "@PYTHON_TEST_PYTHON_PATH@".split(';')
if os.environ.has_key(env_python_path) :
  os.environ[env_python_path] = os.pathsep.join(python_path_list + [os.environ[env_python_path]])
else:
  os.environ[env_python_path] = os.pathsep.join(python_path_list)

env_wrapitk_python_path = "WRAPITK_PYTHON_PATH"
wrapitk_python_path_list = "@PYTHON_TEST_WRAPITK_PYTHON_PATH@".split(';')
if os.environ.has_key(env_wrapitk_python_path) :
  os.environ[env_wrapitk_python_path] = os.pathsep.join(wrapitk_python_path_list + [os.environ[env_wrapitk_python_path]])
else:
  os.environ[env_wrapitk_python_path] = os.pathsep.join(wrapitk_python_path_list)



# setup the option manager to be able to compare the resulting images in the same test

optionParser = OptionParser(usage="usage: %prog [--compare image1 image2] test.py [arg1 [arg2 [...]]]")
optionParser.add_option("-c", "--compare", action="append", dest="compare", default=[], metavar="IMAGE1 IMAGE2", nargs=2, help="compare IMAGE1 and IMAGE2 and exit with an error if the images are different. This options can appear several times to compare several images.")
optionParser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="display the command line before running the programs.")

(options, args) = optionParser.parse_args()

if len(args) < 1:
  optionParser.print_usage(sys.stderr)
  sys.exit(1)

# call the program, and exit if it fail

command = ["@PYTHON_EXECUTABLE@"] + args
if options.verbose:
  print(sys.stderr, "+", " ".join(command))
returnValue = subprocess.call( command )
if returnValue != 0 :
  sys.exit( returnValue )

# compare the images if needed
for imageFile1, imageFile2 in options.compare :
  command = ["@IMAGE_COMPARE@", imageFile1, imageFile2]
  if options.verbose:
    print(sys.stderr, "+", " ".join(command))
  returnValue = subprocess.call( command )
  if returnValue != 0 :
    sys.exit( returnValue )


# everything suceed - just exit
sys.exit(0)
