#!/usr/bin/python

# initial REPO_URL='git://android.git.kernel.org/tools/repo.git'
REPO_URL = 'git://github.com/mynameismevin/andromeda.git'
REPO_REV = 'master'

# Copyright (C) 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Original code can be found here: https://android.googlesource.com/tools/repo/
# This is a refactor for the OpenStack project with an upgrade to Python 3.
# All major code changes are marked.
# Formatting changed to meet PEP8 requirements.

# increment this whenever we make important changes to this script
VERSION = (1, 0)

# increment this if the MAINTAINER_KEYS block is modified
# TODO rip PGP functionality out.
KEYRING_VERSION = (1, 2)
MAINTAINER_KEYS = """

    Mike Lloyd <kevin.michael.lloyd@gmail.com>
     -----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1

mQENBFWwMTYBCACkbUc3zl/K4efBKIhxU+TdY27Gvt8TFK36HHTE7xg4ukqM3d01
1PZmtIonbWz9h5W9K382ujp3IS7k6UiUfahpj+dvSiGmiyx8GApJ5dmbOl2K/wi5
G1fMsevgwlaTjcqn67sX4MF/R6zWCdzW655yzRG4omYP9O9xTYXSGhjWKrl7oc2I
0K0wbdJwMO4vDVc36DIRv6RIiLMt8WITKO502wmr9bzBpTwX1qhNDeXrqtyvCX+T
g/nZY+7xWIgE0QjygxDep2asN75eaoKZVUwu/FeFNZAmUR5m26ny5XmZ3ATmim+m
d0SHChjKPRCeogHn1HmFnm0s9Q3PkjgqZSJpABEBAAG0OE1pa2UgTGxveWQgKFBy
aW1hcnkgS2V5KSA8a2V2aW4ubWljaGFlbC5sbG95ZEBnbWFpbC5jb20+iQE4BBMB
AgAiBQJVsDE2AhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRCyWchujsBS
wHJ6B/4qvfXgBHa+iPOF4cJ1IcJyEr8Ml2+tijgbz6XymyOcHTMEo5Sm7P3Sw9Cq
45hOGgzlbH88EC+SeDJ4TDEPuv1kyi91osFhLgW3xOLVHtJbhrRZRdbZeBcqMzGZ
D2ktDQLuN3lAD8lycKcRUU7ustClMokRcLW2Wl6JHx1cUAD0iFIkZAN9lbeqVQf6
dD9lChuxrVoQ8pNOMYuZMctigwbOgL8dEA0obx2KClP4ZzDki2EQ3DSXM2qe0BLN
sKn87xt/0kXKIjQuJHDhKHe9iOr/49h3W5a4Xvh3prol27yCyN/FvgMoaDqzapYR
RoouK2g8vpZm44Mt+mTJTxTzjMy7uQENBFWwMTYBCADC2RB21LD1mxqybzUIYN6W
3q037u6dmdOSDDXOD5lH2AisVUywcIOlORD8yCXFMjOgY5YKGeeHEXTqfO2/bwQC
GCN0VyQGMKMPUlv92tqLO1M0tHiwVsDvagQBpQaTBPaWpxBJ0Baw2VNxmNuynsrU
oVPTcMXpGj1afqkpYVJIn6lM0efJxwTO6x6iP3oaHJpI4YNymh/8aclZU1tb7s1M
3mcoGAsNika1c8tVqfyjZQeELlCGXXx8vUPCHpCRWZapKzBVmTYydYNkZ5Yb8ajx
Iw5C1a3CK4F9gn0SG7BVivZtaVI7KB+rqxa/UOGWERQfWYSsl3k/FDqqH1YNO8U1
ABEBAAGJAR8EGAECAAkFAlWwMTYCGwwACgkQslnIbo7AUsApcQgAk8ZfKMpi/aAo
xUZUni7/97mA+2CXe8rgGrQ4Dc7MGMbniPFZeVhjvS2IKS1W3Cw9UVr7U5jtjcKL
T7HBAQHkcKssgWFbVURUm3YD22vJQfdyV5SeY/fwvmpbYc0/sia1VxCXJaGX2mDm
S9Kb7HF2V1+m+Cc8KpEMhi1qLHkxozgsX12myJaVaq7PqMAaf2ETB7IUKiIQImHU
oQ2buWbxfAQXDciSS8g/1CVNIAXHR4/WUCL9OIE9NB/jeb253jXtaqg7XpU0mEeW
sPoqRINIZ7k3Ce9kxvcQRAr5l1R0BNWcmGcpYC/W4YOldvUu4FWQmjeZbTgXdNXJ
acUqulitoA==
=htTV
-----END PGP PUBLIC KEY BLOCK-----
"""

