#!/usr/bin/python-exec2c
# vim:fileencoding=utf-8:ft=python
# (c) 2012-2021 Michał Górny
# Released under the terms of the 2-clause BSD license.
#
# This is not the script you are looking for. This is just a wrapper.
# The actual scripts of this application were installed
# in subdirectories of /usr/lib/python-exec.
# You are most likely looking for one of these.

from __future__ import with_statement


# prepare a clean globals for exec()
new_globals = dict(globals())
# we have to keep the import top, so delete it from globals
del new_globals['with_statement']


import errno
import os
import os.path
import sys


try:
    from epython import EPYTHON
except ImportError:
    EPYTHON = os.path.basename(sys.executable)
    if '' and EPYTHON.endswith(''):
        EPYTHON = EPYTHON[:-len('')]


# Alike python-exec2c, perform symlink resolution on target until
# EINVAL is hit. If the final target is python-exec2, use the last
# symlink name preceding it. Otherwise, use the final target.
prev_target = None
target = sys.argv[0]
while True:
    try:
        next_target = os.path.join(os.path.dirname(target),
                                   os.readlink(target))
    except OSError as e:
        if e.errno == errno.EINTR:
            # retry
            continue
        if e.errno == errno.EINVAL:
            # if the final target is python-exec2, use last symlink
            if os.path.basename(target) in ('python-exec2',
                                            'python-exec2'):
                if prev_target is None:
                    sys.stderr.write(
                        '{}: python-exec2 is a wrapper, it must not '
                        'be run directly.\n'.format(target))
                    sys.exit(127)

                target = prev_target
            break
        raise
    else:
        prev_target = target
        target = next_target

target = os.path.join('/usr/lib/python-exec', EPYTHON,
                      os.path.basename(target))

data = None
while data is None:
    try:
        kwargs = {}
        if sys.version_info >= (3,):
            import tokenize

            # need to provide encoding
            with open(target, 'rb') as f:
                kwargs['encoding'] = tokenize.detect_encoding(f.readline)[0]

        with open(target, 'r', **kwargs) as f:
            data = f.read()
    except IOError as e:
        if e.errno == errno.EINTR:
            # retry
            continue
        elif e.errno == errno.ENOENT:
            sys.stderr.write(
                '{}: this Python implementation ({}) is not supported '
                'by the script.\n'.format(target, EPYTHON))
            sys.exit(127)
        else:
            raise

sys.argv[0] = target
# in python3.9+, __file__ paths are absolute
if sys.version_info >= (3, 9):
    target = os.path.abspath(target)
new_globals['__file__'] = target

exec(data, new_globals)
