#!/bin/bash

set -euo pipefail

DRIVING_REPO="$(bazel info workspace)"
KERNEL_DIR=${DRIVING_REPO}/infra/jupyterhub/docker
TMP_DEST_DIR=$(mktemp -d)
echo "Saving temp output to ${TMP_DEST_DIR}" >&2

echo "Removing files from previous deployments (if they exist)" >&2
rm -f ${DRIVING_REPO}/infra/jupyterhub/BUILD
rm -f ${DRIVING_REPO}/infra/jupyterhub/py_deps.bzl
rm -f ${DRIVING_REPO}/infra/jupyterhub/py_proto_deps.bzl
rm -rf ${KERNEL_DIR}/driving_py2_env
rm -rf ${KERNEL_DIR}/driving_py3_env

echo "Finding all required dependencies" >&2
python ${DRIVING_REPO}/infra/jupyterhub/get_all_py2_deps.py > ${DRIVING_REPO}/infra/jupyterhub/py_deps.bzl
python ${DRIVING_REPO}/infra/jupyterhub/get_all_py_proto_deps.py > ${DRIVING_REPO}/infra/jupyterhub/py_proto_deps.bzl
cp ${DRIVING_REPO}/infra/jupyterhub/BUILD.tmpl ${DRIVING_REPO}/infra/jupyterhub/BUILD

echo "Building archives for all Python 2 dependencies" >&2
bazel run //pipedream/common/archive:build_bazel_archive -- \
    --target //infra/jupyterhub:driving_py2_env \
    --archive-dest ${TMP_DEST_DIR}/driving_py2_env.tar \
    --nocheck_visibility \
    --color=yes \
    "$@"

echo "Building archives for all Python 3 dependencies" >&2
bazel run --config=cuda //pipedream/common/archive:build_bazel_archive -- \
    --target //infra/jupyterhub:driving_py3_env \
    --archive-dest ${TMP_DEST_DIR}/driving_py3_env.tar \
    --nocheck_visibility \
    --color=yes \
    --config=tf-2.2 \
    "$@"

echo "Creating Python 2 kernel" >&2
mkdir -p ${KERNEL_DIR}/driving_py2_env
chmod 755 ${KERNEL_DIR}/driving_py2_env
(
    cd ${KERNEL_DIR}/driving_py2_env
    tar xf ${TMP_DEST_DIR}/driving_py2_env.tar
    # Removing typing-3.6.6 because it's a py3 package. Including it here would cause
    # `import typing` to fail.
    rm -rf driving_py2_env.runfiles/pypi__typing_3_6_6
)

echo "Creating Python 3 kernel" >&2
mkdir -p ${KERNEL_DIR}/driving_py3_env
chmod 755 ${KERNEL_DIR}/driving_py3_env
(
    cd ${KERNEL_DIR}/driving_py3_env
    tar xf ${TMP_DEST_DIR}/driving_py3_env.tar
    # Removing pypi__future_python_deps because it's a py2 package
    rm -rf driving_py3_env.runfiles/pypi__future_python_deps
)

echo "Deleting temp output" >&2
rm -rf ${TMP_DEST_DIR}
echo "Done" >&2
