#!/usr/bin/env python3

import os
import subprocess
import sys


def get_pipfile(dir):
    dir = os.path.dirname(dir)
    if dir == "/":
        return ""
    pipfile = dir + "/Pipfile"
    if os.path.exists(pipfile):
        return pipfile
    else:
        return get_pipfile(dir)


script = sys.argv[1]
pipfile = get_pipfile(os.path.realpath(script))

if pipfile:
    env = os.environ.copy()
    env["PIPENV_PIPFILE"] = pipfile
    proc = subprocess.Popen(["pipenv", "run", "python", script] + sys.argv[2:], env=env)
    sys.exit(proc.wait())
else:
    print("Could not locate the Pipfile for $SCRIPT.")
    sys.exit(1)
