#!/usr/bin/env bash
#
# Render the Homebrew formula for rdbms-playground to stdout.
#
# Pure function of its inputs — NO network, NO jq/ruby — so it runs unchanged in
# the CI job container (node:22-bookworm-slim: bash + coreutils only). Given a
# version and the four macOS/Linux asset SHA-256 hashes it prints a complete
# formula. The publish.yaml `homebrew-tap` job fetches the hashes from the
# release .sha256 sidecars and commits the result into lazyeval/homebrew-tap as
# Formula/rdbms-playground.rb.
#
# The release assets are bare binaries (no archive), so Homebrew stages the
# single downloaded file in the build dir and `install` drops it under a stable
# name. Windows is intentionally absent — Homebrew has no Windows port (Scoop /
# winget cover Windows).
#
# Usage: render-homebrew-formula.sh <version> <mac-arm> <mac-intel> <linux-arm> <linux-intel>
#   <version>      version, with or without a leading 'v'
#   <mac-arm>      sha256 of aarch64-apple-darwin
#   <mac-intel>    sha256 of x86_64-apple-darwin
#   <linux-arm>    sha256 of aarch64-unknown-linux-musl
#   <linux-intel>  sha256 of x86_64-unknown-linux-musl
set -euo pipefail

if [ "$#" -ne 5 ]; then
  echo "usage: $0 <version> <mac-arm> <mac-intel> <linux-arm> <linux-intel>" >&2
  exit 2
fi

version=${1#v}
mac_arm=$2
mac_intel=$3
linux_arm=$4
linux_intel=$5

base="https://git.lazyeval.net/oli/rdbms-playground/releases/download/v$version"

# Ruby interpolations (#{version}, #{bin}) must survive verbatim into the
# formula; they contain no '$', so this unquoted heredoc leaves them untouched
# and only expands the shell variables below.
cat <<EOF
# typed: false
# frozen_string_literal: true

# rdbms-playground — installs the prebuilt release binary for the host
# platform. Regenerated for each release by scripts/render-homebrew-formula.sh;
# do not edit by hand.
class RdbmsPlayground < Formula
  desc "Cross-platform TUI playground for learning relational databases"
  homepage "https://relplay.org"
  version "$version"
  license any_of: ["MIT", "Apache-2.0"]

  on_macos do
    on_arm do
      url "$base/rdbms-playground-v$version-aarch64-apple-darwin"
      sha256 "$mac_arm"
    end
    on_intel do
      url "$base/rdbms-playground-v$version-x86_64-apple-darwin"
      sha256 "$mac_intel"
    end
  end

  on_linux do
    on_arm do
      url "$base/rdbms-playground-v$version-aarch64-unknown-linux-musl"
      sha256 "$linux_arm"
    end
    on_intel do
      url "$base/rdbms-playground-v$version-x86_64-unknown-linux-musl"
      sha256 "$linux_intel"
    end
  end

  def install
    # The release asset is a single bare binary; Homebrew stages it in the
    # build dir under its (versioned) basename. Install it as a stable name.
    bin.install Dir["*"].first => "rdbms-playground"
  end

  test do
    assert_match "rdbms-playground #{version}", shell_output("#{bin}/rdbms-playground --version")
  end
end
EOF