GIT = 'git'  # our git command
MIN_GIT_VERSION = (1, 7, 2)  # minimum supported git version
repodir = '.andromeda'  # name of repo's private directory
S_repo = 'andromeda'  # special repo repository
S_manifests = 'manifests'  # special manifest repository
REPO_MAIN = S_repo + '/main.py'  # main script
MIN_PYTHON_VERSION = (2, 6)  # minimum supported python version

import errno
import optparse
import os
import re
import shutil
import stat
import subprocess
import sys

if sys.version_info[0] == 3:
    import urllib.request
    import urllib.error
else:
    import imp
    import urllib2

    urllib = imp.new_module('urllib')
    urllib.request = urllib2
    urllib.error = urllib2


def _print(*objects, **kwargs):
    sep = kwargs.get('sep', ' ')
    end = kwargs.get('end', '\n')
    out = kwargs.get('file', sys.stdout)
    out.write(sep.join(objects) + end)

# Python version check
ver = sys.version_info
if (ver[0], ver[1]) < MIN_PYTHON_VERSION:
    _print('error: Python version %s unsupported.\n'
           'Please use Python 2.6 - 3.4 instead.'
           % sys.version.split(' ')[0], file=sys.stderr)
    sys.exit(1)

home_dot_repo = os.path.expanduser('~/.andromedaconfig')
# TODO rip PGP out.
gpg_dir = os.path.join(home_dot_repo, 'gnupg')

extra_args = []
init_optparse = optparse.OptionParser(usage="andromeda init -u url [options]")

# Logging
group = init_optparse.add_option_group('Logging options')
group.add_option('-q', '--quiet',
                 dest="quiet", action="store_true", default=False,
                 help="be quiet")

# Manifest
group = init_optparse.add_option_group('Manifest options')
group.add_option('-u', '--manifest-url',
                 dest='manifest_url',
                 help='manifest repository location', metavar='URL')
group.add_option('-b', '--manifest-branch',
                 dest='manifest_branch',
                 help='manifest branch or revision', metavar='REVISION')
group.add_option('-m', '--manifest-name',
                 dest='manifest_name',
                 help='initial manifest file', metavar='NAME.xml')
group.add_option('--mirror',
                 dest='mirror', action='store_true',
                 help='create a replica of the remote repositories '
                      'rather than a client working directory')
group.add_option('--reference',
                 dest='reference',
                 help='location of mirror directory', metavar='DIR')
group.add_option('--depth', type='int', default=None,
                 dest='depth',
                 help='create a shallow clone with given depth; see git clone')
group.add_option('--archive',
                 dest='archive', action='store_true',
                 help='checkout an archive instead of a git repository for '
                      'each project. See git archive.')
group.add_option('-g', '--groups',
                 dest='groups', default='default',
                 help='restrict manifest projects to ones with specified '
                      'group(s) [default|all|G1,G2,G3|G4,-G5,-G6]',
                 metavar='GROUP')
group.add_option('-p', '--platform',
                 dest='platform', default="auto",
                 help='restrict manifest projects to ones with a specified '
                      'platform group [auto|all|none|linux|darwin|...]',
                 metavar='PLATFORM')


# Tool
group = init_optparse.add_option_group('andromeda version options')
group.add_option('--repo-url',
                 dest='repo_url',
                 help='andromeda repository location', metavar='URL')
group.add_option('--repo-branch',
                 dest='repo_branch',
                 help='andromeda branch or revision', metavar='REVISION')
group.add_option('--no-repo-verify',
                 dest='no_repo_verify', action='store_true',
                 help='do not verify repo source code')

