#!/usr/bin/env bash

# This script serves as the cffi build step of the
# [**Python Buildpack**](https://github.com/heroku/heroku-buildpack-python)
# compiler.
#
# A [buildpack](https://devcenter.heroku.com/articles/buildpacks) is an
# adapter between a Python application and Heroku's runtime.
#
# This script is invoked by [`bin/compile`](/).

if [[ "$STACK" == "heroku-16" ]]; then
    # libffi is pre-installed in the stack image so there is no need to vendor it.
    return 0
fi

# The location of the pre-compiled libffi binary.
VENDORED_LIBFFI="http://helmsman-backend.oss-cn-shenzhen.aliyuncs.com/heroku/lang-python/$STACK/libraries/vendor/libffi.tar.gz"

PKG_CONFIG_PATH="/app/.heroku/vendor/lib/pkgconfig:$PKG_CONFIG_PATH"

# Syntax sugar.
# shellcheck source=bin/utils
source "$BIN_DIR/utils"

# If a package using cffi exists within requirements, use vendored libffi.
if (pip-grep -s requirements.txt argon2-cffi bcrypt cffi cryptography django[argon2] Django[argon2] django[bcrypt] Django[bcrypt] PyNaCl pyOpenSSL PyOpenSSL requests[security] misaka &> /dev/null) then

  if [ ! -d ".heroku/vendor/lib/libffi-3.1" ]; then
    echo "-----> Noticed cffi. Bootstrapping libffi."
    mkdir -p .heroku/vendor
    # Download and extract libffi into target vendor directory.
    curl "$VENDORED_LIBFFI" -s | tar zxv -C .heroku/vendor &> /dev/null
  fi

  LIBFFI=$(pwd)/vendor
  export LIBFFI
fi
