#!/usr/bin/env python
import argparse
import os
import shutil
from contextlib import contextmanager
from subprocess import check_call

_dname = os.path.dirname

REPO_ROOT = _dname(_dname(_dname(os.path.abspath(__file__))))


@contextmanager
def cd(path):
    """Change directory while inside context manager."""
    cwd = os.getcwd()
    try:
        os.chdir(path)
        yield
    finally:
        os.chdir(cwd)


def run(command):
    return check_call(command, shell=True)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument(
        '-e',
        '--extras',
        help='Install extras_require along with normal install',
    )
    args = parser.parse_args()
    with cd(REPO_ROOT):
        run("python scripts/ci/install-dev-deps")
        if os.path.isdir("dist") and os.listdir("dist"):
            shutil.rmtree("dist")
        run("python setup.py bdist_wheel")
        wheel_dist = os.listdir("dist")[0]
        package = os.path.join('dist', wheel_dist)
        if args.extras:
            package = f"\"{package}[{args.extras}]\""
        run(f'pip install {package}')
