#!/usr/bin/env python
# Gentoo 'epylint' wrapper script

import os
import re
import subprocess
import sys

EPYTHON_re = re.compile(r"^python(\d+\.\d+)$")

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)

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

EPYTHON_matched = EPYTHON_re.match(eselect_output)
if EPYTHON_matched:
	PYTHON_ABI = EPYTHON_matched.group(1)
else:
	sys.stderr.write("'eselect python show --python2' printed unrecognized value '%s" % eselect_output)
	sys.exit(1)

os.environ["PYTHON_SCRIPT_NAME"] = sys.argv[0]
target_executable = "%s-%s" % (os.path.realpath(sys.argv[0]), PYTHON_ABI)
if not os.path.exists(target_executable):
	sys.stderr.write("'%s' does not exist\n" % target_executable)
	sys.exit(1)

os.execv(target_executable, sys.argv)
