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

# update-homebrew-formula.sh <version> <checksums-file>
#
# Emits a Homebrew formula (to stdout) for the PREBUILT uncomment binary, pulling
# the per-platform archive URLs from the GitHub release and the sha256 digests from
# the release checksums file (`uncomment_<version>_checksums.txt`). This replaces
# goreleaser's `brews:` generator. Run only for stable releases.
#
# The archives contain a single `uncomment` binary at the root, so the formula just
# installs it onto PATH.

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

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

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

MAC_ARM=$(sha_for aarch64-apple-darwin)
MAC_X64=$(sha_for x86_64-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" "x86_64-apple-darwin:$MAC_X64" \
	"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 Uncomment < Formula
  desc "A fast, accurate comment removal tool using tree-sitter for AST parsing"
  homepage "https://github.com/Goldziher/uncomment"
  version "${VERSION}"
  license "MIT"

  on_macos do
    on_arm do
      url "${BASE}/uncomment-aarch64-apple-darwin.tar.gz"
      sha256 "${MAC_ARM}"
    end
    on_intel do
      url "${BASE}/uncomment-x86_64-apple-darwin.tar.gz"
      sha256 "${MAC_X64}"
    end
  end

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

  def install
    bin.install "uncomment"
  end

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