# Other
group = init_optparse.add_option_group('Other options')
group.add_option('--config-name',
                 dest='config_name', action="store_true", default=False,
                 help='Always prompt for name/e-mail')


class CloneFailure(Exception):
    """Indicate the remote clone of repo itself failed.
    """


def _Init(args):
    """Installs repo by cloning it over the network.
    """
    opt, args = init_optparse.parse_args(args)
    if args:
        init_optparse.print_usage()
        sys.exit(1)

    url = opt.repo_url
    if not url:
        url = REPO_URL
        extra_args.append('--repo-url=%s' % url)

    branch = opt.repo_branch
    if not branch:
        branch = REPO_REV
        extra_args.append('--repo-branch=%s' % branch)

    if branch.startswith('refs/heads/'):
        branch = branch[len('refs/heads/'):]
    if branch.startswith('refs/'):
        _print("fatal: invalid branch name '%s'" % branch, file=sys.stderr)
        raise CloneFailure()

    try:
        os.mkdir(repodir)
    except OSError as e:
        if e.errno != errno.EEXIST:
            _print('fatal: cannot make %s directory: %s'
                   % (repodir, e.strerror), file=sys.stderr)
            # Don't raise CloneFailure; that would delete the
            # name. Instead exit immediately.
            #
            sys.exit(1)

    _CheckGitVersion()
    try:
        # TODO `NeedSetupGnuPG()` can be ripped out.
        if NeedSetupGnuPG():
            can_verify = SetupGnuPG(opt.quiet)
        else:
            can_verify = True

        dst = os.path.abspath(os.path.join(repodir, S_repo))
        _Clone(url, dst, opt.quiet)

        if can_verify and not opt.no_repo_verify:
            rev = _Verify(dst, branch, opt.quiet)
        else:
            rev = 'refs/remotes/origin/%s^0' % branch

        _Checkout(dst, branch, rev, opt.quiet)
    except CloneFailure:
        if opt.quiet:
            _print('fatal: andromeda init failed; run without --quiet to see why',
                   file=sys.stderr)
        raise


def ParseGitVersion(ver_str):
    # TODO update to encode ver_str to bytes for Python 3.
    if not ver_str.startswith('git version '):
        return None

    num_ver_str = ver_str[len('git version '):].strip().split('-')[0]
    to_tuple = []
    for num_str in num_ver_str.split('.')[:3]:
        if num_str.isdigit():
            to_tuple.append(int(num_str))
        else:
            to_tuple.append(0)
    return tuple(to_tuple)


def _CheckGitVersion():
    cmd = [GIT, '--version']
    try:
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    except OSError as e:
        _print(file=sys.stderr)
        _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
        _print('fatal: %s' % e, file=sys.stderr)
        _print(file=sys.stderr)
        _print('Please make sure %s is installed and in your path.' % GIT,
               file=sys.stderr)
        raise CloneFailure()

    ver_str = proc.stdout.read().strip()
    proc.stdout.close()
    proc.wait()

    ver_act = ParseGitVersion(ver_str)
    if ver_act is None:
        _print('error: "%s" unsupported' % ver_str, file=sys.stderr)
        raise CloneFailure()

    if ver_act < MIN_GIT_VERSION:
        need = '.'.join(map(str, MIN_GIT_VERSION))
        _print('fatal: git %s or later required' % need, file=sys.stderr)
        raise CloneFailure()

    # TODO rip this functionality out.
def NeedSetupGnuPG():
    if not os.path.isdir(home_dot_repo):
        return True

    kv = os.path.join(home_dot_repo, 'keyring-version')
    if not os.path.exists(kv):
        return True

    kv = open(kv).read()
    if not kv:
        return True

    kv = tuple(map(int, kv.split('.')))
    if kv < KEYRING_VERSION:
        return True
    return False

