#!/usr/bin/env python
# Gentoo 'sconsign' wrapper script generated by python_generate_wrapper_scripts()

import os
import re
import subprocess
import sys

cpython_ABI_re = re.compile(r"^(\d+\.\d+)$")
jython_ABI_re = re.compile(r"^(\d+\.\d+)-jython$")
pypy_ABI_re = re.compile(r"^\d+\.\d+-pypy-(\d+\.\d+)$")
cpython_interpreter_re = re.compile(r"^python(\d+\.\d+)$")
jython_interpreter_re = re.compile(r"^jython(\d+\.\d+)$")
pypy_interpreter_re = re.compile(r"^pypy-c(\d+\.\d+)$")
cpython_shebang_re = re.compile(r"^#![ \t]*(?:/usr/bin/python|(?:)?/usr/bin/env[ \t]+(?:/usr/bin/)?python)")
python_shebang_options_re = re.compile(r"^#![ \t]*/usr/bin/(?:jython|pypy-c|python)(?:\d+(?:\.\d+)?)?[ \t]+(-\S)")
python_verification_output_re = re.compile("^GENTOO_PYTHON_TARGET_SCRIPT_PATH supported\n$")

#pypy_versions_mapping = {
#	"1.5": "2.7",
#	"1.6": "2.7",
#	"1.7": "2.7",
#	"1.8": "2.7",
#	"1.9": "2.7",
#	"2.0": "2.7",
#}

def get_PYTHON_ABI(python_interpreter):
	cpython_matched = cpython_interpreter_re.match(python_interpreter)
	jython_matched = jython_interpreter_re.match(python_interpreter)
	pypy_matched = pypy_interpreter_re.match(python_interpreter)
	if cpython_matched is not None:
		PYTHON_ABI = cpython_matched.group(1)
	elif jython_matched is not None:
		PYTHON_ABI = jython_matched.group(1) + "-jython"
	elif pypy_matched is not None:
		#PYTHON_ABI = pypy_versions_mapping[pypy_matched.group(1)] + "-pypy-" + pypy_matched.group(1)
		PYTHON_ABI = "2.7-pypy-" + pypy_matched.group(1)
	else:
		PYTHON_ABI = None
	return PYTHON_ABI

def get_python_interpreter(PYTHON_ABI):
	cpython_matched = cpython_ABI_re.match(PYTHON_ABI)
	jython_matched = jython_ABI_re.match(PYTHON_ABI)
	pypy_matched = pypy_ABI_re.match(PYTHON_ABI)
	if cpython_matched is not None:
		python_interpreter = "python" + cpython_matched.group(1)
	elif jython_matched is not None:
		python_interpreter = "jython" + jython_matched.group(1)
	elif pypy_matched is not None:
		python_interpreter = "pypy-c" + pypy_matched.group(1)
	else:
		python_interpreter = None
	return python_interpreter

try:
	environment = os.environ.copy()
	environment["ROOT"] = "/"
	eselect_process = subprocess.Popen(["/usr/bin/eselect", "python", "show", "--python2"], env=environment, stdout=subprocess.PIPE)
	if eselect_process.wait() != 0:
		raise ValueError
except (OSError, ValueError):
	sys.stderr.write("%s: Execution of 'eselect python show --python2' failed\n" % sys.argv[0])
	sys.exit(1)

python_interpreter = eselect_process.stdout.read()
if not isinstance(python_interpreter, str):
	# Python 3
	python_interpreter = python_interpreter.decode()
python_interpreter = python_interpreter.rstrip("\n")

PYTHON_ABI = get_PYTHON_ABI(python_interpreter)
if PYTHON_ABI is None:
	sys.stderr.write("%s: 'eselect python show --python2' printed unrecognized value '%s'\n" % (sys.argv[0], python_interpreter))
	sys.exit(1)

wrapper_script_path = os.path.realpath(sys.argv[0])
for PYTHON_ABI in [PYTHON_ABI, "2.7"]:
	target_executable_path = "%s-%s" % (wrapper_script_path, PYTHON_ABI)
	if os.path.exists(target_executable_path):
		break
else:
	sys.stderr.write("%s: No target script exists for '%s'\n" % (sys.argv[0], wrapper_script_path))
	sys.exit(1)

python_interpreter = get_python_interpreter(PYTHON_ABI)
if python_interpreter is None:
	sys.stderr.write("%s: Unrecognized Python ABI '%s'\n" % (sys.argv[0], PYTHON_ABI))
	sys.exit(1)

target_executable = open(target_executable_path, "rb")
target_executable_first_line = target_executable.readline()
target_executable.close()
if not isinstance(target_executable_first_line, str):
	# Python 3
	target_executable_first_line = target_executable_first_line.decode("utf_8", "replace")

options = []
python_shebang_options_matched = python_shebang_options_re.match(target_executable_first_line)
if python_shebang_options_matched is not None:
	options = [python_shebang_options_matched.group(1)]

cpython_shebang_matched = cpython_shebang_re.match(target_executable_first_line)

if cpython_shebang_matched is not None:
	try:
		python_interpreter_path = "/usr/bin/%s" % python_interpreter
		os.environ["GENTOO_PYTHON_TARGET_SCRIPT_PATH_VERIFICATION"] = "1"
		python_verification_process = subprocess.Popen([python_interpreter_path, "-c", "pass"], stdout=subprocess.PIPE)
		del os.environ["GENTOO_PYTHON_TARGET_SCRIPT_PATH_VERIFICATION"]
		if python_verification_process.wait() != 0:
			raise ValueError

		python_verification_output = python_verification_process.stdout.read()
		if not isinstance(python_verification_output, str):
			# Python 3
			python_verification_output = python_verification_output.decode()

		if not python_verification_output_re.match(python_verification_output):
			raise ValueError

		if cpython_interpreter_re.match(python_interpreter) is not None:
			os.environ["GENTOO_PYTHON_PROCESS_NAME"] = os.path.basename(sys.argv[0])
			os.environ["GENTOO_PYTHON_WRAPPER_SCRIPT_PATH"] = sys.argv[0]
			os.environ["GENTOO_PYTHON_TARGET_SCRIPT_PATH"] = target_executable_path

		if hasattr(os, "execv"):
			os.execv(python_interpreter_path, [python_interpreter_path] + options + sys.argv)
		else:
			sys.exit(subprocess.Popen([python_interpreter_path] + options + sys.argv).wait())
	except (KeyboardInterrupt, SystemExit):
		raise
	except:
		pass
	for variable in ("GENTOO_PYTHON_PROCESS_NAME", "GENTOO_PYTHON_WRAPPER_SCRIPT_PATH", "GENTOO_PYTHON_TARGET_SCRIPT_PATH", "GENTOO_PYTHON_TARGET_SCRIPT_PATH_VERIFICATION"):
		if variable in os.environ:
			del os.environ[variable]

if hasattr(os, "execv"):
	os.execv(target_executable_path, sys.argv)
else:
	sys.exit(subprocess.Popen([target_executable_path] + sys.argv[1:]).wait())
