#!/usr/bin/env sh -u
#

_install () {
  package=$1
  echo "installing $package from $PIP_WHEEL_DIR..."
  pip install --use-wheel --no-index --find-links="$PIP_WHEEL_DIR" $package

  if [ $? -eq 1 ]; then
    echo "$package not found in cache, downloading..."

    if [ $package == 'wheel' ]; then
      pip install wheel
    else
      pip download --dest="$PIP_CACHE_DIR" $package
      pip wheel --no-index --find-links="$PIP_CACHE_DIR" \
        --wheel-dir="$PIP_WHEEL_DIR" $package
      pip install --use-wheel --no-index --find-links="$PIP_WHEEL_DIR" $package
    fi
  fi
}

if [ "$1" == "-e" ]; then
  pip install $@
else
  _install wheel

  for package in "$@"; do
    _install $package
  done
fi