# TODO rip this functionality out.
def SetupGnuPG(quiet):
    try:
        os.mkdir(home_dot_repo)
    except OSError as e:
        if e.errno != errno.EEXIST:
            _print('fatal: cannot make %s directory: %s'
                   % (home_dot_repo, e.strerror), file=sys.stderr)
            sys.exit(1)

    try:
        os.mkdir(gpg_dir, stat.S_IRWXU)
    except OSError as e:
        if e.errno != errno.EEXIST:
            _print('fatal: cannot make %s directory: %s' % (gpg_dir, e.strerror),
                   file=sys.stderr)
            sys.exit(1)

    env = os.environ.copy()
    env['GNUPGHOME'] = gpg_dir.encode()

    cmd = ['gpg', '--import']
    try:
        proc = subprocess.Popen(cmd,
                                env=env,
                                stdin=subprocess.PIPE)
    except OSError as e:
        if not quiet:
            _print('warning: gpg (GnuPG) is not available, functionality will soon be deprecated.', file=sys.stderr)
            _print(file=sys.stderr)
        return False

    proc.stdin.write(MAINTAINER_KEYS)
    proc.stdin.close()

    if proc.wait() != 0:
        _print('Fatal: registering andromeda maintainer keys failed', file=sys.stderr)
        sys.exit(1)
    _print()

    fd = open(os.path.join(home_dot_repo, 'keyring-version'), 'w')
    fd.write('.'.join(map(str, KEYRING_VERSION)) + '\n')
    fd.close()
    return True


def _SetConfig(local, name, value):
    """Set a git configuration option to the specified value.
    """
    cmd = [GIT, 'config', name, value]
    if subprocess.Popen(cmd, cwd=local).wait() != 0:
        raise CloneFailure()


def _InitHttp():
    handlers = []

    mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    try:
        import netrc

        n = netrc.netrc()
        for host in n.hosts:
            p = n.hosts[host]
            mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
            mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
    except:
        pass
    handlers.append(urllib.request.HTTPBasicAuthHandler(mgr))
    handlers.append(urllib.request.HTTPDigestAuthHandler(mgr))

    if 'http_proxy' in os.environ:
        url = os.environ['http_proxy']
        handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
    if 'REPO_CURL_VERBOSE' in os.environ:
        handlers.append(urllib.request.HTTPHandler(debuglevel=1))
        handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
    urllib.request.install_opener(urllib.request.build_opener(*handlers))


def _Fetch(url, local, src, quiet):
    if not quiet:
        _print('Get %s' % url, file=sys.stderr)

    cmd = [GIT, 'fetch']
    if quiet:
        cmd.append('--quiet')
        err = subprocess.PIPE
    else:
        err = None
    cmd.append(src)
    cmd.append('+refs/heads/*:refs/remotes/origin/*')
    cmd.append('refs/tags/*:refs/tags/*')

    proc = subprocess.Popen(cmd, cwd=local, stderr=err)
    if err:
        proc.stderr.read()
        proc.stderr.close()
    if proc.wait() != 0:
        raise CloneFailure()


# TODO verify is this is causing the clone.bundle errors.
def _DownloadBundle(url, local, quiet):
    if not url.endswith('/'):
        url += '/'
    url += 'clone.bundle'

    proc = subprocess.Popen(
        [GIT, 'config', '--get-regexp', 'url.*.insteadof'],
        cwd=local,
        stdout=subprocess.PIPE)
    for line in proc.stdout:
        m = re.compile(r'^url\.(.*)\.insteadof (.*)$').match(line)
        if m:
            new_url = m.group(1)
            old_url = m.group(2)
            if url.startswith(old_url):
                url = new_url + url[len(old_url):]
                break
    proc.stdout.close()
    proc.wait()

    if not url.startswith('http:') and not url.startswith('https:'):
        return False

    dest = open(os.path.join(local, '.git', 'clone.bundle'), 'w+b')
    try:
        try:
            r = urllib.request.urlopen(url)
        except urllib.error.HTTPError as e:
            if e.code in [401, 403, 404]:
                return False
            _print('fatal: Cannot get %s' % url, file=sys.stderr)
            _print('fatal: HTTP error %s' % e.code, file=sys.stderr)
            raise CloneFailure()
        except urllib.error.URLError as e:
            _print('fatal: Cannot get %s' % url, file=sys.stderr)
            _print('fatal: error %s' % e.reason, file=sys.stderr)
            raise CloneFailure()
        try:
            if not quiet:
                _print('Get %s' % url, file=sys.stderr)
            while True:
                buf = r.read(8192)
                if buf == '':
                    return True
                dest.write(buf)
        finally:
            r.close()
    finally:
        dest.close()


