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

# update-homebrew-formula.sh <version> <checksums-file>
#
# Emits a Homebrew formula (to stdout) for the PREBUILT basemind binary, pulling
# the per-platform archive URLs from the GitHub release and the sha256 digests
# from the release checksums file (`basemind_<version>_checksums.txt`). This
# replaces goreleaser's `brews:` generator. Run only for stable releases.
#
# The archives contain `basemind` + `lib/` at the root; the binary's rpath
# ($ORIGIN/lib on Linux, @loader_path/lib on macOS) resolves the bundled native
# libs, so the formula just drops everything into libexec and symlinks the binary.

if [ $# -ne 2 ]; then
  echo "Usage: $0 <version> <checksums-file>" >&2
  exit 1
fi

VERSION="$1"
SUMS="$2"
BASE="https://github.com/Goldziher/basemind/releases/download/v${VERSION}"

sha_for() {
  awk -v f="basemind-$1.tar.gz" '{n=$NF; sub(/^[*]/, "", n); if (n == f) print $1}' "$SUMS"
}

# Intel macOS (x86_64-apple-darwin) is intentionally not shipped — Apple Silicon only.
MAC_ARM=$(sha_for aarch64-apple-darwin)
LINUX_ARM=$(sha_for aarch64-unknown-linux-gnu)
LINUX_X64=$(sha_for x86_64-unknown-linux-gnu)

for pair in "aarch64-apple-darwin:$MAC_ARM" \
  "aarch64-unknown-linux-gnu:$LINUX_ARM" "x86_64-unknown-linux-gnu:$LINUX_X64"; do
  if [ -z "${pair#*:}" ]; then
    echo "missing checksum for ${pair%%:*} in $SUMS" >&2
    exit 1
  fi
done

cat <<EOF
# typed: false
# frozen_string_literal: true

# Generated by scripts/update-homebrew-formula.sh — do not edit by hand.
class Basemind < Formula
  desc "Full AI context layer over MCP — code-map, document RAG, memory, web, git"
  homepage "https://github.com/Goldziher/basemind"
  version "${VERSION}"
  license "MIT"

  # Apple Silicon only — Intel macOS is not supported.
  on_macos do
    on_arm do
      url "${BASE}/basemind-aarch64-apple-darwin.tar.gz"
      sha256 "${MAC_ARM}"
    end
    on_intel do
      odie "basemind does not ship Intel macOS (x86_64) binaries; Apple Silicon (arm64) only"
    end
  end

  on_linux do
    on_arm do
      url "${BASE}/basemind-aarch64-unknown-linux-gnu.tar.gz"
      sha256 "${LINUX_ARM}"
    end
    on_intel do
      url "${BASE}/basemind-x86_64-unknown-linux-gnu.tar.gz"
      sha256 "${LINUX_X64}"
    end
  end

  def install
    # Archive root holds the binary + lib/ of bundled native libs; the binary's
    # rpath resolves lib/ relative to its own location, so keep them together in
    # libexec and expose the binary on PATH via a symlink.
    libexec.install Dir["*"]
    bin.install_symlink libexec/"basemind"
  end

  test do
    assert_match version.to_s, shell_output("#{bin}/basemind --version")
  end
end
EOF
