#!/bin/bash

set -euo pipefail

script_path=$(cd $(dirname $0); pwd)
driving_root=$(cd ${script_path}/../../..; pwd)
requirements_file=$1
python_bin=$2

# Step 1: compile requirements.txt
pip-compile ${requirements_file}

# Step 2: Download wheels
tmpdir=$(mktemp -d)
trap "rm -r ${tmpdir}" EXIT
mkdir ${tmpdir}/wheels
${python_bin} -m pip wheel -w ${tmpdir}/wheels -r ${requirements_file} >/dev/null

cd ${tmpdir}

# Step 3: unzip the wheels
for file in ${tmpdir}/wheels/*.whl; do
  dest_dir="${tmpdir}/$(basename ${file})"
  mkdir ${dest_dir}
  unzip ${file} -d ${dest_dir} >/dev/null
done

# Step 4: generate bazel rules
all_libs=()
echo 'load("//experimental/sguo/pip:pip.bzl", "py_library_from_whl")'
echo 'load("//build:z3.bzl", "z3_file")'
echo ""
echo "def load_requirements():"
for dir in *.whl; do
  ${driving_root}/scripts/build/upload-to-third-party.sh wheels/${dir} >/dev/null
  sha256=$(sha256sum wheels/${dir} | cut -d" " -f1)
  echo "    z3_file("
  echo "        name = \"${dir}\","
  echo "        bucket = \"zoox-third-party\","
  echo "        path = \"${sha256}/${dir}\","
  echo "        sha256 = \"${sha256}\","
  echo "    )"
  echo ""
  name=$(echo ${dir} | cut -d- -f1)
  echo "    py_library_from_whl("
  echo "        whl = \"${dir}\","
  echo "        outs = ["
  ( cd ${dir} && find -type f -not -name "* *" -printf '%P\0' | xargs -0 -n 1 -I{} echo "            \"{}\"," )
  echo "        ],"
  echo "    )"
  echo ""
  all_libs+=(${name})
done
echo "    native.py_library("
echo "        name = \"requirements\","
echo "        deps = ["
for lib in ${all_libs[@]}; do
  echo "            \":${lib}\","
done
echo "        ],"
echo "    )"