def _ImportBundle(local):
    path = os.path.join(local, '.git', 'clone.bundle')
    try:
        _Fetch(local, local, path, True)
    finally:
        os.remove(path)


def _Clone(url, local, quiet):
    """Clones a git repository to a new subdirectory of repodir
    """
    try:
        os.mkdir(local)
    except OSError as e:
        _print('fatal: cannot make %s directory: %s' % (local, e.strerror),
               file=sys.stderr)
        raise CloneFailure()

    cmd = [GIT, 'init', '--quiet']
    try:
        proc = subprocess.Popen(cmd, cwd=local)
    except OSError as e:
        _print(file=sys.stderr)
        _print("fatal: '%s' is not available" % GIT, file=sys.stderr)
        _print('fatal: %s' % e, file=sys.stderr)
        _print(file=sys.stderr)
        _print('Please make sure %s is installed and in your path.' % GIT,
               file=sys.stderr)
        raise CloneFailure()
    if proc.wait() != 0:
        _print('fatal: could not create %s' % local, file=sys.stderr)
        raise CloneFailure()

    _InitHttp()
    _SetConfig(local, 'remote.origin.url', url)
    _SetConfig(local, 'remote.origin.fetch',
               '+refs/heads/*:refs/remotes/origin/*')
    if _DownloadBundle(url, local, quiet):
        _ImportBundle(local)
    else:
        _Fetch(url, local, 'origin', quiet)


def _Verify(cwd, branch, quiet):
    """Verify the branch has been signed by a tag.
    """
    cmd = [GIT, 'describe', 'origin/%s' % branch]
    proc = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            cwd=cwd)
    cur = proc.stdout.read().strip()
    proc.stdout.close()

    proc.stderr.read()
    proc.stderr.close()

    if proc.wait() != 0 or not cur:
        _print(file=sys.stderr)
        _print("fatal: branch '%s' has not been signed" % branch, file=sys.stderr)
        raise CloneFailure()

    m = re.compile(r'^(.*)-[0-9]{1,}-g[0-9a-f]{1,}$').match(cur)
    if m:
        cur = m.group(1)
        if not quiet:
            _print(file=sys.stderr)
            _print("info: Ignoring branch '%s'; using tagged release '%s'"
                   % (branch, cur), file=sys.stderr)
            _print(file=sys.stderr)

    env = os.environ.copy()
    # TODO rip out PGP
    # env['GNUPGHOME'] = gpg_dir.encode()

    cmd = [GIT, 'tag', '-v', cur]
    proc = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            cwd=cwd,
                            env=env)
    out = proc.stdout.read()
    proc.stdout.close()

    err = proc.stderr.read()
    proc.stderr.close()

    if proc.wait() != 0:
        _print(file=sys.stderr)
        _print(out, file=sys.stderr)
        _print(err, file=sys.stderr)
        _print(file=sys.stderr)
        raise CloneFailure()
    return '%s^0' % cur


def _Checkout(cwd, branch, rev, quiet):
    """Checkout an upstream branch into the repository and track it.
    """
    cmd = [GIT, 'update-ref', 'refs/heads/default', rev]
    if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
        raise CloneFailure()

    _SetConfig(cwd, 'branch.default.remote', 'origin')
    _SetConfig(cwd, 'branch.default.merge', 'refs/heads/%s' % branch)

    cmd = [GIT, 'symbolic-ref', 'HEAD', 'refs/heads/default']
    if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
        raise CloneFailure()

    cmd = [GIT, 'read-tree', '--reset', '-u']
    if not quiet:
        cmd.append('-v')
    cmd.append('HEAD')
    if subprocess.Popen(cmd, cwd=cwd).wait() != 0:
        raise CloneFailure()


def _FindRepo():
    """Look for a repo installation, starting at the current directory.
    """
    curdir = os.getcwd()
    repo = None

    olddir = None
    while curdir != '/' \
            and curdir != olddir \
            and not repo:
        repo = os.path.join(curdir, repodir, REPO_MAIN)
        if not os.path.isfile(repo):
            repo = None
            olddir = curdir
            curdir = os.path.dirname(curdir)
    return (repo, os.path.join(curdir, repodir))


