#!/usr/bin/env python3

import os
import sys
import tempfile

sep = sys.argv.index("--")
if sep < 0:
  print("Usage: /path/to/bin /path/to/other/bin -- cmd to run", file=sys.stderr)
  sys.exit(1)

def is_executable(path):
  return os.path.isfile(path) and os.access(path, os.X_OK)

def path_or_which(path, path_env):
  if is_executable(path):
    return path
  for d in path_env.split(":"):
    maybe = os.path.join(d, os.path.basename(path))
    if is_executable(maybe):
      return maybe
  print(f"Could not find {path}", file=sys.stderr)
  sys.exit(1)


files = sys.argv[1:sep]
args = sys.argv[sep + 1:]

path_dir = tempfile.mkdtemp()
for file in files:
  resolved_file = path_or_which(file, os.environ.get("PATH", ""))
  os.symlink(resolved_file, os.path.join(path_dir, os.path.basename(file)))

env = dict(os.environ)
env["PATH"] = path_dir

os.execve(path_or_which(args[0], env["PATH"]), args, env)
