#!/usr/bin/env bash

set +e
runtime-fixer runtime.txt
PYTHON_VERSION=$(cat runtime.txt)

if [[ $PYTHON_VERSION =~ ^python-2 ]]; then
  if [[ "$PYTHON_VERSION" != "$LATEST_2" ]]; then
    puts-warn "The latest version of Python 2 is $LATEST_2 (you are using $PYTHON_VERSION, which is unsupported)."
    puts-warn "We recommend upgrading by specifying the latest version ($LATEST_2)."
    echo "       Learn More: https://devcenter.heroku.com/articles/python-runtimes"
  fi
else
  if [[ "$PYTHON_VERSION" != "$LATEST_3" ]]; then
    puts-warn "The latest version of Python 3 is $LATEST_3 (you are using $PYTHON_VERSION, which is unsupported)."
    puts-warn "We recommend upgrading by specifying the latest version ($LATEST_3)."
    echo "       Learn More: https://devcenter.heroku.com/articles/python-runtimes"
  fi

fi

if [[ "$STACK" != "$CACHED_PYTHON_STACK" ]]; then
    puts-step "Stack has changed from $CACHED_PYTHON_STACK to $STACK, clearing cache"
    rm -fr .heroku/python-stack .heroku/python-version .heroku/python .heroku/vendor
fi

if [ -f .heroku/python-version ]; then
  if [ ! "$(cat .heroku/python-version)" = "$PYTHON_VERSION" ]; then
      puts-step "Found $(cat .heroku/python-version), removing"
      rm -fr .heroku/python
  else
    SKIP_INSTALL=1
  fi
fi

if [ ! "$SKIP_INSTALL" ]; then
    puts-step "Installing $PYTHON_VERSION"

    # Prepare destination directory.
    mkdir -p .heroku/python

    mcount "version.python.$PYTHON_VERSION"

    echo "http://helmsman-backend.oss-cn-shenzhen.aliyuncs.com/heroku/lang-python/$STACK/runtimes/$PYTHON_VERSION.tar.gz is being downloaded..."
    if ! curl "http://helmsman-backend.oss-cn-shenzhen.aliyuncs.com/heroku/lang-python/$STACK/runtimes/$PYTHON_VERSION.tar.gz" -s | tar zxv -C .heroku/python &> /dev/null; then
      puts-warn "Requested runtime ($PYTHON_VERSION) is not available for this stack ($STACK)."
      puts-warn "Aborting.  More info: https://devcenter.heroku.com/articles/python-support"
      exit 1
    fi
    echo "http://helmsman-backend.oss-cn-shenzhen.aliyuncs.com/heroku/lang-python/$STACK/runtimes/$PYTHON_VERSION.tar.gz is downloaded successfully"

  # Record for future reference.
  echo "$PYTHON_VERSION" > .heroku/python-version
  echo "$STACK" > .heroku/python-stack
  FRESH_PYTHON=true

  hash -r
fi

# If Pip isn't up to date:
if [ "$FRESH_PYTHON" ] || [[ ! $(pip --version) == *$PIP_UPDATE* ]]; then

  puts-step "Installing pip"

  # Remove old installations.
  rm -fr /app/.heroku/python/lib/python2.7/site-packages/pip-*
  rm -fr /app/.heroku/python/lib/python2.7/site-packages/setuptools-*

  /app/.heroku/python/bin/python "$ROOT_DIR/vendor/get-pip.py" &> /dev/null

fi

set -e
hash -r
