#!/usr/bin/env bash
# Regenerate the Homebrew formula for a release.
#
# Usage: update-formula.sh <version> <dist-dir> <out-file>
#   <version>   release version without the leading 'v' (e.g. 0.1.0)
#   <dist-dir>  directory containing mind-<version>-<target>.tar.gz tarballs
#   <out-file>  formula path to write (e.g. Formula/mind.rb)
#
# Invoked by .github/workflows/release.yml; the formula it writes must match the
# committed Formula/mind.rb byte-for-byte except for the version, urls, and
# sha256 values, so releases produce a clean diff.
set -euo pipefail

version="$1"
dist="$2"
out="$3"
repo="jaemk/mind"
base="https://github.com/${repo}/releases/download/v${version}"

sha() {
  sha256sum "${dist}/mind-${version}-$1.tar.gz" | awk '{print $1}'
}

mac_arm="$(sha aarch64-apple-darwin)"
lin_arm="$(sha aarch64-unknown-linux-gnu)"
lin_x86="$(sha x86_64-unknown-linux-gnu)"

cat > "$out" <<EOF
# Auto-generated by .github/workflows/release.yml on each tagged release.
# The version, urls, and sha256 values are overwritten there; do not edit by hand.
class Mind < Formula
  desc "Manager for agent tooling: skills, agents, and rules"
  homepage "https://github.com/${repo}"
  version "${version}"
  license "MIT"

  on_macos do
    on_arm do
      url "${base}/mind-${version}-aarch64-apple-darwin.tar.gz"
      sha256 "${mac_arm}"
    end
  end

  on_linux do
    on_arm do
      url "${base}/mind-${version}-aarch64-unknown-linux-gnu.tar.gz"
      sha256 "${lin_arm}"
    end
    on_intel do
      url "${base}/mind-${version}-x86_64-unknown-linux-gnu.tar.gz"
      sha256 "${lin_x86}"
    end
  end

  def install
    bin.install "mind"
  end

  test do
    system "#{bin}/mind", "--version"
  end
end
EOF

echo "wrote ${out} for v${version}"
