#!/usr/bin/env bash

# Set error handling
set -o errexit
set -o nounset
set -o pipefail

# Get the root directory and third_party directory
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"

# Include the common functions
source "${ROOT_DIR}/hack/lib/init.sh"

function download_deps() {
  if ! command -v uv &> /dev/null; then
    pip install uv
  fi
  # uv sync --all-extras to install all dependencies
  uv sync --locked
  if [[ "${DEPS_ONLY:-false}" == "false" ]]; then
    uv pip install pre-commit==3.7.1
    uv run pre-commit install
  fi
}

# Update community backends
function make_community_backends() {
  local tmp_dir
  tmp_dir=$(mktemp -d -t gpustack-community-backends.XXXXXX)

  # shellcheck disable=SC2064
  trap "rm -rf \"${tmp_dir}\"" EXIT

  local target_dir="${ROOT_DIR}/gpustack/assets/"

  gpustack::log::info "pulling community backends"

  # Clone the repository
  git clone https://gh-proxy.com/https://github.com/gpustack/community-inference-backends "${tmp_dir}"

  # Build the community backends
  (
    cd "${tmp_dir}"
    if [[ "${UV_SYSTEM_PYTHON:-}" == "1" ]]; then
      # In Docker build, use system Python directly
      uv pip install PyYAML && uv run make
    else
      # For local development, use virtual environment
      uv venv && source .venv/bin/activate && uv pip install PyYAML && uv run make
    fi
  )

  # Create target directory and copy the yaml file
  mkdir -p "${target_dir}"
  cp "${tmp_dir}/dist/community-inference-backends.yaml" "${target_dir}/community-inference-backends.yaml"

  gpustack::log::info "community backends updated successfully"
}

#
# main
#

gpustack::log::info "+++ DEPENDENCIES +++"
download_deps
make_community_backends
gpustack::log::info "--- DEPENDENCIES ---"
