#!/usr/bin/env python3
#
# venv.py - Build a python3 virtualenv for running TortoiseHg
#
# Copyright 2020 Matt Harbison <mharbison72@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

import os
import pathlib
import subprocess


def build_py3(
    source_dir: pathlib.Path,
    hg_source_dir: pathlib.Path,
    python_exe: pathlib.Path,
    output: pathlib.Path,
):
    """Creates a virtualenv at ``output`` with the necessary dependencies
    for running thg from source.

    The python version and architecture will match the characteristics of
    ``python_exe``.  Mercurial is built and installed from the source tree
    at ``hg_source_dir``.
    """
    print()
    print('building virtualenv at %s' % output)

    output.mkdir(exist_ok=True)

    subprocess.run(
        [str(python_exe), '-m', 'venv', str(output)], check=True,
    )

    if os.name == "nt":
        venv_bin = output / "Scripts"
        venv_pip = venv_bin / "pip.exe"
        venv_python = venv_bin / "python.exe"
    else:
        venv_bin = output / "bin"
        venv_pip = venv_bin / "pip"
        venv_python = venv_bin / "python"

    requirements_txt = (
        source_dir / 'contrib' / 'packaging' / 'venv_py3' / 'requirements.txt'
    )

    if os.name == 'nt':
        requirements_txt = requirements_txt.parent / 'requirements_win32.txt'

    subprocess.run([
        str(venv_pip),
        "install",
        "-r",
        str(requirements_txt),
        "--disable-pip-version-check",
    ], check=True)

    install_mercurial(venv_python, hg_source_dir)

    print()
    print('virtualenv and dependencies installed at %s' % output)


def install_mercurial(venv_python, hg_source_dir):
    """Build and install Mercurial from the source path identified on the
    command line, using the python in ``venv_python``."""
    print()
    print('building Mercurial')

    subprocess.run(
        [str(venv_python), 'setup.py', 'clean'],
        cwd=str(hg_source_dir),
        check=True,
    )

    subprocess.run(
        [str(venv_python), 'setup.py', 'build'],
        cwd=str(hg_source_dir),
        check=True,
    )

    subprocess.run(
        [str(venv_python), 'setup.py', 'install'],
        cwd=str(hg_source_dir),
        check=True,
    )
