#!/usr/bin/env bash
# Generate packaging/homebrew/rivet.rb from Cargo.toml version + GitHub release SHA256SUMS.
#
# Prerequisites: a GitHub Release for tag v<X> must exist with SHA256SUMS.txt and .tar.gz assets
# (produced by .github/workflows/release.yml).
#
# Usage:
#   ./dev/update_homebrew_formula.sh
#   GITHUB_REPOSITORY=owner/rivet ./dev/update_homebrew_formula.sh
#   ./dev/update_homebrew_formula.sh --tag v0.2.0-beta.1   # override tag (version still from tag)
#   ./dev/update_homebrew_formula.sh --tag v0.2.0-beta.1 --sums-file artifacts/SHA256SUMS.txt  # CI (no curl)
#
# After generation, copy packaging/homebrew/rivet.rb to your tap repo, e.g.:
#   https://github.com/<you>/homebrew-rivet/blob/main/Formula/rivet.rb
# Users install with: brew tap <you>/rivet && brew install rivet

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CARGO_TOML="${ROOT}/Cargo.toml"
OUT="${ROOT}/packaging/homebrew/rivet.rb"

usage() {
  echo "Usage: $0 [--tag vX.Y.Z] [--sums-file PATH]" >&2
  echo "  --sums-file   use local SHA256SUMS.txt (skips download; use with --tag in CI)" >&2
  exit 1
}

TAG_OVERRIDE=""
SUMS_FILE=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --tag)
      TAG_OVERRIDE="${2:-}"
      [[ -n "$TAG_OVERRIDE" ]] || usage
      shift 2
      ;;
    --sums-file)
      SUMS_FILE="${2:-}"
      [[ -n "$SUMS_FILE" ]] || usage
      shift 2
      ;;
    -h|--help) usage ;;
    *) echo "Unknown option: $1" >&2; usage ;;
  esac
done

if [[ ! -f "$CARGO_TOML" ]]; then
  echo "error: Cargo.toml not found at $CARGO_TOML" >&2
  exit 1
fi

# Use [[:space:]] — BSD sed on macOS does not treat \s as whitespace.
VERSION="$(grep -E '^version[[:space:]]*=' "$CARGO_TOML" | head -1 | sed -n 's/^version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p')"
if [[ -z "$VERSION" ]]; then
  echo "error: could not parse version from Cargo.toml" >&2
  exit 1
fi

if [[ -n "$TAG_OVERRIDE" ]]; then
  TAG="$TAG_OVERRIDE"
  # If tag is v0.1.2, version for formula should be 0.1.2
  if [[ "$TAG" == v* ]]; then
    VERSION="${TAG#v}"
  fi
else
  TAG="v${VERSION}"
fi

if [[ -n "$SUMS_FILE" && -z "$TAG_OVERRIDE" ]]; then
  echo "error: --sums-file requires --tag (Cargo.toml version may not match the release assets)" >&2
  exit 1
fi

# owner/repo from Cargo.toml repository = "https://github.com/org/repo"
REPO_URL="$(grep -E '^repository[[:space:]]*=' "$CARGO_TOML" | head -1 | sed -n 's/^repository[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' || true)"
GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-}"
if [[ -z "$GITHUB_REPOSITORY" && -n "$REPO_URL" ]]; then
  GITHUB_REPOSITORY="$(echo "$REPO_URL" | sed -E 's#https?://github.com/##' | sed 's/\.git$//' | tr -d '[:space:]')"
fi
if [[ -z "$GITHUB_REPOSITORY" || "$GITHUB_REPOSITORY" != */* ]]; then
  echo "error: set GITHUB_REPOSITORY=owner/repo or add a valid repository URL to Cargo.toml" >&2
  exit 1
fi

OWNER="${GITHUB_REPOSITORY%%/*}"
REPO_NAME="${GITHUB_REPOSITORY##*/}"
SUMS_URL="https://github.com/${OWNER}/${REPO_NAME}/releases/download/${TAG}/SHA256SUMS.txt"

if [[ -n "$SUMS_FILE" ]]; then
  if [[ ! -f "$SUMS_FILE" ]]; then
    echo "error: --sums-file not found: $SUMS_FILE" >&2
    exit 1
  fi
  TMP="$SUMS_FILE"
else
  TMP="$(mktemp)"
  cleanup() { rm -f "$TMP"; }
  trap cleanup EXIT
  echo "Fetching ${SUMS_URL} ..."
  if ! curl -fsSL "$SUMS_URL" -o "$TMP"; then
    echo "error: could not download SHA256SUMS (does release ${TAG} exist on ${GITHUB_REPOSITORY}?)" >&2
    exit 1
  fi
fi

# Expected asset basenames (must match release workflow)
declare -a ASSETS=(
  "rivet-${TAG}-aarch64-apple-darwin.tar.gz"
  "rivet-${TAG}-x86_64-apple-darwin.tar.gz"
  "rivet-${TAG}-aarch64-unknown-linux-gnu.tar.gz"
  "rivet-${TAG}-x86_64-unknown-linux-gnu.tar.gz"
)

lookup_sha() {
  local base="$1"
  local line
  line="$(grep -F " ${base}" "$TMP" | head -1 || true)"
  if [[ -z "$line" ]]; then
    # sha256sum may use " *file" or "  file"
    line="$(grep -E "[[:space:]]${base}$" "$TMP" | head -1 || true)"
  fi
  if [[ -z "$line" ]]; then
    echo "error: no checksum for ${base} in SHA256SUMS.txt" >&2
    exit 1
  fi
  echo "$line" | awk '{print $1}'
}

SHA_ARM_MAC="$(lookup_sha "${ASSETS[0]}")"
SHA_INTEL_MAC="$(lookup_sha "${ASSETS[1]}")"
SHA_ARM_LINUX="$(lookup_sha "${ASSETS[2]}")"
SHA_INTEL_LINUX="$(lookup_sha "${ASSETS[3]}")"

BASE_URL="https://github.com/${OWNER}/${REPO_NAME}/releases/download/${TAG}"
HOMEPAGE="https://github.com/${OWNER}/${REPO_NAME}"

mkdir -p "$(dirname "$OUT")"

cat > "$OUT" <<EOF
# typed: false
# frozen_string_literal: true

# Generated by dev/update_homebrew_formula.sh — do not edit checksums by hand.
# Re-run the script after each release.

class Rivet < Formula
  desc "CLI to export PostgreSQL and MySQL to Parquet/CSV (local, S3, GCS)"
  homepage "${HOMEPAGE}"
  version "${VERSION}"
  license "MIT"

  on_macos do
    on_arm do
      url "${BASE_URL}/${ASSETS[0]}"
      sha256 "${SHA_ARM_MAC}"
    end
    on_intel do
      url "${BASE_URL}/${ASSETS[1]}"
      sha256 "${SHA_INTEL_MAC}"
    end
  end

  on_linux do
    on_arm do
      url "${BASE_URL}/${ASSETS[2]}"
      sha256 "${SHA_ARM_LINUX}"
    end
    on_intel do
      url "${BASE_URL}/${ASSETS[3]}"
      sha256 "${SHA_INTEL_LINUX}"
    end
  end

  def install
    bin.install Dir["rivet-*/rivet"].first => "rivet"
  end

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

echo "Wrote ${OUT}"
echo "Next: copy to your tap repository as Formula/rivet.rb (see packaging/homebrew/README.md)."