class _Options:
    help = False


def _ParseArguments(args):
    cmd = None
    opt = _Options()
    arg = []

    for i in range(len(args)):
        a = args[i]
        if a == '-h' or a == '--help':
            opt.help = True

        elif not a.startswith('-'):
            cmd = a
            arg = args[i + 1:]
            break
    return cmd, opt, arg


def _Usage():
    _print(
        """Usage: andromeda COMMAND [ARGS]

        andromeda is not yet installed.  Use "andromeda init" to install it here.

        The most commonly used andromeda commands are:

          init      Install andromeda in the current working directory
          help      Display detailed help on a command

        For access to the full online help, install andromeda ("andromeda init").
        """, file=sys.stderr)
    sys.exit(1)


def _Help(args):
    if args:
        if args[0] == 'init':
            init_optparse.print_help()
            sys.exit(0)
        else:
            _print("Error: '%s' is not a bootstrap command.\n"
                   'For access to online help, install andromeda ("andromeda init").'
                   % args[0], file=sys.stderr)
    else:
        _Usage()
    sys.exit(1)


def _NotInstalled():
    _print('Error: andromeda is not installed.  Use "andromeda init" to install it here.',
           file=sys.stderr)
    sys.exit(1)


def _NoCommands(cmd):
    _print("""Error: command '%s' requires andromeda to be installed first.
         Use "andromeda init" to install it here.""" % cmd, file=sys.stderr)
    sys.exit(1)


def _RunSelf(wrapper_path):
    my_dir = os.path.dirname(wrapper_path)
    my_main = os.path.join(my_dir, 'main.py')
    my_git = os.path.join(my_dir, '.git')

    if os.path.isfile(my_main) and os.path.isdir(my_git):
        for name in ['git_config.py',
                     'project.py',
                     'subcmds']:
            if not os.path.exists(os.path.join(my_dir, name)):
                return None, None
        return my_main, my_git
    return None, None


def _SetDefaultsTo(gitdir):
    global REPO_URL
    global REPO_REV

    REPO_URL = gitdir
    proc = subprocess.Popen([GIT,
                             '--git-dir=%s' % gitdir,
                             'symbolic-ref',
                             'HEAD'],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    REPO_REV = proc.stdout.read().strip()
    proc.stdout.close()

    proc.stderr.read()
    proc.stderr.close()

    if proc.wait() != 0:
        _print('fatal: %s has no current branch' % gitdir, file=sys.stderr)
        sys.exit(1)


def main(orig_args):
    repo_main, rel_repo_dir = _FindRepo()
    cmd, opt, args = _ParseArguments(orig_args)

    wrapper_path = os.path.abspath(__file__)
    my_main, my_git = _RunSelf(wrapper_path)

    if not repo_main:
        if opt.help:
            _Usage()
        if cmd == 'help':
            _Help(args)
        if not cmd:
            _NotInstalled()
        if cmd == 'init':
            if my_git:
                _SetDefaultsTo(my_git)
            try:
                _Init(args)
            except CloneFailure:
                shutil.rmtree(os.path.join(repodir, S_repo), ignore_errors=True)
                sys.exit(1)
            repo_main, rel_repo_dir = _FindRepo()
        else:
            _NoCommands(cmd)

    if my_main:
        repo_main = my_main

    ver_str = '.'.join(map(str, VERSION))
    me = [sys.executable, repo_main,
          '--repo-dir=%s' % rel_repo_dir,
          '--wrapper-version=%s' % ver_str,
          '--wrapper-path=%s' % wrapper_path,
          '--']
    me.extend(orig_args)
    me.extend(extra_args)
    try:
        os.execv(sys.executable, me)
    except OSError as e:
        _print("fatal: unable to start %s" % repo_main, file=sys.stderr)
        _print("fatal: %s" % e, file=sys.stderr)
        sys.exit(148)


if __name__ == '__main__':
    if ver[0] == 3:
        _print(
            "Warning: Python 3 is currently in beta support.\nSome things work, if it doesn't, please file an issue!",
            file=sys.stderr)
    main(sys.argv[1:])
