#!/usr/bin/env bash
# This command is specifically for pip-installing a previously
# built wheel.

# Default arguments for all packages installed with `pip install`
# --verbose          : Display the output when running setup.py.
# --no-index         : Don't look at the package index.
# --disable-pip-version-check : Disables pip's version self-check.
# --isolated         : Don't read configuration files such as
#                      ~/.pydistutils.cfg
# --no-cache-dir     : Disable the cache.
#                      (so that no previously built wheels can sneak in to
#                      resolve runtime dependencies)
pip_install_flags="--verbose --no-index --find-links=$SAGE_SPKG_WHEELS --disable-pip-version-check --isolated --no-cache-dir"

# Note: "sage-pip-install" is meant to be run after $(PYTHON) has
# been installed (either as an spkg or as a venv over a system python3).
# It is then guaranteed by sage-env that PATH is set in a way that "python3"
# refers to the correct python3.
#
# All SPKGs that use this script must therefore declare $(PYTHON) as a
# dependency.
PYTHON=python3

# The PIP variable is only used to determine the name of the lock file.
PIP=pip3

# We should avoid running pip while installing a package because that
# is prone to race conditions. Therefore, we use a lockfile while
# running pip. This is implemented in the Python script sage-flock
LOCK="$SAGE_VENV/var/lock/$PIP.lock"

# Issue #33155: Pythons installed using the python.org macOS installers
# for Python < 3.10 identify macOS Big Sur and newer as "10.16", causing
# pip to refuse to install wheels tagged macosx_11_0_x86_64
export SYSTEM_VERSION_COMPAT=0

# Finally actually do the installation (the "SHARED" tells pip2/3-lock
# to apply a shared lock)
sage-flock -s $LOCK $PYTHON -m pip install $pip_install_flags "$@"
if [ $? -ne 0 ]; then
    # --ignore-installed : Force pip to re-install package even if it thinks it's
    #                      already installed (for which it sometimes gets false
    #                      positives for partially-installed packages).
    # --no-deps          : Don't install runtime dependencies from PyPI.
    extra_pip_install_flags="--no-deps --ignore-installed --ignore-requires-python"
    echo >&2 "Warning: installing with \"$PYTHON -m pip install $pip_install_flags\" failed. Retrying, adding \"$extra_pip_install_flags\""
    sage-flock -s $LOCK $PYTHON -m pip install $pip_install_flags $extra_pip_install_flags "$@"
    if [ $? -ne 0 ]; then
        echo >&2 "Error: installing with pip  failed"
        exit 3
    else
        echo >&2 "Warning: The installation needed to use \"$extra_pip_install_flags\" to succeed. This means that a dependencies file in build/pkgs/ needs to be updated. Please report this to sage-devel@googlegroups.com, including the build log of this package."
    fi
fi
