#!/usr/bin/env python

# Copyright 2019 The Emscripten Authors.  All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License.  Both these licenses can be
# found in the LICENSE file.

"""Provides a way to run a script on the preferred Python version"""

import os
import subprocess
import sys


def which(program):
  for path in [""] + os.environ.get("PATH", "").split(os.pathsep):
    exe_file = os.path.join(path, program)
    if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
      # in case of pyenv we might have `python3` command available, but it's just a stub
      # https://github.com/emscripten-core/emscripten/issues/8792
      p = subprocess.Popen([exe_file, "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      p.communicate()
      if p.returncode == 0:
        return exe_file
  return None

# Look for the best choice for python, favours Python3 over Python2
# In case of Windows it uses always python that was used for this script
if sys.platform in ["linux", "linux2", "darwin"]:
  python = which("python3") or which("python") or sys.executable
else:
  python = sys.executable

sys.exit(subprocess.call([python] + sys.argv[1:]))