#!/usr/bin/env bash
set -euo pipefail

script_directory=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
repository_root=$(cd -- "${script_directory}/../../.." && pwd)
tooling_root="${repository_root}/.local/recursion-python-sdk"
binary_directory="${tooling_root}/bin"

export UV_CACHE_DIR="${UV_CACHE_DIR:-${tooling_root}/cache}"
export UV_PYTHON_INSTALL_DIR="${UV_PYTHON_INSTALL_DIR:-${tooling_root}/python}"
export UV_PYTHON_BIN_DIR="${UV_PYTHON_BIN_DIR:-${tooling_root}/python-bin}"
export UV_TOOL_DIR="${UV_TOOL_DIR:-${tooling_root}/tools}"

uv_executable=$(command -v uv || true)
if [ "${uv_executable}" = "${script_directory}/uv" ]; then
  uv_executable=''
fi

if [ -z "${uv_executable}" ]; then
  uv_executable="${binary_directory}/uv"
  if [ ! -x "${uv_executable}" ]; then
    if [ "$(uname -s)" != Linux ] || [ "$(uname -m)" != x86_64 ]; then
      echo 'Automatic uv bootstrap requires Linux x86_64; provide uv on PATH for this platform.' >&2
      exit 1
    fi

    uv_version='0.12.14'
    uv_archive_sha256='18ef5c3888ae59828cb13f38d57e9389b8173ecc719eff163bfafc74b38f5936'
    uv_archive_name='uv-x86_64-unknown-linux-gnu.tar.gz'
    uv_archive_url="https://github.com/astral-sh/uv/releases/download/${uv_version}/${uv_archive_name}"
    uv_download_retry_count=3
    uv_download_connection_timeout_seconds=10
    uv_download_timeout_seconds=120
    uv_executable_file_mode='0755'
    mkdir -p "${binary_directory}"
    download_directory=$(mktemp -d "${tooling_root}/download.XXXXXX")
    temporary_executable="${binary_directory}/uv.$$.tmp"
    trap 'rm -rf -- "${download_directory}"; rm -f -- "${temporary_executable}"' EXIT

    curl --fail --location --silent --show-error --retry "${uv_download_retry_count}" \
      --connect-timeout "${uv_download_connection_timeout_seconds}" \
      --max-time "${uv_download_timeout_seconds}" \
      --output "${download_directory}/${uv_archive_name}" "${uv_archive_url}"
    printf '%s  %s\n' "${uv_archive_sha256}" "${download_directory}/${uv_archive_name}" \
      | sha256sum --check --status
    tar --extract --gzip --file "${download_directory}/${uv_archive_name}" \
      --directory "${download_directory}"
    install -m "${uv_executable_file_mode}" \
      "${download_directory}/uv-x86_64-unknown-linux-gnu/uv" "${temporary_executable}"
    mv -f -- "${temporary_executable}" "${uv_executable}"
    rm -rf -- "${download_directory}"
    trap - EXIT
  fi
fi

export PATH="${binary_directory}:${PATH}"
exec "${uv_executable}" "$@"
