#!/usr/bin/env bash
set -euo pipefail

# Consolidated installation script for use by both Travis and humans.
#
# First installs a known-good version of pip, then any requirements
# specified in the EXTERNAL_REQUIREMENTS environment variable (e.g.,
# coveralls); then installs the project requirements, constrained by
# etc/requirements.txt; then editably installs zipline itself.

echo
echo "Installing zipline using $(which python)"
echo

set -x

python --version
python -m pip --version

# New releases of pip have frequently caused strange issues. Make sure
# we know exactly which version we're working with.
python -m pip install pip==19.3.1
# Python 3.5's default setuptools is 28.8.0; flake8 requires >=30.
# The newest version of this one is probably fine.
python -m pip install --upgrade setuptools

# Pip's command line options can also be set with environment variables:
# all subsequent invocations of pip will use these options.
#
# XXX: Pip works fine with relative paths if they are provided via the
# -c/--constraint option, but not via the PIP_CONSTRAINT environment
# variable: use `realpath` to make the path absolute.
export PIP_CONSTRAINT="$(realpath etc/requirements.txt)"
# XXX: bcolz has to be compiled against our specific version of numpy:
# by default, it uses an incompatible pre-compiled wheel.
export PIP_NO_BINARY=bcolz

# Install external requirements first: if they share any of our
# transitive dependencies, we want our pinned versions to win.
if [ "${EXTERNAL_REQUIREMENTS:-}" ]; then
    # Note: If EXTERNAL_REQUIREMENTS is unset, the expression in the
    # above test expands to the empty string, which fails the test.
    # (Simply expanding $EXTERNAL_REQUIREMENTS causes an error with the
    # -u option, which helps prevent many other kinds of errors.)
    echo "Installing additional packages: $EXTERNAL_REQUIREMENTS"
    python -m pip install "$EXTERNAL_REQUIREMENTS"
fi

# These have to be installed first so that the other requirements can be
# compiled against the specific versions we use.
python -m pip install numpy Cython

python -m pip install \
    -r etc/requirements.txt \
    -r etc/requirements_dev.txt \
    -r etc/requirements_blaze.txt

# TODO: resolve this error message:
# blaze keepalive-30.g31060532 has requirement odo>=0.5.0, but you'll have odo 0.3.2+729.gda7f26d which is incompatible.

# All requirements should already be satisfied by this point.
python -m pip install -e .[all]

# Make sure it's installed and working.
which zipline
zipline --help

set +x

echo
echo "Installation complete!"
echo
