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

import os
import re
import subprocess
import sys

cpython_re = re.compile(r"^python(\d+\.\d+)$")
jython_re = re.compile(r"^jython(\d+\.\d+)$")
python_shebang_re = re.compile(r"^#! *(/usr/bin/python|()?/usr/bin/env +(/usr/bin/)?python)")
python_verification_output_re = re.compile("^GENTOO_PYTHON_TARGET_SCRIPT_PATH supported\n$")

def get_PYTHON_ABI(EPYTHON):
	cpython_matched = cpython_re.match(EPYTHON)
	jython_matched = jython_re.match(EPYTHON)
	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"
	else:
		PYTHON_ABI = None
	return PYTHON_ABI

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

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

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

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

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

python_shebang_matched = python_shebang_re.match(target_executable_first_line)
target_executable.close()

if python_shebang_matched is not None:
	try:
		python_interpreter_path = "/usr/bin/%s" % EPYTHON
		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_re.match(EPYTHON) 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] + sys.argv)
		else:
			sys.exit(subprocess.Popen([python_interpreter_path] + 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())
