#!/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"
install_marker="$install_dir/.installed"
archive_ext="tar.gz"

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

if [ ! -x "$binary" ] || [ ! -f "$install_marker" ]; then
  mkdir -p "$cache_root"
  lock_dir="$cache_root/$version-$os-$arch.lock"
  tmp_dir=""
  cleanup_install() {
    if [ -n "$tmp_dir" ]; then
      rm -rf "$tmp_dir"
    fi
    rmdir "$lock_dir" 2>/dev/null || true
  }

  lock_waits=0
  while ! mkdir "$lock_dir" 2>/dev/null; do
    lock_waits=$((lock_waits + 1))
    if [ "$lock_waits" -ge 300 ]; then
      echo "Timed out waiting for bibsync install lock: $lock_dir" >&2
      exit 2
    fi
    sleep 1
  done
  trap cleanup_install EXIT

  if [ -x "$binary" ]; then
    touch "$install_marker"
  else
    tmp_dir="$(mktemp -d "$cache_root/.install.XXXXXX")"
    staging_dir="$tmp_dir/extract"
    mkdir -p "$staging_dir"

    archive="bibsync-$version-$os-$arch.$archive_ext"
    url="https://github.com/isaac-cf-wong/bibsync/releases/download/$version/$archive"
    tmp="$tmp_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 "$staging_dir"
    else
      tar -xzf "$tmp" -C "$staging_dir"
    fi
    staging_binary="$staging_dir/$(basename "$binary")"
    chmod +x "$staging_binary"
    mkdir -p "$install_dir"
    mv "$staging_binary" "$binary"
    touch "$install_marker"
    rm -rf "$tmp_dir"
    tmp_dir=""
  fi
  cleanup_install
  trap - EXIT
fi

exec "$binary" "$@"
