#!/bin/bash

# Ensure pip dependencies are present
missing_deps=""
while IFS= read -r req; do
    # Check if the dependency is installed
    python3 -c "import pkg_resources; pkg_resources.require(\"$req\")" &>/dev/null
    if [ $? -ne 0 ]; then
        missing_deps+="\"$req\" "
        echo "Missing dependency: $req" >&2
    fi
done <<EOF
pip>22.0.2
cupy-cuda12x>=12.2,<14.0
numpy>=1.0.4,<2.0
cloudpickle>=3.0,<4.0
python-on-whales>=0.60.1,<1.0
Jinja2>=3.1.3,<4.0
packaging>=23.1
pyyaml>=6.0,<7.0
requests>=2.31.0,<3.0
psutil>=6.0.0,<7.0
EOF
if [ ! -z "$missing_deps" ]; then
  echo "" >&2
  echo "The Holoscan CLI requires that the PIP dependencies above be installed by the user \
when using an alternative installation than the holoscan python wheel. Install them in a virtual \
environment or on your global system with the command below:" >&2
  echo "" >&2
  echo "  $ python3 -m pip install $missing_deps" >&2
  echo "" >&2
  exit 1
fi

# Add --sdk and --sdk-version if not passed to `package`
ARGS=("$@")
if [ "$1" = "package" ]; then
  default_sdk="holoscan"
  default_sdk_version=""
  for i in "${!ARGS[@]}"; do
      arg="${ARGS[i]}"
      if [ "$arg" = "--sdk" ]; then
          sdk=${ARGS[i+1]}
      elif [ "$arg" = "--sdk-version" ]; then
          sdk_version=${ARGS[i+1]}
      fi
  done
  if [[ -z "$sdk" ]]; then
    ARGS+=("--sdk holoscan")
  fi
  if [[ -z "$sdk_version" ]]; then
    ARGS+=("--sdk-version 2.8.0")
  fi
fi

# Set PYTHONPATH to current holoscan install
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
export PYTHONPATH=${SCRIPT_DIR}/../python/lib

# Run CLI
python3 -m holoscan.cli ${ARGS[@]}
