##############################################################################
#
# Copyright (c) 2010 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is free software: you can Use, Study, Modify and Redistribute
# it under the terms of the GNU General Public License version 3, or (at your
# option) any later version, as published by the Free Software Foundation.
#
# You can also Link and Combine this program with other software covered by
# the terms of any of the Free Software licenses or any of the Open Source
# Initiative approved licenses and Convey the resulting work. Corresponding
# source of such a combination shall include the source code for all other
# software used.
#
# This program is distributed WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING file for full licensing terms.
# See https://www.nexedi.com/licensing for rationale and options.
#
##############################################################################
import os
import sys

def runTestSuite(args, d):
  env = os.environ.copy()
  if 'openssl_binary' in d:
    env['OPENSSL_BINARY'] = d['openssl_binary']
  if 'test_ca_path' in d:
    env['TEST_CA_PATH'] = d['test_ca_path']
  if 'prepend_path' in d:
    try:
      env['PATH'] = d['prepend_path'] + ':' + env['PATH']
    except KeyError:
      env['PATH'] = d['prepend_path']
  if 'instance_home' in d:
    env['INSTANCE_HOME'] = d['instance_home']
    env['REAL_INSTANCE_HOME'] = d['instance_home']

  # If defined, will add (and replace if existing) envvars to environment.
  if 'environment' in d:
    env.update(d['environment'])

  # Deal with Shebang size limitation
  executable_filepath = args[0]
  with open(executable_filepath, 'r') as f:
    line = f.readline()
  argument_list = []
  if line[:2] == '#!':
    executable_filepath = line[2:].strip()
    argument_list.append(executable_filepath)
  argument_list += args
  argument_list += sys.argv[1:]
  os.execve(executable_filepath, argument_list, env)

runUnitTest = runTestSuite
