#!/usr/bin/env bash

set -euo pipefail

PROJECT_ROOT="$(realpath "$(dirname "$0")/..")"

# Which requirements.txt to pass to pip
REQUIREMENTS_FILE="${PROJECT_ROOT}/requirements.txt"

# Where to put the final output in
PYLIBS_DIR="${PROJECT_ROOT}/pylibs"

# Distinguish Ubuntu Touch versions
UT_FRAMEWORK="${SDK_FRAMEWORK:-''}"

if [[ -n "$UT_FRAMEWORK" ]]; then
  PYLIBS_DIR="${PROJECT_ROOT}/pylibs-${UT_FRAMEWORK}"
  REQUIREMENTS_FILE="${PROJECT_ROOT}/requirements-${UT_FRAMEWORK}.txt"
fi

echo "Using $REQUIREMENTS_FILE for resolving dependencies"

# List the glob patterns of files/directories you want in the qml plugin
# The idea here is to only declare what's _required_ to reduce our size a bit
PYTHON_INCLUDED_PATTERNS=(
  "soupsieve"
  "markdown"
  "jinja2"
  "markupsafe"
  "bs4"
  "cssutils"
  "encutils"
  # "pynliner" # we include our own instead
  "pygments"
  "html2text"
  "importlib_metadata"
  "zipp"
  "typing_extensions*"
)

# Remove something from the copied-over modules, to improve final size
PYTHON_EXCLUDED_PATHS=(
  # cssutils comes with a large test suite
  # which we don't really need in the snap
  # it saves us about 1MB
  "cssutils/tests"
)

if [ ! -f "${REQUIREMENTS_FILE}" ]; then
  echo "${REQUIREMENTS_FILE} does not exist!" >&2
  exit 1
fi

if ! command -v pip3; then
  echo "pip3 binary not found!" >&2
  exit 1
fi

# Clear our output dir
rm -vfr "${PYLIBS_DIR}"
mkdir -vp "${PYLIBS_DIR}"

PYTHONUSERBASE="$(mktemp -d)"
echo "Set temporary PYTHONUSERBASE to: ${PYTHONUSERBASE}"
export PYTHONUSERBASE

echo "Installing required modules via pip..."
pip3 install --upgrade -r "${REQUIREMENTS_FILE}" --user
PYTHON_PACKAGES_DIR="$(python3 -m site --user-site)"
echo "Python packages were installed to: ${PYTHON_PACKAGES_DIR}"
echo "Installation done."

echo "Copying over requested python modules..."
for pattern in "${PYTHON_INCLUDED_PATTERNS[@]}"; do
  cp -vr "${PYTHON_PACKAGES_DIR}/"${pattern} "${PYLIBS_DIR}/"
done
echo "Copying done."

echo "Trimming unneeded things from the modules..."
for excludedPath in "${PYTHON_EXCLUDED_PATHS[@]}"; do
  rm -vr "${PYLIBS_DIR}/${excludedPath:?entry in PYTHON_EXCLUDED_PATHS is null or unset}"
done
echo "Trimming done."

echo "Cleaning up pip data..."
rm -vr "${PYTHONUSERBASE}"
echo "Cleaning done."

echo "Done! Data has been installed to: ${PYLIBS_DIR}"
