#!/bin/bash
#
# runs dh_virtualenv to build the virtualenv in the build directory

set -e

export DH_VIRTUALENV_INSTALL_ROOT=/opt/venvs

# make sure that the virtualenv links to the specific version of python, by
# dereferencing the python3 symlink.
#
# Otherwise, if somebody tries to install (say) the stretch package on buster,
# they will get a confusing error about "No module named 'mathesar'", because
# python won't look in the right directory. At least this way, the error will
# be a *bit* more obvious.
#
SNAKE=$(readlink -e /usr/bin/python3)

# try to set the CFLAGS so any compiled C extensions are compiled with the most
# generic as possible x64 instructions, so that compiling it on a new Intel chip
# doesn't enable features not available on older ones or AMD.
#

case $(dpkg-architecture -q DEB_HOST_ARCH) in
    amd64)
        export CFLAGS=-march=x86-64
        ;;
esac

dh_virtualenv -v --extra-pip-arg "--no-index" --extra-pip-arg "--find-links=file://${PWD}/debian/pypi" --extra-pip-arg "--no-build-isolation"

PACKAGE_BUILD_DIR="$(pwd)/debian/mathesar"
VIRTUALENV_DIR="${PACKAGE_BUILD_DIR}${DH_VIRTUALENV_INSTALL_ROOT}/mathesar"
TARGET_PYTHON="${VIRTUALENV_DIR}/bin/python"

# add a dependency on the right version of python to substvars.
PYPKG=$(basename "$SNAKE")
echo "mathesar:pydepends=$PYPKG" >> debian/mathesar.substvars


# add a couple of triggers.  This is needed so that dh-virtualenv can rebuild
# the venv when the system python changes (see
# https://dh-virtualenv.readthedocs.io/en/latest/tutorial.html#step-2-set-up-packaging-for-your-project)
#
# we do it here rather than the more conventional way of just adding it to
# debian/mathesar.triggers, because we need to add a trigger on the
# right version of python.
cat >>"debian/.debhelper/generated/mathesar/triggers" <<EOF
# triggers for dh-virtualenv
interest-noawait $SNAKE
interest dh-virtualenv-interpreter-update

EOF
