#!/usr/bin/env bash
# Filename: uv-install.sh
# Ensures `uv` and `uvx` are installed in /usr/local/bin.
# Checks the installed version via `uv --version`, compares it against
# the latest GitHub release tag for astral-sh/uv, and only installs
# when missing or older than the latest available release.
# Supports Linux x86_64 and arm64/aarch64 and downloads the matching
# musl tarball from Astral's GitHub-backed release host.

set -euo pipefail

REPO="astral-sh/uv"
API_URL="https://api.github.com/repos/${REPO}/releases/latest"
DOWNLOAD_BASE_URL="https://releases.astral.sh/github/uv/releases/download"
INSTALL_DIR="/usr/local/bin"
UV_INSTALL_PATH="${INSTALL_DIR}/uv"
UVX_INSTALL_PATH="${INSTALL_DIR}/uvx"

if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
  echo "Error: this script must be run as root." >&2
  exit 1
fi

need_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Error: required command not found: $1" >&2
    exit 1
  fi
}

need_cmd wget
need_cmd tar
need_cmd mktemp
need_cmd install
need_cmd uname
need_cmd arch

tmp_dir=""
cleanup() {
  [[ -n "$tmp_dir" ]] && rm -rf "$tmp_dir"
}
trap cleanup EXIT

extract_version() {
  echo "$1" | grep -Eo '[0-9]+([.][0-9]+)+' | head -n1 || true
}

normalize_version() {
  echo "$1" | sed 's/^v//'
}

release_version_from_tag() {
  local tag extracted
  tag="$1"
  extracted="$(extract_version "$tag")"
  if [[ -n "$extracted" ]]; then
    echo "$extracted"
  else
    normalize_version "$tag"
  fi
}

version_cmp() {
  # Echoes: -1 (a<b), 0 (a==b), 1 (a>b)
  local a b first
  a="$(normalize_version "$1")"
  b="$(normalize_version "$2")"
  if [[ "$a" == "$b" ]]; then
    echo 0
    return
  fi
  first="$(printf '%s\n%s\n' "$a" "$b" | sort -V | head -n1)"
  if [[ "$first" == "$a" ]]; then
    echo -1
  else
    echo 1
  fi
}

raw_os="$(uname -s)"
raw_arch="$(arch)"

case "$raw_os" in
  Linux)
    uv_os="unknown-linux-musl"
    ;;
  *)
    echo "Error: unsupported OS '${raw_os}'. Supported: Linux." >&2
    exit 1
    ;;
esac

case "$raw_arch" in
  x86_64|amd64)
    uv_arch="x86_64"
    ;;
  arm64|aarch64)
    uv_arch="aarch64"
    ;;
  *)
    echo "Error: unsupported architecture '${raw_arch}'. Supported: x86_64, arm64." >&2
    exit 1
    ;;
esac

echo "Detected platform: os=${raw_os}, arch=${raw_arch}"

release_json="$(wget -qO- "$API_URL")"

if command -v jq >/dev/null 2>&1; then
  latest_version="$(echo "$release_json" | jq -r '.tag_name // empty' | head -n1)"
else
  latest_version="$(
    echo "$release_json" \
      | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
      | head -n1
  )"
fi

if [[ -z "${latest_version:-}" ]]; then
  echo "Error: could not determine latest release version for ${REPO}." >&2
  exit 1
fi

latest_version="$(release_version_from_tag "$latest_version")"
download_url="${DOWNLOAD_BASE_URL}/${latest_version}/uv-${uv_arch}-${uv_os}.tar.gz"

installed_version=""
if command -v uv >/dev/null 2>&1; then
  installed_version="$(extract_version "$(uv --version 2>/dev/null || true)")"
fi

if [[ -n "$installed_version" ]]; then
  installed_version="$(normalize_version "$installed_version")"
  cmp_result="$(version_cmp "$installed_version" "$latest_version")"
  should_install=true
  if [[ "$cmp_result" -eq 0 ]]; then
    echo "uv ${installed_version} is already the latest version."
    should_install=false
  fi
  if [[ "$cmp_result" -gt 0 ]]; then
    echo "Installed uv (${installed_version}) is newer than latest GitHub release (${latest_version}); skipping install."
    should_install=false
  fi
  if [[ "$should_install" == true ]]; then
    echo "Updating uv from ${installed_version} to ${latest_version}..."
  fi
else
  should_install=true
  echo "uv is not currently installed or version is unreadable; installing latest (${latest_version})..."
fi

if [[ "$should_install" == true ]]; then
  tmp_dir="$(mktemp -d)"

  uv_tarball_name="$(basename "$download_url")"
  tarball_path="${tmp_dir}/${uv_tarball_name}"

  echo "Downloading: $download_url"
  wget -qO "$tarball_path" "$download_url"

  tar -xzf "$tarball_path" -C "$tmp_dir"

  uv_path="$(
    find "$tmp_dir" -type f -name "uv" -perm -u+x \
      | head -n1 || true
  )"
  if [[ -z "$uv_path" ]]; then
    uv_path="$(
      find "$tmp_dir" -type f -name "uv" \
        | head -n1 || true
    )"
  fi

  uvx_path="$(
    find "$tmp_dir" -type f -name "uvx" -perm -u+x \
      | head -n1 || true
  )"
  if [[ -z "$uvx_path" ]]; then
    uvx_path="$(
      find "$tmp_dir" -type f -name "uvx" \
        | head -n1 || true
    )"
  fi

  if [[ -z "$uv_path" ]]; then
    echo "Error: could not find 'uv' binary in extracted archive." >&2
    exit 1
  fi

  if [[ -z "$uvx_path" ]]; then
    echo "Error: could not find 'uvx' binary in extracted archive." >&2
    exit 1
  fi

  if [[ -e "$UV_INSTALL_PATH" ]]; then
    rm -f "$UV_INSTALL_PATH"
  fi

  if [[ -e "$UVX_INSTALL_PATH" ]]; then
    rm -f "$UVX_INSTALL_PATH"
  fi

  install -o root -g root -m 755 "$uv_path" "$UV_INSTALL_PATH"
  install -o root -g root -m 755 "$uvx_path" "$UVX_INSTALL_PATH"

  echo "Done. Installed ${UV_INSTALL_PATH} and ${UVX_INSTALL_PATH} (uv version ${latest_version})"
fi
