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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
version="${BIBSYNC_VERSION:-}"

if [ -z "$version" ]; then
  version="$(git -C "$repo_root" describe --tags --exact-match HEAD 2>/dev/null || true)"
fi

if [ -z "$version" ]; then
  version="v$(sed -n 's/^version = "\(.*\)"/\1/p' "$repo_root/Cargo.toml" | head -n 1)"
fi

case "$(uname -s)" in
  Linux) os="linux" ;;
  Darwin) os="macos" ;;
  MINGW*|MSYS*|CYGWIN*) os="windows" ;;
  *)
    echo "Unsupported OS: $(uname -s)" >&2
    exit 2
    ;;
esac

case "$(uname -m)" in
  x86_64|amd64) arch="x86_64" ;;
  arm64|aarch64) arch="aarch64" ;;
  *)
    echo "Unsupported architecture: $(uname -m)" >&2
    exit 2
    ;;
esac

cache_root="${PRE_COMMIT_HOME:-${XDG_CACHE_HOME:-$HOME/.cache/pre-commit}}/bibsync"
install_dir="$cache_root/$version-$os-$arch"
binary="$install_dir/bibsync"
archive_ext="tar.gz"

if [ "$os" = "windows" ]; then
  binary="$install_dir/bibsync.exe"
  archive_ext="zip"
fi

if [ ! -x "$binary" ]; then
  mkdir -p "$install_dir"
  archive="bibsync-$version-$os-$arch.$archive_ext"
  url="https://github.com/isaac-cf-wong/bibsync/releases/download/$version/$archive"
  tmp="$install_dir/$archive"

  echo "Downloading $url" >&2
  if command -v curl >/dev/null 2>&1; then
    curl --fail --location --silent --show-error "$url" --output "$tmp"
  elif command -v wget >/dev/null 2>&1; then
    wget -q "$url" -O "$tmp"
  else
    echo "curl or wget is required to download the bibsync binary" >&2
    exit 2
  fi

  if [ "$archive_ext" = "zip" ]; then
    unzip -q -o "$tmp" -d "$install_dir"
  else
    tar -xzf "$tmp" -C "$install_dir"
  fi
  chmod +x "$binary"
fi

exec "$binary" "$@"
